@causyne/agent 1.20.12 → 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.
Files changed (72) hide show
  1. package/LICENSE +1 -1
  2. package/package.json +1 -1
  3. package/src/SmartTools.js +33 -0
  4. package/src/SmartTools.ts +37 -0
  5. package/src/acp/client.js +157 -4
  6. package/src/acp/client.ts +152 -5
  7. package/src/agentLoop.js +857 -178
  8. package/src/agentLoop.ts +865 -183
  9. package/src/browser/browserRuntime.js +8 -1
  10. package/src/browser/browserRuntime.ts +8 -1
  11. package/src/browser/causyneBrowser.js +20 -4
  12. package/src/browser/causyneBrowser.ts +20 -4
  13. package/src/browser/urlPolicy.js +35 -0
  14. package/src/browser/urlPolicy.ts +34 -0
  15. package/src/cliMode.js +6 -2
  16. package/src/commands.js +14 -0
  17. package/src/contextManager.d.ts +1 -0
  18. package/src/core/contextCompactor.js +277 -0
  19. package/src/core/contextCompactor.ts +353 -0
  20. package/src/decideTools.js +157 -0
  21. package/src/decideTools.ts +195 -0
  22. package/src/decisionPolicy.js +5 -3
  23. package/src/decisionPolicy.ts +5 -3
  24. package/src/implementationPlan.js +284 -0
  25. package/src/implementationPlan.ts +275 -0
  26. package/src/observer/coldObserver.js +10 -4
  27. package/src/observer/coldObserver.ts +15 -7
  28. package/src/observer/evidence.js +11 -5
  29. package/src/observer/evidence.ts +13 -6
  30. package/src/observer.js +196 -0
  31. package/src/observer.ts +287 -0
  32. package/src/providers/acp.js +362 -109
  33. package/src/providers/acp.ts +359 -111
  34. package/src/providers/antigravity.js +133 -105
  35. package/src/providers/antigravity.ts +130 -109
  36. package/src/providers/base.d.ts +3 -0
  37. package/src/providers/budgetEnforcer.js +13 -0
  38. package/src/providers/budgetEnforcer.ts +13 -3
  39. package/src/provisioning/capabilityProvisioner.js +14 -10
  40. package/src/sandbox.js +4 -2
  41. package/src/saveTools.js +146 -0
  42. package/src/saveTools.ts +169 -0
  43. package/src/session/cachePressure.js +77 -0
  44. package/src/session/cachePressure.ts +122 -0
  45. package/src/smartToolsUse.js +69 -12
  46. package/src/smartToolsUse.ts +103 -12
  47. package/src/taskShape.js +7 -7
  48. package/src/taskShape.ts +7 -7
  49. package/src/timeMachine.js +55 -20
  50. package/src/timeMachine.ts +64 -20
  51. package/src/toolPacks.js +217 -310
  52. package/src/toolPacks.ts +505 -0
  53. package/src/tools/deferredMcpSearch.js +21 -13
  54. package/src/tools/deferredMcpSearch.ts +23 -15
  55. package/src/tools/updatePlan.js +2 -2
  56. package/src/tools/updatePlan.ts +2 -2
  57. package/src/toolsList.js +203 -0
  58. package/src/toolsList.ts +224 -0
  59. package/src/tui/chatRenderer.js +49 -14
  60. package/src/tui/codeStreamRenderer.js +16 -5
  61. package/src/tui/codeStreamRenderer.ts +14 -4
  62. package/src/tui/prompt.js +4 -2
  63. package/src/tui/sessionSidebar.js +10 -2
  64. package/src/tui/sessionSidebar.ts +10 -3
  65. package/src/tui/stageSurface.js +27 -1
  66. package/src/tui/text.d.ts +1 -0
  67. package/src/tui/turnRail.js +274 -0
  68. package/src/tui/turnRail.ts +334 -0
  69. package/src/types/contracts.ts +103 -0
  70. package/src/verificationPlan.js +141 -0
  71. package/src/verificationPlan.ts +166 -0
  72. package/src/toolPacks.d.ts +0 -10
