@causyne/agent 1.20.120 → 1.20.122
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 +3 -3
- package/package.json +1 -1
- package/src/acp/agentCatalog.js +81 -26
- package/src/acp/agentCatalog.ts +73 -29
- package/src/acp/client.js +210 -53
- package/src/acp/client.ts +202 -52
- package/src/acp/peerProfiles.js +55 -22
- package/src/acp/peerProfiles.ts +51 -22
- package/src/acp/protocol.js +37 -8
- package/src/acp/protocol.ts +30 -8
- package/src/acp/server.js +123 -25
- package/src/acp/server.ts +124 -24
- package/src/agent/errorClassifier.js +117 -0
- package/src/agent/errorClassifier.ts +165 -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 +33 -344
- package/src/agentLoop.ts +51 -352
- package/src/approvalGrants.js +19 -7
- package/src/approvalGrants.ts +20 -7
- package/src/approvalPolicy.js +48 -15
- package/src/approvalPolicy.ts +46 -15
- package/src/autoUpdate.js +116 -10
- package/src/autoUpdate.ts +149 -10
- package/src/browser/causyneBrowser.js +3 -2
- package/src/browser/causyneBrowser.ts +3 -2
- package/src/browser/searchProviders.js +1 -1
- package/src/browser/searchProviders.ts +1 -1
- package/src/cliMode.js +16 -2
- package/src/commands.js +10 -9
- package/src/config.js +288 -272
- package/src/config.ts +342 -0
- package/src/configVault.js +271 -0
- package/src/configVault.ts +273 -0
- package/src/continuum/compactor.js +2 -1
- package/src/continuum/compactor.ts +2 -1
- package/src/continuum/sanitizer.js +10 -3
- package/src/continuum/sanitizer.ts +9 -3
- package/src/continuum/ui/continuumPickerView.js +3 -2
- package/src/continuum/ui/continuumPickerView.ts +3 -2
- package/src/core/contextCompactor.js +70 -11
- package/src/core/contextCompactor.ts +83 -11
- package/src/cortex/vectorDb.js +26 -15
- package/src/cortex/vectorDb.ts +26 -16
- package/src/creative/liveBridge.js +7 -5
- package/src/creative/liveBridge.ts +7 -5
- package/src/creative/studioScripts.js +16 -5
- package/src/creative/studioScripts.ts +14 -5
- package/src/decisionPolicy.js +16 -4
- package/src/decisionPolicy.ts +14 -4
- package/src/documentEngine/antiSlopAuditor.js +10 -5
- package/src/documentEngine/antiSlopAuditor.ts +11 -5
- package/src/documentEngine/documentForge.js +47 -15
- package/src/documentEngine/documentForge.ts +43 -14
- package/src/dynamicCatalogue.js +42 -73
- package/src/dynamicCatalogue.ts +74 -60
- package/src/engines/design.js +2 -1
- package/src/engines/design.ts +2 -1
- package/src/engines/film.js +4 -4
- package/src/engines/film.ts +2 -2
- package/src/engines/light.js +2 -1
- package/src/engines/light.ts +2 -1
- package/src/engines/registry.js +1 -1
- package/src/engines/registry.ts +1 -1
- package/src/engines/reverseHarness.js +4 -3
- package/src/engines/reverseHarness.ts +4 -3
- package/src/entrypoint.js +77 -4
- package/src/headlessCli.js +305 -0
- package/src/headlessCli.ts +381 -0
- package/src/historyPruner.js +3 -2
- package/src/historyPruner.ts +3 -2
- package/src/hooks.js +3 -0
- package/src/hooks.ts +3 -0
- package/src/implementationPlan.js +21 -11
- package/src/implementationPlan.ts +21 -11
- package/src/infra/atomicWriter.js +4 -1
- package/src/infra/atomicWriter.ts +4 -1
- package/src/launchIntent.js +1 -1
- package/src/launchIntent.ts +1 -1
- 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/memory/scopedFacts.js +1 -1
- package/src/memory/scopedFacts.ts +1 -1
- package/src/memory/symbolFolder.js +1 -1
- package/src/memory/symbolFolder.ts +1 -1
- package/src/modelRouter.js +1 -1
- package/src/modelRouter.ts +1 -1
- package/src/observer/evidence.js +10 -4
- package/src/observer/evidence.ts +10 -4
- package/src/osKeychain.js +263 -0
- package/src/osKeychain.ts +287 -0
- package/src/perception.js +3 -2
- package/src/perception.ts +3 -2
- package/src/planCache.js +2 -2
- package/src/planCache.ts +2 -2
- package/src/pluginsFactory/pluginsFactory.js +19 -11
- package/src/pluginsFactory/pluginsFactory.ts +18 -11
- package/src/promptMentions.js +2 -2
- package/src/promptMentions.ts +2 -2
- package/src/providers/acp.js +1 -1
- package/src/providers/acp.ts +1 -1
- package/src/providers/anthropic.js +328 -385
- package/src/providers/anthropic.ts +386 -0
- package/src/providers/antigravity.js +10 -4
- package/src/providers/antigravity.ts +10 -4
- package/src/providers/base.js +221 -319
- package/src/providers/base.ts +340 -0
- package/src/providers/byokHttp.js +397 -0
- package/src/providers/byokHttp.ts +497 -0
- package/src/providers/byokStream.js +748 -0
- package/src/providers/byokStream.ts +863 -0
- package/src/providers/dashscope-byok.js +98 -81
- package/src/providers/dashscope-byok.ts +114 -0
- package/src/providers/deepseek.js +74 -64
- package/src/providers/deepseek.ts +99 -0
- package/src/providers/factory.js +35 -28
- package/src/providers/factory.ts +40 -0
- package/src/providers/gemini.js +229 -253
- package/src/providers/gemini.ts +261 -0
- package/src/providers/loopGuard.js +9 -5
- package/src/providers/loopGuard.ts +10 -5
- package/src/providers/moonshot.js +71 -64
- package/src/providers/moonshot.ts +93 -0
- package/src/providers/muse.js +82 -152
- package/src/providers/muse.ts +122 -0
- package/src/providers/ollama.js +116 -93
- package/src/providers/ollama.ts +135 -0
- package/src/providers/openai-compatible.js +114 -65
- package/src/providers/openai-compatible.ts +139 -0
- package/src/providers/openai.js +22 -15
- package/src/providers/openai.ts +30 -0
- package/src/providers/openrouter.js +194 -98
- package/src/providers/openrouter.ts +202 -97
- package/src/providers/pi.js +6 -0
- package/src/providers/pi.ts +6 -0
- package/src/providers/qwen-byok.js +97 -71
- package/src/providers/qwen-byok.ts +113 -0
- package/src/providers/toolContracts.js +40 -14
- package/src/providers/toolContracts.ts +35 -14
- package/src/providers/wireNormalizer.js +78 -11
- package/src/providers/wireNormalizer.ts +68 -12
- package/src/providers/xai.js +74 -64
- package/src/providers/xai.ts +97 -0
- package/src/reliability/assetEvidence.js +4 -2
- package/src/reliability/assetEvidence.ts +4 -2
- package/src/sandbox.js +486 -530
- package/src/sandbox.ts +552 -0
- package/src/sandboxPolicy.js +1287 -0
- package/src/sandboxPolicy.ts +1381 -0
- package/src/sessionJournal.js +55 -3
- package/src/sessionJournal.ts +58 -3
- package/src/skills/skillResourceSafety.js +19 -8
- package/src/skills/skillResourceSafety.ts +16 -7
- package/src/skillsManager.js +3 -3
- package/src/skillsManager.ts +3 -3
- package/src/smartToolsUse.js +28 -4
- package/src/smartToolsUse.ts +29 -7
- package/src/stallGuard.js +45 -22
- package/src/stallGuard.ts +46 -22
- package/src/subagentJournal.js +6 -4
- package/src/subagentJournal.ts +6 -4
- package/src/textDiff.js +6 -1
- package/src/textDiff.ts +6 -1
- package/src/timeMachine.js +7 -1
- package/src/timeMachine.ts +7 -1
- package/src/tokenTracker.js +43 -28
- package/src/tokenTracker.ts +44 -30
- package/src/toolPacks.js +3 -1
- package/src/toolPacks.ts +3 -1
- package/src/tools/archive.js +245 -35
- package/src/tools/archive.ts +244 -35
- package/src/tools/computerUse.js +7 -3
- package/src/tools/computerUse.ts +7 -3
- package/src/tools/creativeApps.js +13 -8
- package/src/tools/creativeApps.ts +22 -9
- package/src/tools/deferredMcpSearch.js +26 -14
- package/src/tools/deferredMcpSearch.ts +26 -14
- package/src/tools/desktopOpen.js +69 -10
- package/src/tools/desktopOpen.ts +70 -11
- package/src/tools/documentForge.js +167 -82
- package/src/tools/documentForge.ts +169 -84
- package/src/tools/fsEdit.js +101 -30
- package/src/tools/fsEdit.ts +105 -32
- package/src/tools/fsFind.js +8 -5
- package/src/tools/fsFind.ts +7 -4
- package/src/tools/fsRead.js +119 -13
- package/src/tools/fsRead.ts +124 -13
- package/src/tools/fsWrite.js +17 -5
- package/src/tools/fsWrite.ts +17 -7
- package/src/tools/generateMediaViaApi.js +82 -19
- package/src/tools/generateMediaViaApi.ts +80 -19
- package/src/tools/memoryRecall.js +62 -11
- package/src/tools/memoryRecall.ts +70 -13
- package/src/tools/memoryWrite.js +27 -14
- package/src/tools/memoryWrite.ts +30 -14
- package/src/tools/multiEdit.js +100 -30
- package/src/tools/multiEdit.ts +104 -32
- package/src/tools/nativeEngine.js +33 -18
- package/src/tools/nativeEngine.ts +31 -18
- package/src/tools/openSourceToolProvisioner.js +49 -14
- package/src/tools/openSourceToolProvisioner.ts +54 -15
- package/src/tools/osSandbox.js +513 -0
- package/src/tools/osSandbox.ts +588 -0
- package/src/tools/payloadSanitizer.js +40 -8
- package/src/tools/payloadSanitizer.ts +39 -8
- package/src/tools/peerAgent.js +96 -34
- package/src/tools/peerAgent.ts +114 -37
- package/src/tools/persistentShell.js +8 -3
- package/src/tools/pluginsFactory.js +38 -6
- package/src/tools/pluginsFactory.ts +42 -6
- package/src/tools/readNativeSkill.js +10 -8
- package/src/tools/readNativeSkill.ts +10 -8
- package/src/tools/requestDecision.js +10 -3
- package/src/tools/requestDecision.ts +10 -3
- package/src/tools/resolveAutomator.js +91 -17
- package/src/tools/resolveAutomator.ts +102 -17
- package/src/tools/reverseEngineering.js +168 -41
- package/src/tools/reverseEngineering.ts +161 -41
- package/src/tools/subprocessEnv.js +197 -0
- package/src/tools/subprocessEnv.ts +212 -0
- package/src/tools/sysRun.js +108 -35
- package/src/tools/sysRun.ts +119 -31
- package/src/tools/toolDispatch.js +24 -1
- package/src/tools/toolDispatch.ts +21 -1
- package/src/tools/toolOutputStore.js +62 -23
- package/src/tools/toolOutputStore.ts +56 -23
- package/src/tools/toolScanner.js +13 -10
- package/src/tools/toolScanner.ts +13 -10
- package/src/tools/toolSelfRepair.js +94 -28
- package/src/tools/toolSelfRepair.ts +96 -28
- package/src/tools/uiForge.js +71 -6
- package/src/tools/uiForge.ts +74 -6
- package/src/tools/viewImage.js +62 -17
- package/src/tools/viewImage.ts +57 -12
- package/src/tools/visionInspector.js +15 -3
- package/src/tools/visionInspector.ts +15 -3
- package/src/tools/walkerSafety.js +2 -0
- package/src/tools/walkerSafety.ts +1 -0
- package/src/tools/webFetch.js +105 -10
- package/src/tools/webFetch.ts +105 -11
- package/src/tui/banner.js +3 -2
- package/src/tui/banner.ts +3 -2
- package/src/tui/consoleGuard.js +12 -4
- package/src/tui/consoleGuard.ts +9 -4
- package/src/tui/messageInteraction.js +2 -3
- package/src/tui/messageInteraction.ts +2 -3
- package/src/tui/modelPicker.js +1 -0
- package/src/tui/modelPicker.ts +1 -0
- package/src/tui/overlay.js +3 -1
- package/src/tui/overlay.ts +3 -1
- package/src/tui/sessionPicker.js +3 -2
- package/src/tui/sessionPicker.ts +3 -2
- package/src/tui/sessionPickerView.js +7 -1
- package/src/tui/sessionPickerView.ts +6 -1
- package/src/tui/toolOutputNormalizer.js +2 -3
- package/src/tui/toolOutputNormalizer.ts +4 -3
- package/src/tui/viewport.js +4 -4
- package/src/tui/viewport.ts +5 -5
- package/src/tui/workspaceIdentity.js +2 -1
- package/src/tui/workspaceIdentity.ts +2 -1
- package/src/uncertainty.js +8 -3
- package/src/uncertainty.ts +8 -3
- package/src/utils/paths.js +8 -5
- package/src/utils/paths.ts +9 -7
- package/src/vfeTracker.js +9 -3
- package/src/vfeTracker.ts +9 -3
- package/src/config.d.ts +0 -2
- package/src/providers/base.d.ts +0 -94
- package/src/providers/factory.d.ts +0 -1
- package/src/sandbox.d.ts +0 -1
|
@@ -0,0 +1,273 @@
|
|
|
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
|
+
const MAX_SECRET_HEX_CHARS = 1_048_576;
|
|
28
|
+
const STRICT_HEX_PATTERN = /^[0-9a-fA-F]+$/;
|
|
29
|
+
|
|
30
|
+
export function isEncryptedVaultSecret(value: unknown): value is string {
|
|
31
|
+
return typeof value === 'string' && value.startsWith(VAULT_ENC_PREFIX);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function ensureVaultDir(dir: string): void {
|
|
35
|
+
if (typeof dir !== 'string' || !dir.trim() || dir.includes('\0')) {
|
|
36
|
+
throw new Error('Invalid vault directory path');
|
|
37
|
+
}
|
|
38
|
+
const resolved = path.resolve(dir);
|
|
39
|
+
if (!fs.existsSync(resolved)) {
|
|
40
|
+
fs.mkdirSync(resolved, { recursive: true, mode: 0o700 });
|
|
41
|
+
} else {
|
|
42
|
+
const stat = fs.lstatSync(resolved);
|
|
43
|
+
if (stat.isSymbolicLink() || !stat.isDirectory()) {
|
|
44
|
+
throw new Error('Refusing to use symlink or non-directory as vault directory');
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
if (process.platform !== 'win32') {
|
|
48
|
+
try {
|
|
49
|
+
fs.chmodSync(resolved, 0o700);
|
|
50
|
+
} catch {
|
|
51
|
+
// Best-effort permission tightening on platforms that restrict chmod
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Atomically writes a secret-bearing file (`config.json` or `.vault_key`) using
|
|
58
|
+
* a unique sibling temporary file with mode `0o600` followed by atomic rename.
|
|
59
|
+
*/
|
|
60
|
+
export function atomicWriteSecretFileSync(targetPath: string, content: string | Buffer): void {
|
|
61
|
+
if (typeof targetPath !== 'string' || !targetPath.trim() || targetPath.includes('\0')) {
|
|
62
|
+
throw new Error('Invalid secret target file path');
|
|
63
|
+
}
|
|
64
|
+
const resolved = path.resolve(targetPath);
|
|
65
|
+
const dir = path.dirname(resolved);
|
|
66
|
+
ensureVaultDir(dir);
|
|
67
|
+
try {
|
|
68
|
+
const existing = fs.lstatSync(resolved);
|
|
69
|
+
if (existing.isSymbolicLink() || !existing.isFile()) {
|
|
70
|
+
throw new Error('Refusing to overwrite symlink or non-regular secret file');
|
|
71
|
+
}
|
|
72
|
+
} catch (err: unknown) {
|
|
73
|
+
const code = typeof err === 'object' && err !== null && 'code' in err ? String(err.code) : '';
|
|
74
|
+
if (code !== 'ENOENT') throw err;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const suffix = `${process.pid}.${crypto.randomBytes(6).toString('hex')}`;
|
|
78
|
+
const tempPath = path.join(dir, `.${path.basename(resolved)}.${suffix}.tmp`);
|
|
79
|
+
|
|
80
|
+
try {
|
|
81
|
+
const payload = typeof content === 'string' ? Buffer.from(content, 'utf8') : content;
|
|
82
|
+
const fd = fs.openSync(tempPath, fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_WRONLY, 0o600);
|
|
83
|
+
try {
|
|
84
|
+
fs.writeSync(fd, payload, 0, payload.length);
|
|
85
|
+
fs.fsyncSync(fd);
|
|
86
|
+
} finally {
|
|
87
|
+
fs.closeSync(fd);
|
|
88
|
+
}
|
|
89
|
+
if (process.platform !== 'win32') {
|
|
90
|
+
try {
|
|
91
|
+
fs.chmodSync(tempPath, 0o600);
|
|
92
|
+
} catch {
|
|
93
|
+
// Ignore chmod errors on non-POSIX mounts
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
fs.renameSync(tempPath, resolved);
|
|
97
|
+
if (process.platform !== 'win32') {
|
|
98
|
+
try {
|
|
99
|
+
fs.chmodSync(resolved, 0o600);
|
|
100
|
+
} catch {
|
|
101
|
+
// Ignore chmod errors on non-POSIX mounts
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
} catch (err: unknown) {
|
|
105
|
+
try {
|
|
106
|
+
if (fs.existsSync(tempPath)) fs.unlinkSync(tempPath);
|
|
107
|
+
} catch {
|
|
108
|
+
// Ignore temp cleanup failure
|
|
109
|
+
}
|
|
110
|
+
throw err;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Loads or atomically initializes the 256-bit local vault key with `0o600` permissions.
|
|
116
|
+
* When `CAUSYNE_KEYCHAIN=on|auto|strict` is enabled, uses the OS Keychain backend
|
|
117
|
+
* first (migrating an existing file key if present) and fails closed on `strict`.
|
|
118
|
+
*/
|
|
119
|
+
export function getOrCreateVaultKey(
|
|
120
|
+
keyFilePath: string,
|
|
121
|
+
keychainOptions?: KeychainSpawnOptions
|
|
122
|
+
): Buffer {
|
|
123
|
+
const resolved = path.resolve(keyFilePath);
|
|
124
|
+
const vaultDir = path.dirname(resolved);
|
|
125
|
+
ensureVaultDir(vaultDir);
|
|
126
|
+
|
|
127
|
+
const keychainMode = resolveKeychainMode(keychainOptions?.env ?? process.env);
|
|
128
|
+
if (keychainMode !== 'off') {
|
|
129
|
+
const fromKeychain = loadVaultKeyFromKeychain(vaultDir, keychainOptions);
|
|
130
|
+
if (fromKeychain && fromKeychain.length === VAULT_KEY_BYTES) {
|
|
131
|
+
return fromKeychain;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// If a file key already exists, migrate it cleanly into the OS Keychain
|
|
135
|
+
if (fs.existsSync(resolved)) {
|
|
136
|
+
const stat = fs.lstatSync(resolved);
|
|
137
|
+
if (stat.isSymbolicLink() || !stat.isFile()) {
|
|
138
|
+
throw new Error('Refusing to read symlink or non-regular vault key file.');
|
|
139
|
+
}
|
|
140
|
+
const existingFileKey = fs.readFileSync(resolved);
|
|
141
|
+
if (existingFileKey.length === VAULT_KEY_BYTES) {
|
|
142
|
+
const stored = saveVaultKeyToKeychain(vaultDir, existingFileKey, keychainOptions);
|
|
143
|
+
if (stored || keychainMode !== 'strict') {
|
|
144
|
+
return existingFileKey;
|
|
145
|
+
}
|
|
146
|
+
throw new Error('Strict OS keychain mode requested (CAUSYNE_KEYCHAIN=strict) but storing the vault key failed.');
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// Generate a fresh key and persist into OS Keychain
|
|
151
|
+
const generated = crypto.randomBytes(VAULT_KEY_BYTES);
|
|
152
|
+
if (saveVaultKeyToKeychain(vaultDir, generated, keychainOptions)) {
|
|
153
|
+
return generated;
|
|
154
|
+
}
|
|
155
|
+
if (keychainMode === 'strict') {
|
|
156
|
+
throw new Error('Strict OS keychain mode requested (CAUSYNE_KEYCHAIN=strict) but OS keychain storage is unavailable.');
|
|
157
|
+
}
|
|
158
|
+
// Non-strict (`on`/`auto`) degrades cleanly to atomic 0600 file storage below
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
if (fs.existsSync(resolved)) {
|
|
162
|
+
const stat = fs.lstatSync(resolved);
|
|
163
|
+
if (stat.isSymbolicLink() || !stat.isFile()) {
|
|
164
|
+
throw new Error('Refusing to read symlink or non-regular vault key file.');
|
|
165
|
+
}
|
|
166
|
+
if (process.platform !== 'win32') {
|
|
167
|
+
try {
|
|
168
|
+
fs.chmodSync(resolved, 0o600);
|
|
169
|
+
} catch {
|
|
170
|
+
// Ignore chmod errors on non-POSIX mounts
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
const existing = fs.readFileSync(resolved);
|
|
174
|
+
if (existing.length !== VAULT_KEY_BYTES) {
|
|
175
|
+
throw new Error(`Invalid vault key length (${existing.length} bytes; expected ${VAULT_KEY_BYTES}).`);
|
|
176
|
+
}
|
|
177
|
+
return existing;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const freshKey = crypto.randomBytes(VAULT_KEY_BYTES);
|
|
181
|
+
try {
|
|
182
|
+
// Exclusive create first so concurrent startups do not clobber each other's key
|
|
183
|
+
fs.writeFileSync(resolved, freshKey, { mode: 0o600, flag: 'wx' });
|
|
184
|
+
if (process.platform !== 'win32') {
|
|
185
|
+
try {
|
|
186
|
+
fs.chmodSync(resolved, 0o600);
|
|
187
|
+
} catch {
|
|
188
|
+
// Ignore chmod errors
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
return freshKey;
|
|
192
|
+
} catch (err: unknown) {
|
|
193
|
+
const code = typeof err === 'object' && err !== null && 'code' in err ? String(err.code) : '';
|
|
194
|
+
if (code === 'EEXIST') {
|
|
195
|
+
const stat = fs.lstatSync(resolved);
|
|
196
|
+
if (stat.isSymbolicLink() || !stat.isFile()) {
|
|
197
|
+
throw new Error('Refusing to read symlink or non-regular vault key file.');
|
|
198
|
+
}
|
|
199
|
+
if (process.platform !== 'win32') {
|
|
200
|
+
try {
|
|
201
|
+
fs.chmodSync(resolved, 0o600);
|
|
202
|
+
} catch {
|
|
203
|
+
// Ignore chmod errors
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
const raced = fs.readFileSync(resolved);
|
|
207
|
+
if (raced.length === VAULT_KEY_BYTES) return raced;
|
|
208
|
+
}
|
|
209
|
+
throw err;
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* Encrypts a plaintext secret using AES-256-GCM with a NIST-standard 12-byte IV.
|
|
215
|
+
*/
|
|
216
|
+
export function encryptVaultSecret(text: string, keyFilePath: string): string {
|
|
217
|
+
if (typeof text !== 'string' || !text) return text;
|
|
218
|
+
if (isEncryptedVaultSecret(text)) return text;
|
|
219
|
+
const key = getOrCreateVaultKey(keyFilePath);
|
|
220
|
+
try {
|
|
221
|
+
const iv = crypto.randomBytes(VAULT_GCM_IV_BYTES);
|
|
222
|
+
const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
|
|
223
|
+
let encrypted = cipher.update(text, 'utf8', 'hex');
|
|
224
|
+
encrypted += cipher.final('hex');
|
|
225
|
+
const authTag = cipher.getAuthTag().toString('hex');
|
|
226
|
+
return `${VAULT_ENC_PREFIX}${iv.toString('hex')}:${authTag}:${encrypted}`;
|
|
227
|
+
} finally {
|
|
228
|
+
key.fill(0);
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* Decrypts an `ENC:` secret produced with either the standard 12-byte GCM IV
|
|
234
|
+
* or legacy 16-byte GCM IV. Returns empty string on authentication failure.
|
|
235
|
+
*/
|
|
236
|
+
export function decryptVaultSecret(encryptedText: string, keyFilePath: string): string {
|
|
237
|
+
if (typeof encryptedText !== 'string' || !encryptedText) return '';
|
|
238
|
+
if (!isEncryptedVaultSecret(encryptedText)) return encryptedText;
|
|
239
|
+
if (encryptedText.length > MAX_SECRET_HEX_CHARS) return '';
|
|
240
|
+
let key: Buffer | null = null;
|
|
241
|
+
try {
|
|
242
|
+
const parts = encryptedText.split(':');
|
|
243
|
+
if (parts.length !== 4) return '';
|
|
244
|
+
const ivHex = parts[1] ?? '';
|
|
245
|
+
const authTagHex = parts[2] ?? '';
|
|
246
|
+
const ciphertextHex = parts[3] ?? '';
|
|
247
|
+
if (
|
|
248
|
+
!STRICT_HEX_PATTERN.test(ivHex) ||
|
|
249
|
+
!STRICT_HEX_PATTERN.test(authTagHex) ||
|
|
250
|
+
(ciphertextHex.length > 0 && (ciphertextHex.length % 2 !== 0 || !STRICT_HEX_PATTERN.test(ciphertextHex)))
|
|
251
|
+
) {
|
|
252
|
+
return '';
|
|
253
|
+
}
|
|
254
|
+
if (
|
|
255
|
+
(ivHex.length !== VAULT_GCM_IV_BYTES * 2 && ivHex.length !== VAULT_LEGACY_GCM_IV_BYTES * 2) ||
|
|
256
|
+
authTagHex.length !== VAULT_GCM_AUTH_TAG_BYTES * 2
|
|
257
|
+
) {
|
|
258
|
+
return '';
|
|
259
|
+
}
|
|
260
|
+
const iv = Buffer.from(ivHex, 'hex');
|
|
261
|
+
const authTag = Buffer.from(authTagHex, 'hex');
|
|
262
|
+
key = getOrCreateVaultKey(keyFilePath);
|
|
263
|
+
const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
|
|
264
|
+
decipher.setAuthTag(authTag);
|
|
265
|
+
let decrypted = decipher.update(ciphertextHex, 'hex', 'utf8');
|
|
266
|
+
decrypted += decipher.final('utf8');
|
|
267
|
+
return decrypted;
|
|
268
|
+
} catch {
|
|
269
|
+
return '';
|
|
270
|
+
} finally {
|
|
271
|
+
if (key) key.fill(0);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
@@ -15,7 +15,8 @@ export function compactContinuumMessages(messages, options = {}) {
|
|
|
15
15
|
const rootMessage = rootIndex !== -1
|
|
16
16
|
? messages[rootIndex]
|
|
17
17
|
: { role: 'user', content: 'Initial user turn' };
|
|
18
|
-
const
|
|
18
|
+
const safeRecent = Number.isFinite(recentTurns) ? Math.max(0, Math.min(messages.length, Math.floor(recentTurns))) : 12;
|
|
19
|
+
const recentStart = Math.max(0, messages.length - safeRecent);
|
|
19
20
|
const recent = messages.slice(recentStart);
|
|
20
21
|
// If the root intent is already within the recent window, simply return recent
|
|
21
22
|
if (rootIndex !== -1 && rootIndex >= recentStart) {
|
|
@@ -32,7 +32,8 @@ export function compactContinuumMessages(
|
|
|
32
32
|
? messages[rootIndex]!
|
|
33
33
|
: { role: 'user', content: 'Initial user turn' };
|
|
34
34
|
|
|
35
|
-
const
|
|
35
|
+
const safeRecent = Number.isFinite(recentTurns) ? Math.max(0, Math.min(messages.length, Math.floor(recentTurns))) : 12;
|
|
36
|
+
const recentStart = Math.max(0, messages.length - safeRecent);
|
|
36
37
|
const recent = messages.slice(recentStart);
|
|
37
38
|
|
|
38
39
|
// If the root intent is already within the recent window, simply return recent
|
|
@@ -39,12 +39,19 @@ export function cleanUserText(text) {
|
|
|
39
39
|
export function cleanAssistantText(text, maxChars = 2000) {
|
|
40
40
|
if (!text)
|
|
41
41
|
return '';
|
|
42
|
+
const limit = Number.isFinite(maxChars) ? Math.max(0, Math.floor(maxChars)) : 2000;
|
|
43
|
+
if (limit === 0)
|
|
44
|
+
return '';
|
|
42
45
|
const str = String(text).trim();
|
|
43
|
-
|
|
46
|
+
const chars = Array.from(str);
|
|
47
|
+
if (chars.length <= limit) {
|
|
44
48
|
return str;
|
|
45
49
|
}
|
|
46
|
-
|
|
47
|
-
|
|
50
|
+
if (limit === 1) {
|
|
51
|
+
return chars[0] ?? '';
|
|
52
|
+
}
|
|
53
|
+
const half = Math.floor(limit / 2);
|
|
54
|
+
return `${chars.slice(0, half).join('')}\n\n... [output condensed for context efficiency] ...\n\n${chars.slice(-half).join('')}`;
|
|
48
55
|
}
|
|
49
56
|
/** Extract a clean, meaningful title from the first user request. */
|
|
50
57
|
export function deriveSessionTitle(firstPrompt, fallback = 'Untitled Session') {
|
|
@@ -43,12 +43,18 @@ export function cleanUserText(text: unknown): string {
|
|
|
43
43
|
/** Summarize and truncate excessive tool dump text while preserving answer & rationale. */
|
|
44
44
|
export function cleanAssistantText(text: unknown, maxChars = 2000): string {
|
|
45
45
|
if (!text) return '';
|
|
46
|
+
const limit = Number.isFinite(maxChars) ? Math.max(0, Math.floor(maxChars)) : 2000;
|
|
47
|
+
if (limit === 0) return '';
|
|
46
48
|
const str = String(text).trim();
|
|
47
|
-
|
|
49
|
+
const chars = Array.from(str);
|
|
50
|
+
if (chars.length <= limit) {
|
|
48
51
|
return str;
|
|
49
52
|
}
|
|
50
|
-
|
|
51
|
-
|
|
53
|
+
if (limit === 1) {
|
|
54
|
+
return chars[0] ?? '';
|
|
55
|
+
}
|
|
56
|
+
const half = Math.floor(limit / 2);
|
|
57
|
+
return `${chars.slice(0, half).join('')}\n\n... [output condensed for context efficiency] ...\n\n${chars.slice(-half).join('')}`;
|
|
52
58
|
}
|
|
53
59
|
|
|
54
60
|
/** Extract a clean, meaningful title from the first user request. */
|
|
@@ -62,7 +62,8 @@ function pairedRow(left, right, columns) {
|
|
|
62
62
|
return title + ' '.repeat(Math.max(1, width - visibleWidth(title) - rightWidth)) + right;
|
|
63
63
|
}
|
|
64
64
|
function sourceName(value) {
|
|
65
|
-
|
|
65
|
+
const platformName = Object.hasOwn(PLATFORM_NAMES, value.sourcePlatform) ? PLATFORM_NAMES[value.sourcePlatform] : undefined;
|
|
66
|
+
return clean(value.sourceLabel) || platformName || 'Other';
|
|
66
67
|
}
|
|
67
68
|
/**
|
|
68
69
|
* Group by agent with recency inside each source. A stable tie-breaker means
|
|
@@ -201,7 +202,7 @@ export class ContinuumPickerLayer extends SelectLayer {
|
|
|
201
202
|
const h = Number.isFinite(height) ? Math.max(1, Math.min(200, Math.floor(height))) : 1;
|
|
202
203
|
const rows = [];
|
|
203
204
|
const scope = this.scope;
|
|
204
|
-
const label = scope === 'all' ? 'ALL SOURCES' : PLATFORM_NAMES[scope];
|
|
205
|
+
const label = scope === 'all' ? 'ALL SOURCES' : (Object.hasOwn(PLATFORM_NAMES, scope) ? PLATFORM_NAMES[scope] : 'Other');
|
|
205
206
|
const filtered = this.list.filtered;
|
|
206
207
|
const count = filtered.length;
|
|
207
208
|
const total = this.items.length;
|
|
@@ -96,7 +96,8 @@ function pairedRow(left: string, right: string, columns: number): string {
|
|
|
96
96
|
}
|
|
97
97
|
|
|
98
98
|
function sourceName(value: ContinuumSessionSummary): string {
|
|
99
|
-
|
|
99
|
+
const platformName = Object.hasOwn(PLATFORM_NAMES, value.sourcePlatform) ? PLATFORM_NAMES[value.sourcePlatform] : undefined;
|
|
100
|
+
return clean(value.sourceLabel) || platformName || 'Other';
|
|
100
101
|
}
|
|
101
102
|
|
|
102
103
|
/**
|
|
@@ -262,7 +263,7 @@ export class ContinuumPickerLayer extends SelectLayer {
|
|
|
262
263
|
const h = Number.isFinite(height) ? Math.max(1, Math.min(200, Math.floor(height))) : 1;
|
|
263
264
|
const rows: string[] = [];
|
|
264
265
|
const scope = this.scope;
|
|
265
|
-
const label = scope === 'all' ? 'ALL SOURCES' : PLATFORM_NAMES[scope];
|
|
266
|
+
const label = scope === 'all' ? 'ALL SOURCES' : (Object.hasOwn(PLATFORM_NAMES, scope) ? PLATFORM_NAMES[scope] : 'Other');
|
|
266
267
|
const filtered = this.list.filtered;
|
|
267
268
|
const count = filtered.length;
|
|
268
269
|
const total = this.items.length;
|
|
@@ -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)`,
|