@causyne/agent 1.20.13 → 1.20.14
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/SmartTools.js +33 -0
- package/src/SmartTools.ts +37 -0
- package/src/acp/client.js +157 -4
- package/src/acp/client.ts +152 -5
- package/src/agentLoop.js +857 -178
- package/src/agentLoop.ts +865 -183
- package/src/browser/browserRuntime.js +8 -1
- package/src/browser/browserRuntime.ts +8 -1
- package/src/browser/causyneBrowser.js +20 -4
- package/src/browser/causyneBrowser.ts +20 -4
- package/src/browser/urlPolicy.js +35 -0
- package/src/browser/urlPolicy.ts +34 -0
- package/src/cliMode.js +6 -2
- package/src/commands.js +14 -0
- package/src/contextManager.d.ts +1 -0
- package/src/core/contextCompactor.js +277 -0
- package/src/core/contextCompactor.ts +353 -0
- package/src/decideTools.js +157 -0
- package/src/decideTools.ts +195 -0
- package/src/decisionPolicy.js +5 -3
- package/src/decisionPolicy.ts +5 -3
- package/src/implementationPlan.js +284 -0
- package/src/implementationPlan.ts +275 -0
- package/src/observer/coldObserver.js +10 -4
- package/src/observer/coldObserver.ts +15 -7
- package/src/observer/evidence.js +11 -5
- package/src/observer/evidence.ts +13 -6
- package/src/observer.js +196 -0
- package/src/observer.ts +287 -0
- package/src/providers/acp.js +362 -109
- package/src/providers/acp.ts +359 -111
- package/src/providers/antigravity.js +133 -105
- package/src/providers/antigravity.ts +130 -109
- package/src/providers/base.d.ts +3 -0
- package/src/providers/budgetEnforcer.js +13 -0
- package/src/providers/budgetEnforcer.ts +13 -3
- package/src/provisioning/capabilityProvisioner.js +14 -10
- package/src/sandbox.js +4 -2
- package/src/saveTools.js +146 -0
- package/src/saveTools.ts +169 -0
- package/src/session/cachePressure.js +77 -0
- package/src/session/cachePressure.ts +122 -0
- package/src/smartToolsUse.js +69 -12
- package/src/smartToolsUse.ts +103 -12
- package/src/taskShape.js +7 -7
- package/src/taskShape.ts +7 -7
- package/src/timeMachine.js +55 -20
- package/src/timeMachine.ts +64 -20
- package/src/toolPacks.js +217 -310
- package/src/toolPacks.ts +505 -0
- package/src/tools/deferredMcpSearch.js +21 -13
- package/src/tools/deferredMcpSearch.ts +23 -15
- package/src/tools/updatePlan.js +2 -2
- package/src/tools/updatePlan.ts +2 -2
- package/src/toolsList.js +203 -0
- package/src/toolsList.ts +224 -0
- package/src/tui/chatRenderer.js +49 -14
- package/src/tui/codeStreamRenderer.js +16 -5
- package/src/tui/codeStreamRenderer.ts +14 -4
- package/src/tui/prompt.js +4 -2
- package/src/tui/sessionSidebar.js +10 -2
- package/src/tui/sessionSidebar.ts +10 -3
- package/src/tui/stageSurface.js +27 -1
- package/src/tui/text.d.ts +1 -0
- package/src/tui/turnRail.js +274 -0
- package/src/tui/turnRail.ts +334 -0
- package/src/types/contracts.ts +103 -0
- package/src/verificationPlan.js +141 -0
- package/src/verificationPlan.ts +166 -0
- package/src/toolPacks.d.ts +0 -10
|
@@ -323,9 +323,16 @@ export function isBrowserRuntimeInstalled() {
|
|
|
323
323
|
const candidates = configured
|
|
324
324
|
? [resolveCandidateExecutablePath(path.resolve(configured))]
|
|
325
325
|
: candidateExecutables().map(resolveCandidateExecutablePath);
|
|
326
|
+
// Match launch-time discovery: Chromium is a supported installed runtime
|
|
327
|
+
// too. The former Camoufox-only check suppressed host verification even
|
|
328
|
+
// when resolveBrowserRuntime could launch the installed Chrome browser.
|
|
329
|
+
if (configured && /(?:chrome|chromium|msedge)(?:\.exe)?$/i.test(path.basename(configured))) {
|
|
330
|
+
return resolveChromiumRuntime(path.resolve(configured)) !== null;
|
|
331
|
+
}
|
|
326
332
|
return candidates.some(candidate => {
|
|
327
333
|
try {
|
|
328
|
-
|
|
334
|
+
assertExecutable(candidate);
|
|
335
|
+
return Boolean(findResourceDirectory(candidate, realpathSync(candidate)));
|
|
329
336
|
}
|
|
330
337
|
catch {
|
|
331
338
|
return false;
|
|
@@ -380,9 +380,16 @@ export function isBrowserRuntimeInstalled(): boolean {
|
|
|
380
380
|
const candidates = configured
|
|
381
381
|
? [resolveCandidateExecutablePath(path.resolve(configured))]
|
|
382
382
|
: candidateExecutables().map(resolveCandidateExecutablePath);
|
|
383
|
+
// Match launch-time discovery: Chromium is a supported installed runtime
|
|
384
|
+
// too. The former Camoufox-only check suppressed host verification even
|
|
385
|
+
// when resolveBrowserRuntime could launch the installed Chrome browser.
|
|
386
|
+
if (configured && /(?:chrome|chromium|msedge)(?:\.exe)?$/i.test(path.basename(configured))) {
|
|
387
|
+
return resolveChromiumRuntime(path.resolve(configured)) !== null;
|
|
388
|
+
}
|
|
383
389
|
return candidates.some(candidate => {
|
|
384
390
|
try {
|
|
385
|
-
|
|
391
|
+
assertExecutable(candidate);
|
|
392
|
+
return Boolean(findResourceDirectory(candidate, realpathSync(candidate)));
|
|
386
393
|
} catch {
|
|
387
394
|
return false;
|
|
388
395
|
}
|
|
@@ -5,7 +5,7 @@ import path from 'node:path';
|
|
|
5
5
|
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
6
6
|
import { capabilityDirectory, ensureCapability, loadCapabilityPackage } from '../provisioning/capabilityProvisioner.js';
|
|
7
7
|
import { resolveBrowserRuntime } from './browserRuntime.js';
|
|
8
|
-
import { assertPublicWebUrl } from './urlPolicy.js';
|
|
8
|
+
import { assertPublicWebUrl, assertBrowserNavigableUrl } from './urlPolicy.js';
|
|
9
9
|
import { windowSnapshot } from './snapshotWindow.js';
|
|
10
10
|
const NAVIGATION_TIMEOUT_MS = 30_000;
|
|
11
11
|
const ACTION_TIMEOUT_MS = 12_000;
|
|
@@ -677,7 +677,7 @@ export class CausyneBrowser {
|
|
|
677
677
|
this.resolveRuntime = options.resolveRuntime ?? resolveBrowserRuntime;
|
|
678
678
|
this.profileDirectory = path.resolve(options.profileDirectory ?? path.join(capabilityDirectory(), 'browser-profile'));
|
|
679
679
|
this.visible = options.visible ?? process.env.CAUSYNE_BROWSER_VISIBLE === '1';
|
|
680
|
-
this.validateUrl = options.validateUrl ??
|
|
680
|
+
this.validateUrl = options.validateUrl ?? assertBrowserNavigableUrl;
|
|
681
681
|
}
|
|
682
682
|
setWorkspace(workspace) {
|
|
683
683
|
if (workspace && typeof workspace === 'string') {
|
|
@@ -801,9 +801,16 @@ export class CausyneBrowser {
|
|
|
801
801
|
if (runtime.engine === 'chromium') {
|
|
802
802
|
const engine = await loadCapabilityPackage('playwright-core');
|
|
803
803
|
const profile = path.join(this.profileDirectory, 'chromium');
|
|
804
|
-
|
|
804
|
+
const chromiumArgs = [
|
|
805
|
+
'--enable-webgl',
|
|
806
|
+
'--use-gl=angle',
|
|
807
|
+
...(process.platform === 'darwin' ? ['--use-angle=metal'] : ['--use-gl=swiftshader']),
|
|
808
|
+
'--ignore-gpu-blocklist',
|
|
809
|
+
'--enable-gpu-rasterization'
|
|
810
|
+
];
|
|
805
811
|
this.session = await engine.chromium.launchPersistentContext(profile, {
|
|
806
812
|
executablePath: runtime.executablePath, headless: !this.visible, serviceWorkers: 'block', chromiumSandbox: true,
|
|
813
|
+
args: chromiumArgs,
|
|
807
814
|
handleSIGTERM: false, handleSIGINT: false, handleSIGHUP: false
|
|
808
815
|
});
|
|
809
816
|
}
|
|
@@ -865,9 +872,18 @@ export class CausyneBrowser {
|
|
|
865
872
|
}
|
|
866
873
|
const state = { id, page, refs: new Map(), lastSnapshot: '', lastStructure: null, runtimeErrors: [] };
|
|
867
874
|
page.on?.('pageerror', (error) => {
|
|
868
|
-
if (state.runtimeErrors.length <
|
|
875
|
+
if (state.runtimeErrors.length < 10)
|
|
869
876
|
state.runtimeErrors.push(error instanceof Error ? error.message.slice(0, 400) : String(error).slice(0, 400));
|
|
870
877
|
});
|
|
878
|
+
page.on?.('console', (msg) => {
|
|
879
|
+
const type = typeof msg?.type === 'function' ? msg.type() : (msg?.type || 'log');
|
|
880
|
+
const text = typeof msg?.text === 'function' ? msg.text() : String(msg?.text || msg || '');
|
|
881
|
+
if (type === 'error' || type === 'warning') {
|
|
882
|
+
if (state.runtimeErrors.length < 10) {
|
|
883
|
+
state.runtimeErrors.push(`[console.${type}] ${text.slice(0, 400)}`);
|
|
884
|
+
}
|
|
885
|
+
}
|
|
886
|
+
});
|
|
871
887
|
page.on?.('crash', () => {
|
|
872
888
|
state.crashed = true;
|
|
873
889
|
});
|
|
@@ -10,7 +10,7 @@ import {
|
|
|
10
10
|
loadCapabilityPackage
|
|
11
11
|
} from '../provisioning/capabilityProvisioner.js';
|
|
12
12
|
import { resolveBrowserRuntime, type PreparedBrowserRuntime } from './browserRuntime.js';
|
|
13
|
-
import { assertPublicWebUrl } from './urlPolicy.js';
|
|
13
|
+
import { assertPublicWebUrl, assertBrowserNavigableUrl } from './urlPolicy.js';
|
|
14
14
|
import { windowSnapshot, type SnapshotWindow } from './snapshotWindow.js';
|
|
15
15
|
|
|
16
16
|
const NAVIGATION_TIMEOUT_MS = 30_000;
|
|
@@ -944,7 +944,7 @@ export class CausyneBrowser {
|
|
|
944
944
|
this.resolveRuntime = options.resolveRuntime ?? resolveBrowserRuntime;
|
|
945
945
|
this.profileDirectory = path.resolve(options.profileDirectory ?? path.join(capabilityDirectory(), 'browser-profile'));
|
|
946
946
|
this.visible = options.visible ?? process.env.CAUSYNE_BROWSER_VISIBLE === '1';
|
|
947
|
-
this.validateUrl = options.validateUrl ??
|
|
947
|
+
this.validateUrl = options.validateUrl ?? assertBrowserNavigableUrl;
|
|
948
948
|
}
|
|
949
949
|
|
|
950
950
|
setWorkspace(workspace: string): void {
|
|
@@ -1064,9 +1064,16 @@ export class CausyneBrowser {
|
|
|
1064
1064
|
if (runtime.engine === 'chromium') {
|
|
1065
1065
|
const engine = await loadCapabilityPackage('playwright-core') as { chromium: { launchPersistentContext(profile: string, options: Record<string, unknown>): Promise<BrowserSession> } };
|
|
1066
1066
|
const profile = path.join(this.profileDirectory, 'chromium');
|
|
1067
|
-
|
|
1067
|
+
const chromiumArgs = [
|
|
1068
|
+
'--enable-webgl',
|
|
1069
|
+
'--use-gl=angle',
|
|
1070
|
+
...(process.platform === 'darwin' ? ['--use-angle=metal'] : ['--use-gl=swiftshader']),
|
|
1071
|
+
'--ignore-gpu-blocklist',
|
|
1072
|
+
'--enable-gpu-rasterization'
|
|
1073
|
+
];
|
|
1068
1074
|
this.session = await engine.chromium.launchPersistentContext(profile, {
|
|
1069
1075
|
executablePath: runtime.executablePath, headless: !this.visible, serviceWorkers: 'block', chromiumSandbox: true,
|
|
1076
|
+
args: chromiumArgs,
|
|
1070
1077
|
handleSIGTERM: false, handleSIGINT: false, handleSIGHUP: false
|
|
1071
1078
|
});
|
|
1072
1079
|
} else {
|
|
@@ -1123,7 +1130,16 @@ export class CausyneBrowser {
|
|
|
1123
1130
|
}
|
|
1124
1131
|
const state: TabState = { id, page, refs: new Map(), lastSnapshot: '', lastStructure: null, runtimeErrors: [] };
|
|
1125
1132
|
page.on?.('pageerror', (error: unknown) => {
|
|
1126
|
-
if (state.runtimeErrors.length <
|
|
1133
|
+
if (state.runtimeErrors.length < 10) state.runtimeErrors.push(error instanceof Error ? error.message.slice(0, 400) : String(error).slice(0, 400));
|
|
1134
|
+
});
|
|
1135
|
+
page.on?.('console', (msg: any) => {
|
|
1136
|
+
const type = typeof msg?.type === 'function' ? msg.type() : (msg?.type || 'log');
|
|
1137
|
+
const text = typeof msg?.text === 'function' ? msg.text() : String(msg?.text || msg || '');
|
|
1138
|
+
if (type === 'error' || type === 'warning') {
|
|
1139
|
+
if (state.runtimeErrors.length < 10) {
|
|
1140
|
+
state.runtimeErrors.push(`[console.${type}] ${text.slice(0, 400)}`);
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1127
1143
|
});
|
|
1128
1144
|
page.on?.('crash', () => {
|
|
1129
1145
|
state.crashed = true;
|
package/src/browser/urlPolicy.js
CHANGED
|
@@ -62,6 +62,16 @@ async function resolvedAddresses(hostname) {
|
|
|
62
62
|
hostCache.set(hostname, { expiresAt: Date.now() + DNS_CACHE_MS, addresses });
|
|
63
63
|
return addresses;
|
|
64
64
|
}
|
|
65
|
+
export function isLoopbackHost(hostname) {
|
|
66
|
+
const host = hostname.toLowerCase().replace(/^\[|\]$/g, '').replace(/\.$/, '');
|
|
67
|
+
if (host === 'localhost' || host.endsWith('.localhost'))
|
|
68
|
+
return true;
|
|
69
|
+
if (/^127(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d\d?)){3}$/.test(host))
|
|
70
|
+
return true;
|
|
71
|
+
if (host === '::1' || host === '0:0:0:0:0:0:0:1')
|
|
72
|
+
return true;
|
|
73
|
+
return false;
|
|
74
|
+
}
|
|
65
75
|
export async function assertPublicWebUrl(value) {
|
|
66
76
|
let url;
|
|
67
77
|
try {
|
|
@@ -84,6 +94,31 @@ export async function assertPublicWebUrl(value) {
|
|
|
84
94
|
}
|
|
85
95
|
return url;
|
|
86
96
|
}
|
|
97
|
+
export async function assertBrowserNavigableUrl(value) {
|
|
98
|
+
let url;
|
|
99
|
+
try {
|
|
100
|
+
url = new URL(value);
|
|
101
|
+
}
|
|
102
|
+
catch {
|
|
103
|
+
throw new Error('URL must be absolute and valid');
|
|
104
|
+
}
|
|
105
|
+
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
|
|
106
|
+
throw new Error('Only http and https URLs are allowed');
|
|
107
|
+
}
|
|
108
|
+
if (url.username || url.password)
|
|
109
|
+
throw new Error('URLs containing credentials are not allowed');
|
|
110
|
+
if (isLoopbackHost(url.hostname)) {
|
|
111
|
+
return url;
|
|
112
|
+
}
|
|
113
|
+
if (blockedHostname(url.hostname))
|
|
114
|
+
throw new Error('Local and internal hostnames are not allowed');
|
|
115
|
+
const literalVersion = isIP(url.hostname);
|
|
116
|
+
const addresses = literalVersion ? [url.hostname] : await resolvedAddresses(url.hostname);
|
|
117
|
+
if (addresses.length === 0 || addresses.some(isPrivateAddress)) {
|
|
118
|
+
throw new Error('Local, private, link-local, multicast, and reserved network addresses are not allowed');
|
|
119
|
+
}
|
|
120
|
+
return url;
|
|
121
|
+
}
|
|
87
122
|
export function clearUrlPolicyCache() {
|
|
88
123
|
hostCache.clear();
|
|
89
124
|
}
|
package/src/browser/urlPolicy.ts
CHANGED
|
@@ -63,6 +63,14 @@ async function resolvedAddresses(hostname: string): Promise<string[]> {
|
|
|
63
63
|
return addresses;
|
|
64
64
|
}
|
|
65
65
|
|
|
66
|
+
export function isLoopbackHost(hostname: string): boolean {
|
|
67
|
+
const host = hostname.toLowerCase().replace(/^\[|\]$/g, '').replace(/\.$/, '');
|
|
68
|
+
if (host === 'localhost' || host.endsWith('.localhost')) return true;
|
|
69
|
+
if (/^127(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d\d?)){3}$/.test(host)) return true;
|
|
70
|
+
if (host === '::1' || host === '0:0:0:0:0:0:0:1') return true;
|
|
71
|
+
return false;
|
|
72
|
+
}
|
|
73
|
+
|
|
66
74
|
export async function assertPublicWebUrl(value: string): Promise<URL> {
|
|
67
75
|
let url: URL;
|
|
68
76
|
try {
|
|
@@ -84,6 +92,32 @@ export async function assertPublicWebUrl(value: string): Promise<URL> {
|
|
|
84
92
|
return url;
|
|
85
93
|
}
|
|
86
94
|
|
|
95
|
+
export async function assertBrowserNavigableUrl(value: string): Promise<URL> {
|
|
96
|
+
let url: URL;
|
|
97
|
+
try {
|
|
98
|
+
url = new URL(value);
|
|
99
|
+
} catch {
|
|
100
|
+
throw new Error('URL must be absolute and valid');
|
|
101
|
+
}
|
|
102
|
+
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
|
|
103
|
+
throw new Error('Only http and https URLs are allowed');
|
|
104
|
+
}
|
|
105
|
+
if (url.username || url.password) throw new Error('URLs containing credentials are not allowed');
|
|
106
|
+
|
|
107
|
+
if (isLoopbackHost(url.hostname)) {
|
|
108
|
+
return url;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
if (blockedHostname(url.hostname)) throw new Error('Local and internal hostnames are not allowed');
|
|
112
|
+
|
|
113
|
+
const literalVersion = isIP(url.hostname);
|
|
114
|
+
const addresses = literalVersion ? [url.hostname] : await resolvedAddresses(url.hostname);
|
|
115
|
+
if (addresses.length === 0 || addresses.some(isPrivateAddress)) {
|
|
116
|
+
throw new Error('Local, private, link-local, multicast, and reserved network addresses are not allowed');
|
|
117
|
+
}
|
|
118
|
+
return url;
|
|
119
|
+
}
|
|
120
|
+
|
|
87
121
|
export function clearUrlPolicyCache(): void {
|
|
88
122
|
hostCache.clear();
|
|
89
123
|
}
|
package/src/cliMode.js
CHANGED
|
@@ -346,8 +346,8 @@ export async function chatMode({ home = false } = {}) {
|
|
|
346
346
|
let surface = home && isInteractive() ? createStageSurface({ config }) : null;
|
|
347
347
|
const openedHome = Boolean(surface);
|
|
348
348
|
const bannerWidth = openedHome ? 0 : conn.renderer.sessionHeader(headerInfo);
|
|
349
|
+
conn.renderer.status.setSession(headerInfo);
|
|
349
350
|
if (openedHome) {
|
|
350
|
-
conn.renderer.status.setSession(headerInfo);
|
|
351
351
|
surface.enterHome(headerInfo);
|
|
352
352
|
}
|
|
353
353
|
const homeTransition = new HomeTransition(openedHome, surface);
|
|
@@ -374,7 +374,10 @@ export async function chatMode({ home = false } = {}) {
|
|
|
374
374
|
// The header reports the companion composer width. The Stage keeps that
|
|
375
375
|
// readable width throughout the session, including after history clears.
|
|
376
376
|
if (!surface) surface = createStageSurface({ config, openingWidth: bannerWidth });
|
|
377
|
-
if (surface)
|
|
377
|
+
if (surface) {
|
|
378
|
+
surface.setSessionInfo(headerInfo);
|
|
379
|
+
conn.renderer.transcript = surface.transcript;
|
|
380
|
+
}
|
|
378
381
|
|
|
379
382
|
prompt = new ChatPrompt({
|
|
380
383
|
root: process.cwd(),
|
|
@@ -567,6 +570,7 @@ export async function chatMode({ home = false } = {}) {
|
|
|
567
570
|
|
|
568
571
|
homeTransition.beginTurn(loop);
|
|
569
572
|
loop.userPrompt = task;
|
|
573
|
+
loop.currentTaskPrompt = task;
|
|
570
574
|
// ONE USER REQUEST IS ONE TASK.
|
|
571
575
|
//
|
|
572
576
|
// The loop object is reused across the whole chat — that is deliberate, it
|
package/src/commands.js
CHANGED
|
@@ -992,6 +992,20 @@ export const COMMANDS = [
|
|
|
992
992
|
}
|
|
993
993
|
},
|
|
994
994
|
|
|
995
|
+
{
|
|
996
|
+
name: 'compact',
|
|
997
|
+
aliases: ['compress', 'summarize'],
|
|
998
|
+
scope: 'local',
|
|
999
|
+
usage: '/compact',
|
|
1000
|
+
description: 'Condense earlier conversation turns into a structured state checkpoint to reclaim tokens',
|
|
1001
|
+
dialogTitle: 'Context Compaction',
|
|
1002
|
+
run: async (argv, ctx) => {
|
|
1003
|
+
const { runCompactSlashCommand } = await import('./core/contextCompactor.js');
|
|
1004
|
+
const res = await runCompactSlashCommand(argv, ctx);
|
|
1005
|
+
return res.ok ? ok(res.output) : fail(res.output);
|
|
1006
|
+
}
|
|
1007
|
+
},
|
|
1008
|
+
|
|
995
1009
|
{
|
|
996
1010
|
name: 'copy',
|
|
997
1011
|
aliases: ['cp', 'clip'],
|
package/src/contextManager.d.ts
CHANGED
|
@@ -8,3 +8,4 @@ export function describeDroppedMessages(...args: any[]): any;
|
|
|
8
8
|
export function sanitizeSequences(...args: any[]): any;
|
|
9
9
|
export function applyProgressiveCompaction(...args: any[]): any;
|
|
10
10
|
export function snipOversizedToolOutputs(...args: any[]): any;
|
|
11
|
+
export const CHARS_PER_TOKEN: number;
|
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file src/core/contextCompactor.ts
|
|
3
|
+
* Enterprise-Grade Context Compactor (OpenAI Codex & Claude Code Architecture).
|
|
4
|
+
*
|
|
5
|
+
* Provides:
|
|
6
|
+
* 1. High-fidelity structured state summarization (Goal, Architecture, Files, Milestones, Next Steps).
|
|
7
|
+
* 2. Non-destructive physical in-place compaction preserving root anchor and recent turns.
|
|
8
|
+
* 3. Proactive auto-compaction before context limits or token budgets choke execution.
|
|
9
|
+
* 4. User-facing `/compact` slash-command handler.
|
|
10
|
+
*
|
|
11
|
+
* Authorship: Strict TypeScript (Causyne Agent).
|
|
12
|
+
*/
|
|
13
|
+
import { pruneStaleToolObservations, shortenOversizedToolObservations, pruneExecutedToolArguments, buildRecoverableDroppedSummary } from '../historyPruner.js';
|
|
14
|
+
import { compactInPlace, measureMessages, CHARS_PER_TOKEN } from '../contextManager.js';
|
|
15
|
+
/**
|
|
16
|
+
* Extracts a high-fidelity, structured state summary from dropped message history.
|
|
17
|
+
* Mirrors the state preservation architecture of OpenAI Codex and Claude Code.
|
|
18
|
+
*/
|
|
19
|
+
export function buildCodexStyleSummary(droppedMessages, originalPrompt) {
|
|
20
|
+
const createdFiles = new Set();
|
|
21
|
+
const modifiedFiles = new Set();
|
|
22
|
+
const inspectedFiles = new Set();
|
|
23
|
+
const verifiedMilestones = new Set();
|
|
24
|
+
const toolCounts = new Map();
|
|
25
|
+
const architectureNotes = new Set();
|
|
26
|
+
const failures = new Set();
|
|
27
|
+
for (const msg of droppedMessages) {
|
|
28
|
+
if (msg.role === 'assistant') {
|
|
29
|
+
const calls = msg.tool_calls || [];
|
|
30
|
+
for (const call of calls) {
|
|
31
|
+
const fnName = call.function?.name || 'tool';
|
|
32
|
+
toolCounts.set(fnName, (toolCounts.get(fnName) || 0) + 1);
|
|
33
|
+
try {
|
|
34
|
+
const rawArgs = call.function?.arguments;
|
|
35
|
+
if (typeof rawArgs === 'string') {
|
|
36
|
+
const parsed = JSON.parse(rawArgs);
|
|
37
|
+
if (parsed && typeof parsed === 'object') {
|
|
38
|
+
const target = String(parsed.path || parsed.file_path || parsed.target || '');
|
|
39
|
+
if (target) {
|
|
40
|
+
if (['fs_write', 'write_to_file', 'writeFile'].includes(fnName)) {
|
|
41
|
+
createdFiles.add(target);
|
|
42
|
+
}
|
|
43
|
+
else if (['fs_edit', 'replace_file_content', 'multi_replace_file_content'].includes(fnName)) {
|
|
44
|
+
modifiedFiles.add(target);
|
|
45
|
+
}
|
|
46
|
+
else if (['fs_read', 'view_file', 'readFile'].includes(fnName)) {
|
|
47
|
+
inspectedFiles.add(target);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
// Detect architectural and technology declarations
|
|
51
|
+
if (parsed.command && typeof parsed.command === 'string') {
|
|
52
|
+
const cmd = parsed.command;
|
|
53
|
+
if (/npm\s+i|install/i.test(cmd))
|
|
54
|
+
architectureNotes.add(`Dependencies: ${cmd.slice(0, 100)}`);
|
|
55
|
+
if (/tsc|build/i.test(cmd))
|
|
56
|
+
architectureNotes.add('Compiled build pipeline invoked');
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
// Arguments might be truncated or non-JSON; continue extraction.
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
// Extract technology/design keywords from assistant narrative
|
|
66
|
+
if (typeof msg.content === 'string') {
|
|
67
|
+
const text = msg.content;
|
|
68
|
+
if (/three\.?js|webgl|canvas3d/i.test(text))
|
|
69
|
+
architectureNotes.add('Three.js / WebGL 3D rendering pipeline');
|
|
70
|
+
if (/audio(?:\s*context|\s*engine)|\.mp3|\.wav/i.test(text))
|
|
71
|
+
architectureNotes.add('Web Audio Engine & sound effects');
|
|
72
|
+
if (/blender/i.test(text))
|
|
73
|
+
architectureNotes.add('Blender 3D procedural studio');
|
|
74
|
+
if (/typescript/i.test(text))
|
|
75
|
+
architectureNotes.add('Strict TypeScript architecture');
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
if (msg.role === 'tool') {
|
|
79
|
+
const contentStr = typeof msg.content === 'string' ? msg.content : JSON.stringify(msg.content ?? '');
|
|
80
|
+
try {
|
|
81
|
+
const parsed = JSON.parse(contentStr);
|
|
82
|
+
if (parsed && typeof parsed === 'object') {
|
|
83
|
+
if (parsed.success === true) {
|
|
84
|
+
if (msg.name)
|
|
85
|
+
verifiedMilestones.add(`${msg.name} verified`);
|
|
86
|
+
}
|
|
87
|
+
else if (parsed.success === false && parsed.error) {
|
|
88
|
+
failures.add(`${msg.name || 'tool'}: ${String(parsed.error).slice(0, 120)}`);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
// Plain output or decayed marker
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
// Build the Codex-style structured report
|
|
98
|
+
const sections = [];
|
|
99
|
+
sections.push('### [COMPACTED CONTEXT CHECKPOINT — CODEX STATE PRESERVATION]');
|
|
100
|
+
if (originalPrompt && originalPrompt.trim()) {
|
|
101
|
+
sections.push(`**Goal & User Intent:**\n${originalPrompt.trim()}`);
|
|
102
|
+
}
|
|
103
|
+
if (architectureNotes.size > 0) {
|
|
104
|
+
sections.push(`**Architecture & Technology Stack:**\n${[...architectureNotes].map(a => `- ${a}`).join('\n')}`);
|
|
105
|
+
}
|
|
106
|
+
const allFilesTouched = [
|
|
107
|
+
...[...createdFiles].map(f => `- [Created] ${f}`),
|
|
108
|
+
...[...modifiedFiles].map(f => `- [Modified] ${f}`),
|
|
109
|
+
...[...inspectedFiles].filter(f => !createdFiles.has(f) && !modifiedFiles.has(f)).map(f => `- [Inspected] ${f}`)
|
|
110
|
+
];
|
|
111
|
+
if (allFilesTouched.length > 0) {
|
|
112
|
+
sections.push(`**Files Manifest & Workspace State:**\n${allFilesTouched.slice(0, 20).join('\n')}`);
|
|
113
|
+
}
|
|
114
|
+
if (toolCounts.size > 0) {
|
|
115
|
+
const summary = [...toolCounts.entries()]
|
|
116
|
+
.sort((a, b) => b[1] - a[1])
|
|
117
|
+
.map(([name, count]) => `${name} (${count}x)`)
|
|
118
|
+
.join(', ');
|
|
119
|
+
sections.push(`**Actions Executed:** ${summary}`);
|
|
120
|
+
}
|
|
121
|
+
if (verifiedMilestones.size > 0) {
|
|
122
|
+
sections.push(`**Verified Outcomes:** ${[...verifiedMilestones].slice(0, 8).join(', ')}`);
|
|
123
|
+
}
|
|
124
|
+
if (failures.size > 0) {
|
|
125
|
+
sections.push(`**Prior Failures Handled:** ${[...failures].slice(0, 4).join(' | ')}`);
|
|
126
|
+
}
|
|
127
|
+
sections.push('**Directive for Continuation:** Completed workspace files and session artifacts on disk are preserved. '
|
|
128
|
+
+ 'Do not re-scan or repeat verified setup steps. Continue forward execution and complete the remaining requirements.');
|
|
129
|
+
return sections.join('\n\n');
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Compacts the conversation trajectory in-place.
|
|
133
|
+
* Preserves the Golden Anchor (message 0) and the most recent working turns.
|
|
134
|
+
*/
|
|
135
|
+
export function compactSessionMessages(messages, options = {}) {
|
|
136
|
+
const initialChars = measureMessages(messages);
|
|
137
|
+
const keepRecentTurns = Math.max(2, options.keepRecentTurns ?? 4);
|
|
138
|
+
// Must have enough messages to compact: root message (0) + at least 2 dropped + keepRecent
|
|
139
|
+
if (messages.length < keepRecentTurns + 3) {
|
|
140
|
+
return {
|
|
141
|
+
compacted: false,
|
|
142
|
+
removedCount: 0,
|
|
143
|
+
reclaimedChars: 0,
|
|
144
|
+
reclaimedTokens: 0,
|
|
145
|
+
initialChars,
|
|
146
|
+
finalChars: initialChars,
|
|
147
|
+
summaryText: '',
|
|
148
|
+
reason: 'History contains too few messages for compaction.'
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
// Pre-pass: run Observation Elision and Argument Archiving on all messages
|
|
152
|
+
pruneStaleToolObservations(messages, {
|
|
153
|
+
keepRecent: keepRecentTurns,
|
|
154
|
+
minChars: 300,
|
|
155
|
+
taskId: options.taskId ?? 'compaction'
|
|
156
|
+
});
|
|
157
|
+
shortenOversizedToolObservations(messages, {
|
|
158
|
+
threshold: 1500,
|
|
159
|
+
taskId: options.taskId ?? 'compaction'
|
|
160
|
+
});
|
|
161
|
+
pruneExecutedToolArguments(messages, {
|
|
162
|
+
threshold: 1500,
|
|
163
|
+
taskId: options.taskId ?? 'compaction'
|
|
164
|
+
});
|
|
165
|
+
// Calculate split index for physical compaction:
|
|
166
|
+
// Messages from index 1 to splitIndex will be collapsed into a single summary
|
|
167
|
+
const splitIndex = messages.length - keepRecentTurns - 1;
|
|
168
|
+
if (splitIndex < 1) {
|
|
169
|
+
return {
|
|
170
|
+
compacted: false,
|
|
171
|
+
removedCount: 0,
|
|
172
|
+
reclaimedChars: 0,
|
|
173
|
+
reclaimedTokens: 0,
|
|
174
|
+
initialChars,
|
|
175
|
+
finalChars: measureMessages(messages),
|
|
176
|
+
summaryText: '',
|
|
177
|
+
reason: 'Split index out of range.'
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
const dropped = messages.slice(1, splitIndex + 1);
|
|
181
|
+
const rootPrompt = typeof messages[0]?.content === 'string'
|
|
182
|
+
? messages[0].content
|
|
183
|
+
: options.originalPrompt;
|
|
184
|
+
const structuredSummary = buildCodexStyleSummary(dropped, rootPrompt);
|
|
185
|
+
const fullRecoverableSummary = buildRecoverableDroppedSummary(dropped, structuredSummary);
|
|
186
|
+
const removed = compactInPlace(messages, splitIndex, fullRecoverableSummary);
|
|
187
|
+
const finalChars = measureMessages(messages);
|
|
188
|
+
const reclaimedChars = Math.max(0, initialChars - finalChars);
|
|
189
|
+
const reclaimedTokens = Math.round(reclaimedChars / CHARS_PER_TOKEN);
|
|
190
|
+
return {
|
|
191
|
+
compacted: true,
|
|
192
|
+
removedCount: removed,
|
|
193
|
+
reclaimedChars,
|
|
194
|
+
reclaimedTokens,
|
|
195
|
+
initialChars,
|
|
196
|
+
finalChars,
|
|
197
|
+
summaryText: fullRecoverableSummary
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
201
|
+
* Proactively checks memory pressure and runs auto-compaction if context threshold is exceeded.
|
|
202
|
+
* Operates silently and seamlessly without interrupting active work.
|
|
203
|
+
*/
|
|
204
|
+
export function autoCompactIfUnderPressure(loop, options = {}) {
|
|
205
|
+
if (!loop || !Array.isArray(loop.messages) || loop.messages.length < (options.minMessages ?? 12)) {
|
|
206
|
+
return null;
|
|
207
|
+
}
|
|
208
|
+
const thresholdFraction = options.thresholdFraction ?? 0.70;
|
|
209
|
+
const currentChars = measureMessages(loop.messages);
|
|
210
|
+
const maxPool = loop._contextLimitChars || 120_000;
|
|
211
|
+
if (currentChars >= maxPool * thresholdFraction) {
|
|
212
|
+
const result = compactSessionMessages(loop.messages, {
|
|
213
|
+
keepRecentTurns: 4,
|
|
214
|
+
taskId: loop.taskId,
|
|
215
|
+
originalPrompt: loop.currentTaskPrompt || loop.userPrompt
|
|
216
|
+
});
|
|
217
|
+
if (result.compacted) {
|
|
218
|
+
if (loop.memoryManager && typeof loop.memoryManager.saveHistory === 'function') {
|
|
219
|
+
loop.memoryManager.saveHistory(loop.messages);
|
|
220
|
+
}
|
|
221
|
+
if (typeof loop.emitEvent === 'function') {
|
|
222
|
+
loop.emitEvent({
|
|
223
|
+
type: 'status',
|
|
224
|
+
message: `Context auto-compacted: reclaimed ${(result.reclaimedChars / 1024).toFixed(1)} KB (~${result.reclaimedTokens.toLocaleString()} tokens)`
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
return result;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
return null;
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* Slash command handler for `/compact`.
|
|
234
|
+
*/
|
|
235
|
+
export async function runCompactSlashCommand(_argv, ctx) {
|
|
236
|
+
const loop = ctx.loop;
|
|
237
|
+
if (!loop || !Array.isArray(loop.messages) || loop.messages.length === 0) {
|
|
238
|
+
return {
|
|
239
|
+
ok: false,
|
|
240
|
+
output: 'No active session or conversation messages to compact.'
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
if (loop.messages.length <= 3) {
|
|
244
|
+
return {
|
|
245
|
+
ok: true,
|
|
246
|
+
output: `Conversation currently contains only ${loop.messages.length} message(s). Compaction is not needed yet.`
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
const result = compactSessionMessages(loop.messages, {
|
|
250
|
+
keepRecentTurns: 4,
|
|
251
|
+
taskId: loop.taskId || 'manual-compact',
|
|
252
|
+
originalPrompt: loop.currentTaskPrompt || loop.userPrompt
|
|
253
|
+
});
|
|
254
|
+
if (!result.compacted) {
|
|
255
|
+
return {
|
|
256
|
+
ok: true,
|
|
257
|
+
output: result.reason || 'Context already compact. No older messages eligible for compaction.'
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
if (loop.memoryManager && typeof loop.memoryManager.saveHistory === 'function') {
|
|
261
|
+
loop.memoryManager.saveHistory(loop.messages);
|
|
262
|
+
}
|
|
263
|
+
const reclaimedKb = (result.reclaimedChars / 1024).toFixed(1);
|
|
264
|
+
const finalKb = (result.finalChars / 1024).toFixed(1);
|
|
265
|
+
const report = [
|
|
266
|
+
'✔ Context successfully compacted (OpenAI Codex structured state model).',
|
|
267
|
+
'',
|
|
268
|
+
` • Earlier messages condensed: ${result.removedCount}`,
|
|
269
|
+
` • Memory reclaimed: ${reclaimedKb} KB (~${result.reclaimedTokens.toLocaleString()} tokens)`,
|
|
270
|
+
` • Live active context: ${finalKb} KB`,
|
|
271
|
+
' • Golden Anchor (original prompt) & recent working turns: Preserved in full',
|
|
272
|
+
' • Deliverables and source files on disk: 100% intact',
|
|
273
|
+
'',
|
|
274
|
+
'The agent will continue with a clean, focused context without losing prior achievements.'
|
|
275
|
+
].join('\n');
|
|
276
|
+
return { ok: true, output: report };
|
|
277
|
+
}
|