@@ -0,0 +1,146 @@
1
+ /**
2
+ * @file src/saveTools.ts
3
+ * saveTools — stage 4 of the tool pipeline.
4
+ *
5
+ * user intent -> ToolsList -> decideTools -> SmartTools -> saveTools -> AgentLoop
6
+ *
7
+ * Owns the set of tools admitted for a conversation. Admission is append-only
8
+ * and ordered: tool schemas sit at the front of every provider's cached prefix,
9
+ * so stable ordering avoids unnecessary prefix changes. Adding definitions can
10
+ * still invalidate provider caches; savings must be measured, not assumed.
11
+ *
12
+ * The set is persisted per session so a resumed conversation starts with the
13
+ * tools it already earned, instead of searching for them again.
14
+ *
15
+ * Authorship: Strict TypeScript (Causyne Agent).
16
+ */
17
+ import { createHash } from 'node:crypto';
18
+ import fs from 'node:fs';
19
+ import path from 'node:path';
20
+ import { causyneHome } from './utils/paths.js';
21
+ import { atomicWriteFileSync } from './infra/atomicWriter.js';
22
+ const MAX_NAMES = 10000;
23
+ const MAX_RECORDS = 50;
24
+ const MAX_FILES = 200;
25
+ const NAME = /^[A-Za-z0-9_.:@/-]{1,200}$/;
26
+ export class SavedTools {
27
+ packs;
28
+ tools;
29
+ order;
30
+ history = [];
31
+ /** Passing existing collections lets a caller keep its own references valid. */
32
+ constructor(shared = {}) {
33
+ this.packs = shared.packs ?? new Set();
34
+ this.tools = shared.tools ?? new Set();
35
+ this.order = shared.order ?? [];
36
+ }
37
+ admitPack(name) {
38
+ if (!name || this.packs.has(name))
39
+ return false;
40
+ this.packs.add(name);
41
+ this.order.push(name);
42
+ return true;
43
+ }
44
+ admitTool(name) {
45
+ if (!name || this.tools.has(name))
46
+ return false;
47
+ this.tools.add(name);
48
+ return true;
49
+ }
50
+ admit(refined) {
51
+ const addedPacks = refined.packs.filter((name) => this.admitPack(name));
52
+ const addedTools = refined.tools.filter((name) => this.admitTool(name));
53
+ if (addedPacks.length > 0 || addedTools.length > 0) {
54
+ this.history.push({ at: Date.now(), source: refined.source, tools: addedTools, packs: addedPacks, reasons: refined.reasons });
55
+ if (this.history.length > MAX_RECORDS)
56
+ this.history.splice(0, this.history.length - MAX_RECORDS);
57
+ }
58
+ return { addedTools, addedPacks };
59
+ }
60
+ records() {
61
+ return this.history;
62
+ }
63
+ toState() {
64
+ return { packs: [...this.packs], tools: [...this.tools], order: [...this.order] };
65
+ }
66
+ /** Restore without reordering what is already admitted. */
67
+ restore(state) {
68
+ const addedPacks = state.order.filter((name) => state.packs.includes(name) && this.admitPack(name));
69
+ for (const name of state.packs)
70
+ if (this.admitPack(name))
71
+ addedPacks.push(name);
72
+ const addedTools = state.tools.filter((name) => this.admitTool(name));
73
+ return { addedTools, addedPacks };
74
+ }
75
+ }
76
+ function directory() {
77
+ const dir = path.join(causyneHome(), 'tool-sessions');
78
+ try {
79
+ if (!fs.existsSync(dir)) {
80
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
81
+ }
82
+ else {
83
+ const mode = fs.statSync(dir).mode & 0o777;
84
+ if ((mode & 0o100) === 0)
85
+ fs.chmodSync(dir, 0o700);
86
+ }
87
+ }
88
+ catch {
89
+ // fallback if concurrent or read-only
90
+ }
91
+ return dir;
92
+ }
93
+ /** The session id is hashed so it can never escape the directory or collide with a path. */
94
+ export function savedToolsPath(sessionId) {
95
+ const digest = createHash('sha256').update(String(sessionId)).digest('hex').slice(0, 32);
96
+ return path.join(directory(), `${digest}.json`);
97
+ }
98
+ function names(value) {
99
+ if (!Array.isArray(value))
100
+ return [];
101
+ return value.filter((item) => typeof item === 'string' && NAME.test(item)).slice(0, MAX_NAMES);
102
+ }
103
+ /** Never throws: a missing or damaged file is the same as no saved tools. */
104
+ export function readSavedTools(sessionId) {
105
+ try {
106
+ const raw = JSON.parse(fs.readFileSync(savedToolsPath(sessionId), 'utf8'));
107
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw))
108
+ return null;
109
+ const record = raw;
110
+ const state = { packs: names(record['packs']), tools: names(record['tools']), order: names(record['order']) };
111
+ return state.packs.length + state.tools.length > 0 ? state : null;
112
+ }
113
+ catch {
114
+ return null;
115
+ }
116
+ }
117
+ function prune() {
118
+ try {
119
+ const entries = fs.readdirSync(directory())
120
+ .filter((file) => file.endsWith('.json'))
121
+ .map((file) => ({ file, at: fs.statSync(path.join(directory(), file)).mtimeMs }))
122
+ .sort((a, b) => b.at - a.at);
123
+ for (const stale of entries.slice(MAX_FILES))
124
+ fs.rmSync(path.join(directory(), stale.file), { force: true });
125
+ }
126
+ catch {
127
+ // housekeeping must never block a task
128
+ }
129
+ }
130
+ /** Never throws: persistence is an optimisation, not a dependency. */
131
+ export function writeSavedTools(sessionId, state) {
132
+ try {
133
+ const bounded = {
134
+ packs: names(state.packs),
135
+ tools: names(state.tools),
136
+ order: names(state.order)
137
+ };
138
+ fs.mkdirSync(directory(), { recursive: true, mode: 0o700 });
139
+ atomicWriteFileSync(savedToolsPath(sessionId), JSON.stringify(bounded), { mode: 0o600 });
140
+ prune();
141
+ return true;
142
+ }
143
+ catch {
144
+ return false;
145
+ }
146
+ }
@@ -0,0 +1,169 @@
1
+ /**
2
+ * @file src/saveTools.ts
3
+ * saveTools — stage 4 of the tool pipeline.
4
+ *
5
+ * user intent -> ToolsList -> decideTools -> SmartTools -> saveTools -> AgentLoop
6
+ *
7
+ * Owns the set of tools admitted for a conversation. Admission is append-only
8
+ * and ordered: tool schemas sit at the front of every provider's cached prefix,
9
+ * so stable ordering avoids unnecessary prefix changes. Adding definitions can
10
+ * still invalidate provider caches; savings must be measured, not assumed.
11
+ *
12
+ * The set is persisted per session so a resumed conversation starts with the
13
+ * tools it already earned, instead of searching for them again.
14
+ *
15
+ * Authorship: Strict TypeScript (Causyne Agent).
16
+ */
17
+
18
+ import { createHash } from 'node:crypto';
19
+ import fs from 'node:fs';
20
+ import path from 'node:path';
21
+ import { causyneHome } from './utils/paths.js';
22
+ import { atomicWriteFileSync } from './infra/atomicWriter.js';
23
+ import type { RefinedToolDecision } from './smartToolsUse.js';
24
+
25
+ export interface SavedToolsState {
26
+ packs: string[];
27
+ tools: string[];
28
+ order: string[];
29
+ }
30
+
31
+ export interface AdmissionRecord {
32
+ readonly at: number;
33
+ readonly source: string;
34
+ readonly tools: readonly string[];
35
+ readonly packs: readonly string[];
36
+ readonly reasons: readonly string[];
37
+ }
38
+
39
+ export interface AdmissionResult {
40
+ readonly addedTools: string[];
41
+ readonly addedPacks: string[];
42
+ }
43
+
44
+ const MAX_NAMES = 10000;
45
+ const MAX_RECORDS = 50;
46
+ const MAX_FILES = 200;
47
+ const NAME = /^[A-Za-z0-9_.:@/-]{1,200}$/;
48
+
49
+ export class SavedTools {
50
+ readonly packs: Set<string>;
51
+ readonly tools: Set<string>;
52
+ readonly order: string[];
53
+ private readonly history: AdmissionRecord[] = [];
54
+
55
+ /** Passing existing collections lets a caller keep its own references valid. */
56
+ constructor(shared: { packs?: Set<string>; tools?: Set<string>; order?: string[] } = {}) {
57
+ this.packs = shared.packs ?? new Set<string>();
58
+ this.tools = shared.tools ?? new Set<string>();
59
+ this.order = shared.order ?? [];
60
+ }
61
+
62
+ admitPack(name: string): boolean {
63
+ if (!name || this.packs.has(name)) return false;
64
+ this.packs.add(name);
65
+ this.order.push(name);
66
+ return true;
67
+ }
68
+
69
+ admitTool(name: string): boolean {
70
+ if (!name || this.tools.has(name)) return false;
71
+ this.tools.add(name);
72
+ return true;
73
+ }
74
+
75
+ admit(refined: Pick<RefinedToolDecision, 'source' | 'tools' | 'packs' | 'reasons'>): AdmissionResult {
76
+ const addedPacks = refined.packs.filter((name) => this.admitPack(name));
77
+ const addedTools = refined.tools.filter((name) => this.admitTool(name));
78
+ if (addedPacks.length > 0 || addedTools.length > 0) {
79
+ this.history.push({ at: Date.now(), source: refined.source, tools: addedTools, packs: addedPacks, reasons: refined.reasons });
80
+ if (this.history.length > MAX_RECORDS) this.history.splice(0, this.history.length - MAX_RECORDS);
81
+ }
82
+ return { addedTools, addedPacks };
83
+ }
84
+
85
+ records(): readonly AdmissionRecord[] {
86
+ return this.history;
87
+ }
88
+
89
+ toState(): SavedToolsState {
90
+ return { packs: [...this.packs], tools: [...this.tools], order: [...this.order] };
91
+ }
92
+
93
+ /** Restore without reordering what is already admitted. */
94
+ restore(state: SavedToolsState): AdmissionResult {
95
+ const addedPacks = state.order.filter((name) => state.packs.includes(name) && this.admitPack(name));
96
+ for (const name of state.packs) if (this.admitPack(name)) addedPacks.push(name);
97
+ const addedTools = state.tools.filter((name) => this.admitTool(name));
98
+ return { addedTools, addedPacks };
99
+ }
100
+ }
101
+
102
+ function directory(): string {
103
+ const dir = path.join(causyneHome(), 'tool-sessions');
104
+ try {
105
+ if (!fs.existsSync(dir)) {
106
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
107
+ } else {
108
+ const mode = fs.statSync(dir).mode & 0o777;
109
+ if ((mode & 0o100) === 0) fs.chmodSync(dir, 0o700);
110
+ }
111
+ } catch {
112
+ // fallback if concurrent or read-only
113
+ }
114
+ return dir;
115
+ }
116
+
117
+ /** The session id is hashed so it can never escape the directory or collide with a path. */
118
+ export function savedToolsPath(sessionId: string): string {
119
+ const digest = createHash('sha256').update(String(sessionId)).digest('hex').slice(0, 32);
120
+ return path.join(directory(), `${digest}.json`);
121
+ }
122
+
123
+ function names(value: unknown): string[] {
124
+ if (!Array.isArray(value)) return [];
125
+ return value.filter((item): item is string => typeof item === 'string' && NAME.test(item)).slice(0, MAX_NAMES);
126
+ }
127
+
128
+ /** Never throws: a missing or damaged file is the same as no saved tools. */
129
+ export function readSavedTools(sessionId: string): SavedToolsState | null {
130
+ try {
131
+ const raw: unknown = JSON.parse(fs.readFileSync(savedToolsPath(sessionId), 'utf8'));
132
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return null;
133
+ const record = raw as Record<string, unknown>;
134
+ const state: SavedToolsState = { packs: names(record['packs']), tools: names(record['tools']), order: names(record['order']) };
135
+ return state.packs.length + state.tools.length > 0 ? state : null;
136
+ } catch {
137
+ return null;
138
+ }
139
+ }
140
+
141
+ function prune(): void {
142
+ try {
143
+ const entries = fs.readdirSync(directory())
144
+ .filter((file) => file.endsWith('.json'))
145
+ .map((file) => ({ file, at: fs.statSync(path.join(directory(), file)).mtimeMs }))
146
+ .sort((a, b) => b.at - a.at);
147
+ for (const stale of entries.slice(MAX_FILES)) fs.rmSync(path.join(directory(), stale.file), { force: true });
148
+ } catch {
149
+ // housekeeping must never block a task
150
+ }
151
+ }
152
+
153
+ /** Never throws: persistence is an optimisation, not a dependency. */
154
+ export function writeSavedTools(sessionId: string, state: SavedToolsState): boolean {
155
+ try {
156
+ const bounded: SavedToolsState = {
157
+ packs: names(state.packs),
158
+ tools: names(state.tools),
159
+ order: names(state.order)
160
+ };
161
+ fs.mkdirSync(directory(), { recursive: true, mode: 0o700 });
162
+ atomicWriteFileSync(savedToolsPath(sessionId), JSON.stringify(bounded), { mode: 0o600 });
163
+ prune();
164
+ return true;
165
+ } catch {
166
+ return false;
167
+ }
168
+ }
169
+
@@ -0,0 +1,77 @@
1
+ /**
2
+ * @file src/session/cachePressure.ts
3
+ * Causyne Agent — Process Cache Pressure Monitor & Cold Session Eviction
4
+ *
5
+ * Adapted from Hermes Agent (gateway/agent_cache_pressure.py) and OpenCode session management.
6
+ * Monitors process RSS against memory thresholds and evicts cold sessions from memory
7
+ * while strictly protecting the most recent warm sessions to preserve KV prompt cache value.
8
+ *
9
+ * Authorship: Strict TypeScript (Causyne Agent).
10
+ */
11
+ import * as os from 'node:os';
12
+ export class SessionCachePressure {
13
+ config;
14
+ constructor(customConfig) {
15
+ this.config = {
16
+ autoBudgetFraction: customConfig?.autoBudgetFraction ?? 0.65,
17
+ autoBudgetFloorMb: customConfig?.autoBudgetFloorMb ?? 512,
18
+ maxEvictionsPerPass: customConfig?.maxEvictionsPerPass ?? 16,
19
+ protectRecent: customConfig?.protectRecent ?? 8,
20
+ };
21
+ }
22
+ getConfig() {
23
+ return { ...this.config };
24
+ }
25
+ getProcessMemoryUsageMb() {
26
+ const memory = process.memoryUsage();
27
+ return Math.round(memory.rss / (1024 * 1024));
28
+ }
29
+ calculateThresholdMb(totalSystemMemoryMb) {
30
+ const totalMb = totalSystemMemoryMb ?? Math.round(os.totalmem() / (1024 * 1024));
31
+ const calculatedBudget = Math.round(totalMb * this.config.autoBudgetFraction);
32
+ return Math.max(this.config.autoBudgetFloorMb, calculatedBudget);
33
+ }
34
+ isUnderPressure(totalSystemMemoryMb) {
35
+ const rssMb = this.getProcessMemoryUsageMb();
36
+ const thresholdMb = this.calculateThresholdMb(totalSystemMemoryMb);
37
+ return rssMb > thresholdMb;
38
+ }
39
+ /**
40
+ * Evaluates memory pressure and identifies cold sessions to evict.
41
+ * Protects the hottest `protectRecent` sessions and pinned sessions.
42
+ */
43
+ evaluateEvictions(sessions, forceCheck = false, mockRssMb) {
44
+ const rssMb = mockRssMb ?? this.getProcessMemoryUsageMb();
45
+ const thresholdMb = this.calculateThresholdMb();
46
+ const underPressure = forceCheck || rssMb > thresholdMb;
47
+ if (!underPressure || sessions.length <= this.config.protectRecent) {
48
+ return {
49
+ underPressure,
50
+ rssMb,
51
+ thresholdMb,
52
+ evictedSessionIds: [],
53
+ reclaimedBytes: 0,
54
+ };
55
+ }
56
+ // Sort descending by lastActiveAt (hottest first)
57
+ const sorted = [...sessions].sort((a, b) => b.lastActiveAt - a.lastActiveAt);
58
+ // Protect the top `protectRecent` warm sessions
59
+ const protectedIds = new Set(sorted.slice(0, this.config.protectRecent).map(s => s.id));
60
+ // Candidates for eviction: oldest first (excluding protected and pinned)
61
+ const candidates = sorted
62
+ .slice(this.config.protectRecent)
63
+ .filter(s => !s.isPinned && !protectedIds.has(s.id))
64
+ .reverse(); // Oldest first
65
+ const toEvict = candidates.slice(0, this.config.maxEvictionsPerPass);
66
+ const evictedSessionIds = toEvict.map(s => s.id);
67
+ const reclaimedBytes = toEvict.reduce((sum, s) => sum + s.estimatedBytes, 0);
68
+ return {
69
+ underPressure,
70
+ rssMb,
71
+ thresholdMb,
72
+ evictedSessionIds,
73
+ reclaimedBytes,
74
+ };
75
+ }
76
+ }
77
+ export const defaultCachePressure = new SessionCachePressure();
@@ -0,0 +1,122 @@
1
+ /**
2
+ * @file src/session/cachePressure.ts
3
+ * Causyne Agent — Process Cache Pressure Monitor & Cold Session Eviction
4
+ *
5
+ * Adapted from Hermes Agent (gateway/agent_cache_pressure.py) and OpenCode session management.
6
+ * Monitors process RSS against memory thresholds and evicts cold sessions from memory
7
+ * while strictly protecting the most recent warm sessions to preserve KV prompt cache value.
8
+ *
9
+ * Authorship: Strict TypeScript (Causyne Agent).
10
+ */
11
+
12
+ import * as os from 'node:os';
13
+
14
+ export interface CachePressureConfig {
15
+ /** Fraction of available system/cgroup memory to treat as threshold (default: 0.65). */
16
+ autoBudgetFraction: number;
17
+ /** Minimum memory floor in MB before pressure triggers (default: 512 MB). */
18
+ autoBudgetFloorMb: number;
19
+ /** Maximum number of sessions to evict in a single pass (default: 16). */
20
+ maxEvictionsPerPass: number;
21
+ /** Number of most-recently-active sessions to protect from eviction (default: 8). */
22
+ protectRecent: number;
23
+ }
24
+
25
+ export interface SessionMemoryRecord {
26
+ id: string;
27
+ lastActiveAt: number;
28
+ estimatedBytes: number;
29
+ isPinned?: boolean;
30
+ }
31
+
32
+ export interface EvictionResult {
33
+ underPressure: boolean;
34
+ rssMb: number;
35
+ thresholdMb: number;
36
+ evictedSessionIds: string[];
37
+ reclaimedBytes: number;
38
+ }
39
+
40
+ export class SessionCachePressure {
41
+ private config: CachePressureConfig;
42
+
43
+ constructor(customConfig?: Partial<CachePressureConfig>) {
44
+ this.config = {
45
+ autoBudgetFraction: customConfig?.autoBudgetFraction ?? 0.65,
46
+ autoBudgetFloorMb: customConfig?.autoBudgetFloorMb ?? 512,
47
+ maxEvictionsPerPass: customConfig?.maxEvictionsPerPass ?? 16,
48
+ protectRecent: customConfig?.protectRecent ?? 8,
49
+ };
50
+ }
51
+
52
+ public getConfig(): Readonly<CachePressureConfig> {
53
+ return { ...this.config };
54
+ }
55
+
56
+ public getProcessMemoryUsageMb(): number {
57
+ const memory = process.memoryUsage();
58
+ return Math.round(memory.rss / (1024 * 1024));
59
+ }
60
+
61
+ public calculateThresholdMb(totalSystemMemoryMb?: number): number {
62
+ const totalMb = totalSystemMemoryMb ?? Math.round(os.totalmem() / (1024 * 1024));
63
+ const calculatedBudget = Math.round(totalMb * this.config.autoBudgetFraction);
64
+ return Math.max(this.config.autoBudgetFloorMb, calculatedBudget);
65
+ }
66
+
67
+ public isUnderPressure(totalSystemMemoryMb?: number): boolean {
68
+ const rssMb = this.getProcessMemoryUsageMb();
69
+ const thresholdMb = this.calculateThresholdMb(totalSystemMemoryMb);
70
+ return rssMb > thresholdMb;
71
+ }
72
+
73
+ /**
74
+ * Evaluates memory pressure and identifies cold sessions to evict.
75
+ * Protects the hottest `protectRecent` sessions and pinned sessions.
76
+ */
77
+ public evaluateEvictions(
78
+ sessions: SessionMemoryRecord[],
79
+ forceCheck = false,
80
+ mockRssMb?: number
81
+ ): EvictionResult {
82
+ const rssMb = mockRssMb ?? this.getProcessMemoryUsageMb();
83
+ const thresholdMb = this.calculateThresholdMb();
84
+ const underPressure = forceCheck || rssMb > thresholdMb;
85
+
86
+ if (!underPressure || sessions.length <= this.config.protectRecent) {
87
+ return {
88
+ underPressure,
89
+ rssMb,
90
+ thresholdMb,
91
+ evictedSessionIds: [],
92
+ reclaimedBytes: 0,
93
+ };
94
+ }
95
+
96
+ // Sort descending by lastActiveAt (hottest first)
97
+ const sorted = [...sessions].sort((a, b) => b.lastActiveAt - a.lastActiveAt);
98
+
99
+ // Protect the top `protectRecent` warm sessions
100
+ const protectedIds = new Set(sorted.slice(0, this.config.protectRecent).map(s => s.id));
101
+
102
+ // Candidates for eviction: oldest first (excluding protected and pinned)
103
+ const candidates = sorted
104
+ .slice(this.config.protectRecent)
105
+ .filter(s => !s.isPinned && !protectedIds.has(s.id))
106
+ .reverse(); // Oldest first
107
+
108
+ const toEvict = candidates.slice(0, this.config.maxEvictionsPerPass);
109
+ const evictedSessionIds = toEvict.map(s => s.id);
110
+ const reclaimedBytes = toEvict.reduce((sum, s) => sum + s.estimatedBytes, 0);
111
+
112
+ return {
113
+ underPressure,
114
+ rssMb,
115
+ thresholdMb,
116
+ evictedSessionIds,
117
+ reclaimedBytes,
118
+ };
119
+ }
120
+ }
121
+
122
+ export const defaultCachePressure = new SessionCachePressure();
@@ -12,7 +12,8 @@ import { isMutatingToolCall } from './decisionPolicy.js';
12
12
  const INSPECTION_TOOLS = new Set([
13
13
  'fs_read', 'fs_list', 'fs_find', 'fs_search', 'grep_search', 'code_searcher',
14
14
  'codebase_search', 'web_search', 'web_fetch', 'browser_snapshot',
15
- 'browser_get_dom', 'view_image', 'pdf_read', 'dir_list'
15
+ 'browser_get_dom', 'view_image', 'pdf_read', 'dir_list',
16
+ 'read', 'read_file', 'view_file', 'viewfile', 'cat', 'glob', 'grep', 'search', 'list_dir', 'ls'
16
17
  ]);
17
18
  const VERIFICATION_TOOLS = new Set([
18
19
  'screenshot', 'vision_inspect_ui', 'browser_console', 'ax_snapshot'
@@ -20,18 +21,23 @@ const VERIFICATION_TOOLS = new Set([
20
21
  function isInspection(toolName, args) {
21
22
  if (INSPECTION_TOOLS.has(toolName))
22
23
  return true;
23
- if (toolName !== 'sysRun')
24
+ if (!['sysRun', 'bash', 'terminal', 'execute', 'sh', 'zsh'].includes(toolName))
24
25
  return false;
25
26
  return /^\s*(?:pwd|ls|find|rg|grep|cat|sed|head|tail|git\s+(?:status|diff|log|show)|npm\s+(?:view|audit))\b/i
26
- .test(String(args.command ?? ''));
27
+ .test(String(args.command ?? args.cmd ?? ''));
27
28
  }
28
29
  function isVerification(toolName, args) {
29
30
  if (VERIFICATION_TOOLS.has(toolName))
30
31
  return true;
31
- if (toolName !== 'sysRun')
32
+ if (toolName === 'browser_act') {
33
+ const actions = Array.isArray(args.actions) ? args.actions : [args];
34
+ return actions.some((item) => item !== null && typeof item === 'object'
35
+ && ['preview', 'screenshot', 'inspect', 'snapshot'].includes(String(item.action ?? item.type ?? '')));
36
+ }
37
+ if (!['sysRun', 'bash', 'terminal', 'execute', 'sh', 'zsh'].includes(toolName))
32
38
  return false;
33
- return /^\s*(?:npm\s+(?:test|run\s+(?:test|typecheck|build))|node\s+--check|pytest|cargo\s+test|go\s+test)\b/i
34
- .test(String(args.command ?? ''));
39
+ return /^\s*(?:npm\s+(?:test|run\s+(?:test|typecheck|build))|node\s+--check|pytest|cargo\s+test|go\s+test|python(?:3)?\s+-m\s+unittest|vitest|jest|playwright|cypress)\b/i
40
+ .test(String(args.command ?? args.cmd ?? ''));
35
41
  }
36
42
  /**
37
43
  * Bound each inspection batch to two calls, then yield to a synthesis step.
@@ -121,9 +127,9 @@ const SIMPLE_FILE_OP_PATTERN = /\b(list (the )?files|show files|count files|rena
121
127
  // Media generation intent (explicit creation of 3D, video, audio, or synthesized speech)
122
128
  const EXPLICIT_MEDIA_GENERATION_PATTERN = /\b(blender|3d model|render 3d|render frame|render animation|da vinci|resolve|audio synth|synthesizer|text to speech|tts|voiceover|dubbing)\b|\.blend\d*\b/i;
123
129
  // Explicit web engineering intent
124
- const EXPLICIT_WEB_ENGINEERING_PATTERN = /\b(build|create|make|design|develop|implement|redesign|buat\w*)\b[\s\S]*\b(web|website|webpage|webapp|landing page|dashboard|ui|frontend|threejs|three\.js|3js)\b/i;
130
+ const EXPLICIT_WEB_ENGINEERING_PATTERN = /\b(build|create|make|design|develop|implement|redesign|buat\w*)\b[\s\S]*\b(web|website|webpage|webapp|landing page|dashboard|ui|frontend|threejs|three\.js|thre\.?js|3js|webgl|canvas)\b/i;
125
131
  // Explicit game development intent
126
- const EXPLICIT_GAME_DEV_PATTERN = /\b(build.*game|create.*game|develop.*game|godot|unity|unreal|platformer 2d|rpg game|arcade game)\b/i;
132
+ const EXPLICIT_GAME_DEV_PATTERN = /(?:\b(build.*(?:game|simulation|simulator)|create.*(?:game|simulation|simulator)|develop.*(?:game|simulation|simulator)|buat\w*.*(?:game|simulation|simulator)|bikin\w*.*(?:game|simulation|simulator)|game|gamedev|godot|unity|unreal|platformer|rpg|arcade|simulator|simulation|simulasi|interactive|3d\s*(?:game|app|simulator|scene|city|world|view))\b|[-_]3d\b|\b3d[-_]|\b(?:threejs|three\.js|webgl|canvas3d|babylonjs)\b)/i;
127
133
  /**
128
134
  * Select tools to preload based on prompt intent. This is never an allowlist:
129
135
  * tool_search can add capabilities as the task develops.
@@ -208,6 +214,7 @@ export function determineToolScope(prompt, _taskShape) {
208
214
  reason: 'Simple filesystem operation; suppresses external domain packs.'
209
215
  };
210
216
  }
217
+ // 5. Web engineering intent (websites, web applications, landing pages, Three.js web scenes)
211
218
  if (EXPLICIT_WEB_ENGINEERING_PATTERN.test(text)) {
212
219
  const tools = new Set([
213
220
  'fs_write',
@@ -228,7 +235,7 @@ export function determineToolScope(prompt, _taskShape) {
228
235
  reason: 'Web engineering intent focuses on filesystem authoring, terminal execution, and browser verification; suppresses unrelated media and game packs.'
229
236
  };
230
237
  }
231
- // 5. Media / 3D generation & creative audio intent
238
+ // 6. Media / 3D generation & creative audio intent
232
239
  if (EXPLICIT_MEDIA_GENERATION_PATTERN.test(text)) {
233
240
  const tools = new Set([
234
241
  'blender_act',
@@ -248,6 +255,27 @@ export function determineToolScope(prompt, _taskShape) {
248
255
  reason: 'Media generation intent prioritizes 3D studio, procedural media, and image inspection; suppresses web and game packs.'
249
256
  };
250
257
  }
258
+ // 7. Game development and interactive simulation intent (simulators, 3D worlds, games)
259
+ if (EXPLICIT_GAME_DEV_PATTERN.test(text)) {
260
+ const tools = new Set([
261
+ 'fs_write',
262
+ 'fs_edit',
263
+ 'fs_read',
264
+ 'fs_list',
265
+ 'sysRun',
266
+ 'browser_act',
267
+ 'screenshot',
268
+ 'vision_inspect_ui',
269
+ 'update_plan',
270
+ 'tool_search'
271
+ ]);
272
+ return {
273
+ toolScope: tools,
274
+ archetype: 'game_development',
275
+ suppressedPacks: ['media', 'advanced', 'system'],
276
+ reason: 'Game development and simulation intent focuses on game code, assets, terminal execution, and browser/screen verification.'
277
+ };
278
+ }
251
279
  // Default: unconstrained (standard progressive disclosure and packs apply)
252
280
  return {
253
281
  toolScope: null,
@@ -282,14 +310,14 @@ export function resolveLazyPlaybooks(unlockedPacks, observedTools = [], prompt =
282
310
  const activeDomains = [];
283
311
  let tokenSavings = 0;
284
312
  // 1. Web Domain
285
- if (packs.has('web')) {
313
+ const webExplicitDemand = EXPLICIT_WEB_ENGINEERING_PATTERN.test(text)
314
+ || (isWebIntent(text) && WEB_CONSTRUCTION_EXCLUSION.test(text));
315
+ if (packs.has('web') || webExplicitDemand || tools.has('ui_forge') || tools.has('astryx_oracle')) {
286
316
  const webToolInvoked = tools.has('ui_forge') ||
287
317
  tools.has('browser_act') ||
288
318
  tools.has('vision_inspect_ui') ||
289
319
  tools.has('screenshot') ||
290
320
  tools.has('astryx_oracle');
291
- const webExplicitDemand = EXPLICIT_WEB_ENGINEERING_PATTERN.test(text)
292
- || (isWebIntent(text) && WEB_CONSTRUCTION_EXCLUSION.test(text));
293
321
  if ((webToolInvoked || webExplicitDemand) && PACK_PLAYBOOKS.web) {
294
322
  activePlaybooks.push(PACK_PLAYBOOKS.web);
295
323
  activeDomains.push('web');
@@ -340,3 +368,32 @@ export function resolveLazyPlaybooks(unlockedPacks, observedTools = [], prompt =
340
368
  tokenSavingsEstimate: tokenSavings
341
369
  };
342
370
  }
371
+ /** A mid-task decision may load at most this many schemas at once. */
372
+ export const MAX_ADMIT_PER_STEP = 8;
373
+ /**
374
+ * The smart part: admit only the delta, bound what one step may load, and say
375
+ * what the loop owes before it changes anything. A task the user must decide
376
+ * or plan first keeps the tool for that step reachable, so the checkpoint can
377
+ * never be demanded of a model that was not given the means to meet it.
378
+ */
379
+ export function refineToolDecision(decision, context) {
380
+ const admittedTools = context.admittedTools ?? new Set();
381
+ const admittedPacks = context.admittedPacks ?? new Set();
382
+ const fresh = decision.tools.filter((name) => !admittedTools.has(name));
383
+ const packs = decision.packs.filter((name) => !admittedPacks.has(name));
384
+ const reasons = [...decision.reasons];
385
+ let tools = fresh;
386
+ let deferred = [];
387
+ if (decision.source !== 'intent' && fresh.length > MAX_ADMIT_PER_STEP) {
388
+ tools = fresh.slice(0, MAX_ADMIT_PER_STEP);
389
+ deferred = fresh.slice(MAX_ADMIT_PER_STEP);
390
+ reasons.push(`deferred ${deferred.length} to protect context`);
391
+ }
392
+ const route = context.decisionRequired ? 'decision' : context.planRequired ? 'plan' : 'direct';
393
+ if (decision.source === 'intent') {
394
+ const needed = route === 'decision' ? 'request_decision' : route === 'plan' ? 'update_plan' : '';
395
+ if (needed && !admittedTools.has(needed) && !tools.includes(needed))
396
+ tools = [...tools, needed];
397
+ }
398
+ return { source: decision.source, tools, packs, deferred, route, reasons };
399
+ }