@causyne/agent 1.20.10 → 1.20.12
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/LICENSE +1 -1
- package/docs/ARCHITECTURE.md +24 -1
- package/package.json +1 -1
- package/src/acp/client.js +9 -2
- package/src/acp/client.ts +11 -2
- package/src/acp/protocol.ts +9 -0
- package/src/agentLoop.js +504 -119
- package/src/agentLoop.ts +477 -121
- package/src/browser/browserRuntime.js +47 -0
- package/src/browser/browserRuntime.ts +45 -0
- package/src/browser/causyneBrowser.js +60 -31
- package/src/browser/causyneBrowser.ts +37 -12
- package/src/browser/workspacePreview.js +52 -0
- package/src/browser/workspacePreview.ts +49 -0
- package/src/core/planCache.js +5 -0
- package/src/core/planCache.ts +5 -0
- package/src/decisionPolicy.js +9 -0
- package/src/decisionPolicy.ts +8 -0
- package/src/historyPruner.js +251 -0
- package/src/historyPruner.ts +263 -0
- package/src/infra/atomicWriter.js +49 -0
- package/src/infra/atomicWriter.ts +63 -0
- package/src/infra/telemetry.js +38 -0
- package/src/infra/telemetry.ts +68 -0
- package/src/observer/coldObserver.js +12 -7
- package/src/observer/coldObserver.ts +12 -7
- package/src/observer/evidence.js +8 -2
- package/src/observer/evidence.ts +9 -2
- package/src/outputRecovery.js +36 -0
- package/src/outputRecovery.ts +33 -0
- package/src/providers/acp.js +114 -46
- package/src/providers/acp.ts +129 -46
- package/src/providers/antigravity.js +262 -91
- package/src/providers/antigravity.ts +270 -99
- package/src/providers/antigravityBridge.js +58 -0
- package/src/providers/antigravityBridge.ts +51 -0
- package/src/providers/base.d.ts +9 -0
- package/src/providers/budgetEnforcer.js +110 -0
- package/src/providers/budgetEnforcer.ts +122 -0
- package/src/providers/collaborationPolicy.js +6 -0
- package/src/providers/collaborationPolicy.ts +7 -0
- package/src/providers/loopGuard.js +84 -0
- package/src/providers/loopGuard.ts +105 -0
- package/src/providers/pi.js +19 -6
- package/src/providers/pi.ts +19 -7
- package/src/providers/toolContracts.js +36 -0
- package/src/providers/toolContracts.ts +48 -0
- package/src/session/sidechainEvents.js +49 -0
- package/src/session/sidechainEvents.ts +98 -0
- package/src/skillsManager.d.ts +1 -0
- package/src/smartToolsUse.js +123 -4
- package/src/smartToolsUse.ts +136 -4
- package/src/stallGuard.js +3 -12
- package/src/stallGuard.ts +3 -12
- package/src/subagent/sidechainHarness.js +66 -0
- package/src/subagent/sidechainHarness.ts +91 -0
- package/src/taskContinuation.js +12 -0
- package/src/taskContinuation.ts +13 -0
- package/src/tokenTracker.js +406 -539
- package/src/tokenTracker.ts +569 -0
- package/src/toolPacks.d.ts +2 -0
- package/src/toolPacks.js +1 -1
- package/src/tools/argumentValidation.js +56 -0
- package/src/tools/argumentValidation.ts +50 -0
- package/src/tools/browserAutomator.js +2 -2
- package/src/tools/browserAutomator.ts +3 -2
- package/src/tools/deferredMcpSearch.js +188 -201
- package/src/tools/deferredMcpSearch.ts +250 -0
- package/src/tools/generateMediaViaApi.js +305 -331
- package/src/tools/generateMediaViaApi.ts +330 -0
- package/src/tools/historyPruner.js +5 -0
- package/src/tools/historyPruner.ts +5 -0
- package/src/tools/payloadSanitizer.js +92 -0
- package/src/tools/payloadSanitizer.ts +113 -0
- package/src/tools/registry.d.ts +1 -0
- package/src/tools/sysRun.js +47 -18
- package/src/tools/sysRun.ts +52 -20
- package/src/tools/toolOutputStore.js +180 -0
- package/src/tools/toolOutputStore.ts +209 -0
- package/src/tools/toolSelfRepair.js +26 -1
- package/src/tools/toolSelfRepair.ts +25 -1
- package/src/tui/chatRenderer.d.ts +1 -0
- package/src/tui/chatRenderer.js +4 -2
- package/src/tui/codeStreamRenderer.js +36 -8
- package/src/tui/codeStreamRenderer.ts +38 -8
- package/src/tui/stageSurface.js +1 -0
- package/src/tui/text.js +4 -1
- package/src/tokenTracker.d.ts +0 -1
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
import { spillToolResult, buildDecayPointer } from './outputStore.js';
|
|
2
|
+
import { processToolOutputWithStore, renderSpillDocument } from './tools/toolOutputStore.js';
|
|
3
|
+
/** Archive large arguments only after a matching tool observation exists. */
|
|
4
|
+
export function pruneExecutedToolArguments(messages, options = {}) {
|
|
5
|
+
const completed = new Set(messages.filter(message => message.role === 'tool').map(message => message.tool_call_id));
|
|
6
|
+
const recoveryPaths = [];
|
|
7
|
+
let pruned = 0, reclaimedChars = 0, spillFailures = 0;
|
|
8
|
+
for (let index = 0; index < messages.length; index++) {
|
|
9
|
+
const message = messages[index];
|
|
10
|
+
if (message?.role !== 'assistant')
|
|
11
|
+
continue;
|
|
12
|
+
for (const call of message.tool_calls || []) {
|
|
13
|
+
const original = call.function?.arguments;
|
|
14
|
+
if (typeof original !== 'string' || !call.id || !completed.has(call.id))
|
|
15
|
+
continue;
|
|
16
|
+
let args;
|
|
17
|
+
try {
|
|
18
|
+
const parsed = JSON.parse(original);
|
|
19
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
|
|
20
|
+
continue;
|
|
21
|
+
args = parsed;
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
continue;
|
|
25
|
+
}
|
|
26
|
+
if (typeof args._causyne_archived_args === 'string') {
|
|
27
|
+
recoveryPaths.push(args._causyne_archived_args);
|
|
28
|
+
continue;
|
|
29
|
+
}
|
|
30
|
+
if (original.length <= (options.threshold ?? 2500))
|
|
31
|
+
continue;
|
|
32
|
+
const stored = processToolOutputWithStore(options.taskId ?? 'history', `arguments-${call.id}`, renderSpillDocument(args, { taskId: options.taskId ?? 'history', step: index, tool: call.function?.name ?? 'tool' }));
|
|
33
|
+
if (!stored.diskPath) {
|
|
34
|
+
spillFailures++;
|
|
35
|
+
continue;
|
|
36
|
+
}
|
|
37
|
+
const compact = {
|
|
38
|
+
_causyne_archived_args: stored.diskPath,
|
|
39
|
+
note: 'Historical executed call; complete parameters are archived. Do not replay this placeholder. Read the current target file or archived parameters if needed.'
|
|
40
|
+
};
|
|
41
|
+
for (const key of ['path', 'file_path', 'target', 'action']) {
|
|
42
|
+
if (typeof args[key] === 'string' && args[key].length <= 500)
|
|
43
|
+
compact[key] = args[key];
|
|
44
|
+
}
|
|
45
|
+
const replacement = JSON.stringify(compact);
|
|
46
|
+
if (replacement.length >= original.length || !call.function)
|
|
47
|
+
continue;
|
|
48
|
+
call.function.arguments = replacement;
|
|
49
|
+
recoveryPaths.push(stored.diskPath);
|
|
50
|
+
pruned++;
|
|
51
|
+
reclaimedChars += original.length - replacement.length;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
return { pruned, reclaimedChars, spillFailures, recoveryPaths };
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Shorten a single oversized observation only after preserving the complete
|
|
58
|
+
* result. Recent observations need this path too: the last-four policy does
|
|
59
|
+
* not make a 60 KB result safe to resend in full on every model call.
|
|
60
|
+
*/
|
|
61
|
+
export function shortenOversizedToolObservations(messages, options = {}) {
|
|
62
|
+
const threshold = Math.max(1, options.threshold ?? 2500);
|
|
63
|
+
let pruned = 0;
|
|
64
|
+
let reclaimedChars = 0;
|
|
65
|
+
let spillFailures = 0;
|
|
66
|
+
for (let index = 0; index < messages.length; index++) {
|
|
67
|
+
const message = messages[index];
|
|
68
|
+
if (!message || message.role !== 'tool' || typeof message.content !== 'string')
|
|
69
|
+
continue;
|
|
70
|
+
const original = message.content;
|
|
71
|
+
if (original.length <= threshold || original.startsWith(MARKER))
|
|
72
|
+
continue;
|
|
73
|
+
let spillPath = message.spillPath;
|
|
74
|
+
if (!spillPath) {
|
|
75
|
+
const spill = spillToolResult(original, {
|
|
76
|
+
taskId: options.taskId ?? 'history', step: index, tool: message.name ?? 'tool'
|
|
77
|
+
});
|
|
78
|
+
if (!spill || typeof spill.path !== 'string') {
|
|
79
|
+
spillFailures++;
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
spillPath = spill.path;
|
|
83
|
+
}
|
|
84
|
+
const headLen = Math.min(3000, Math.max(200, Math.floor(threshold * 0.45)));
|
|
85
|
+
const tailLen = Math.min(1500, Math.max(200, Math.floor(threshold * 0.35)));
|
|
86
|
+
const head = original.slice(0, headLen);
|
|
87
|
+
const tail = original.slice(-tailLen);
|
|
88
|
+
const omitted = original.length - head.length - tail.length;
|
|
89
|
+
const shortened = `${head}\n[${omitted} middle characters omitted from active context. Full output saved${buildDecayPointer({ path: spillPath })}]\n${tail}`;
|
|
90
|
+
if (shortened.length >= original.length)
|
|
91
|
+
continue;
|
|
92
|
+
message.content = shortened;
|
|
93
|
+
if (spillPath)
|
|
94
|
+
message.spillPath = spillPath;
|
|
95
|
+
pruned++;
|
|
96
|
+
reclaimedChars += original.length - shortened.length;
|
|
97
|
+
}
|
|
98
|
+
return { pruned, reclaimedChars, spillFailures };
|
|
99
|
+
}
|
|
100
|
+
/** Keep a small recovery index when old messages leave the active window. */
|
|
101
|
+
export function buildRecoverableDroppedSummary(dropped, baseSummary, maxPointers = 8) {
|
|
102
|
+
const paths = new Map();
|
|
103
|
+
for (const message of dropped) {
|
|
104
|
+
for (const call of message.role === 'assistant' ? message.tool_calls ?? [] : []) {
|
|
105
|
+
try {
|
|
106
|
+
const args = typeof call.function?.arguments === 'string' ? JSON.parse(call.function.arguments) : null;
|
|
107
|
+
if (args && typeof args === 'object' && '_causyne_archived_args' in args
|
|
108
|
+
&& typeof args._causyne_archived_args === 'string') {
|
|
109
|
+
paths.set(args._causyne_archived_args, `${call.function?.name ?? 'tool'} arguments (outcome unverified): ${args._causyne_archived_args}`);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
catch { /* Unarchived or malformed historical arguments have no recovery pointer. */ }
|
|
113
|
+
}
|
|
114
|
+
// A later compaction may remove an earlier compaction summary. Carry its
|
|
115
|
+
// recovery index forward so repeated compaction does not orphan files.
|
|
116
|
+
if (message.role === 'user' && typeof message.content === 'string'
|
|
117
|
+
&& message.content.startsWith('[COMPACTED CONTEXT SUMMARY — ')) {
|
|
118
|
+
for (const line of message.content.split('\n')) {
|
|
119
|
+
const prior = /^([^\n]+ \((?:reported success|reported failure|outcome unverified)\): (\/[^\n]+))$/.exec(line);
|
|
120
|
+
if (prior?.[2])
|
|
121
|
+
paths.set(prior[2], line);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
if (message.role !== 'tool' || !message.spillPath)
|
|
125
|
+
continue;
|
|
126
|
+
const verdict = typeof message.content === 'string' && message.content.startsWith(MARKER)
|
|
127
|
+
? (/^\[decayed\] [^:]+: (reported success|reported failure|outcome unverified)/.exec(message.content)?.[1]
|
|
128
|
+
?? 'outcome unverified')
|
|
129
|
+
: typeof message.content === 'string' ? verdictFor(message.content) : 'outcome unverified';
|
|
130
|
+
paths.set(message.spillPath, `${message.name ?? 'tool'} (${verdict}): ${message.spillPath}`);
|
|
131
|
+
}
|
|
132
|
+
if (paths.size === 0)
|
|
133
|
+
return baseSummary;
|
|
134
|
+
const recent = [...paths.values()].slice(-Math.max(0, maxPointers));
|
|
135
|
+
const omitted = paths.size - recent.length;
|
|
136
|
+
const index = `Recoverable prior tool output (${paths.size} saved; local files expire after retention):\n`
|
|
137
|
+
+ recent.join('\n')
|
|
138
|
+
+ (omitted > 0 ? `\n${omitted} older saved outputs omitted from this summary.` : '');
|
|
139
|
+
return baseSummary ? `${baseSummary}\n${index}` : index;
|
|
140
|
+
}
|
|
141
|
+
const MARKER = '[decayed]';
|
|
142
|
+
function verdictFor(content) {
|
|
143
|
+
try {
|
|
144
|
+
const value = JSON.parse(content);
|
|
145
|
+
if (value && typeof value === 'object' && !Array.isArray(value)) {
|
|
146
|
+
const record = value;
|
|
147
|
+
if (record.success === true)
|
|
148
|
+
return 'reported success';
|
|
149
|
+
if (record.success === false)
|
|
150
|
+
return 'reported failure';
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
catch {
|
|
154
|
+
// Plain text and provider-specific results have no machine-verifiable verdict.
|
|
155
|
+
}
|
|
156
|
+
return 'outcome unverified';
|
|
157
|
+
}
|
|
158
|
+
function buildCallInfoMap(messages) {
|
|
159
|
+
const map = new Map();
|
|
160
|
+
for (const msg of messages) {
|
|
161
|
+
if (msg.role !== 'assistant')
|
|
162
|
+
continue;
|
|
163
|
+
for (const call of msg.tool_calls || []) {
|
|
164
|
+
if (!call.id || !call.function?.name)
|
|
165
|
+
continue;
|
|
166
|
+
const toolName = call.function.name;
|
|
167
|
+
let target;
|
|
168
|
+
const isInspection = /^(?:fs_read|read_file|view_file|cat|head|tail|grep|fs_list|dir_list|fs_search)$/i.test(toolName);
|
|
169
|
+
if (typeof call.function.arguments === 'string') {
|
|
170
|
+
try {
|
|
171
|
+
const args = JSON.parse(call.function.arguments);
|
|
172
|
+
if (args && typeof args === 'object') {
|
|
173
|
+
const rawTarget = args.path || args.file_path || args.AbsolutePath || args.target;
|
|
174
|
+
if (typeof rawTarget === 'string' && rawTarget.trim()) {
|
|
175
|
+
target = rawTarget.trim();
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
catch { /* ignore parse error */ }
|
|
180
|
+
}
|
|
181
|
+
map.set(call.id, { toolName, target, isInspection });
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
return map;
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* Preserve recent observations verbatim. Older large observations are replaced
|
|
188
|
+
* only after the complete text is saved to the private output store.
|
|
189
|
+
*
|
|
190
|
+
* Additionally enforces the ClosedWindow pattern (SWE-agent arXiv:2405.15793):
|
|
191
|
+
* Earlier inspections of the same target file within the window are compacted
|
|
192
|
+
* to a lightweight pointer since the latest inspection is already in context.
|
|
193
|
+
*/
|
|
194
|
+
export function pruneStaleToolObservations(messages, options = {}) {
|
|
195
|
+
const keepRecent = Math.max(0, options.keepRecent ?? 4);
|
|
196
|
+
const minChars = Math.max(1, options.minChars ?? 600);
|
|
197
|
+
const callInfoMap = buildCallInfoMap(messages);
|
|
198
|
+
const seenTargets = new Set();
|
|
199
|
+
let seen = 0;
|
|
200
|
+
let pruned = 0;
|
|
201
|
+
let reclaimedChars = 0;
|
|
202
|
+
let spillFailures = 0;
|
|
203
|
+
for (let index = messages.length - 1; index >= 0; index--) {
|
|
204
|
+
const message = messages[index];
|
|
205
|
+
if (!message || message.role !== 'tool')
|
|
206
|
+
continue;
|
|
207
|
+
seen++;
|
|
208
|
+
if (typeof message.content !== 'string')
|
|
209
|
+
continue;
|
|
210
|
+
const original = message.content;
|
|
211
|
+
if (original.startsWith(MARKER))
|
|
212
|
+
continue;
|
|
213
|
+
const callInfo = message.tool_call_id ? callInfoMap.get(message.tool_call_id) : undefined;
|
|
214
|
+
const target = callInfo?.target;
|
|
215
|
+
const isDuplicateInspection = Boolean(callInfo?.isInspection && target && seenTargets.has(target));
|
|
216
|
+
if (callInfo?.isInspection && target) {
|
|
217
|
+
seenTargets.add(target);
|
|
218
|
+
}
|
|
219
|
+
if (seen <= keepRecent && !isDuplicateInspection)
|
|
220
|
+
continue;
|
|
221
|
+
if (original.length < minChars)
|
|
222
|
+
continue;
|
|
223
|
+
let spillPath = message.spillPath;
|
|
224
|
+
if (!spillPath) {
|
|
225
|
+
const spill = spillToolResult(original, {
|
|
226
|
+
taskId: options.taskId ?? 'history',
|
|
227
|
+
step: index,
|
|
228
|
+
tool: message.name ?? 'tool'
|
|
229
|
+
});
|
|
230
|
+
if (!spill || typeof spill.path !== 'string') {
|
|
231
|
+
spillFailures++;
|
|
232
|
+
continue;
|
|
233
|
+
}
|
|
234
|
+
spillPath = spill.path;
|
|
235
|
+
}
|
|
236
|
+
const summary = isDuplicateInspection
|
|
237
|
+
? `${MARKER} ${message.name ?? 'tool'}: [Prior inspection of ${target} omitted; latest inspection is in active context.]`
|
|
238
|
+
+ buildDecayPointer({ path: spillPath })
|
|
239
|
+
: `${MARKER} ${message.name ?? 'tool'}: ${verdictFor(original)}. `
|
|
240
|
+
+ `Earlier output (${original.length} characters) was cleared from context.`
|
|
241
|
+
+ buildDecayPointer({ path: spillPath });
|
|
242
|
+
if (summary.length >= original.length)
|
|
243
|
+
continue;
|
|
244
|
+
message.content = summary;
|
|
245
|
+
if (spillPath)
|
|
246
|
+
message.spillPath = spillPath;
|
|
247
|
+
pruned++;
|
|
248
|
+
reclaimedChars += original.length - summary.length;
|
|
249
|
+
}
|
|
250
|
+
return { pruned, reclaimedChars, spillFailures };
|
|
251
|
+
}
|
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
import { spillToolResult, buildDecayPointer } from './outputStore.js';
|
|
2
|
+
import { processToolOutputWithStore, renderSpillDocument } from './tools/toolOutputStore.js';
|
|
3
|
+
|
|
4
|
+
export interface ToolObservation {
|
|
5
|
+
role: string;
|
|
6
|
+
name?: string;
|
|
7
|
+
content: unknown;
|
|
8
|
+
spillPath?: string;
|
|
9
|
+
tool_call_id?: string;
|
|
10
|
+
tool_calls?: Array<{ id?: string; function?: { name?: string; arguments?: unknown } }>;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** Archive large arguments only after a matching tool observation exists. */
|
|
14
|
+
export function pruneExecutedToolArguments(
|
|
15
|
+
messages: ToolObservation[], options: { threshold?: number; taskId?: string } = {}
|
|
16
|
+
): ObservationPruneResult & { recoveryPaths: string[] } {
|
|
17
|
+
const completed = new Set(messages.filter(message => message.role === 'tool').map(message => message.tool_call_id));
|
|
18
|
+
const recoveryPaths: string[] = [];
|
|
19
|
+
let pruned = 0, reclaimedChars = 0, spillFailures = 0;
|
|
20
|
+
for (let index = 0; index < messages.length; index++) {
|
|
21
|
+
const message = messages[index];
|
|
22
|
+
if (message?.role !== 'assistant') continue;
|
|
23
|
+
for (const call of message.tool_calls || []) {
|
|
24
|
+
const original = call.function?.arguments;
|
|
25
|
+
if (typeof original !== 'string' || !call.id || !completed.has(call.id)) continue;
|
|
26
|
+
let args: Record<string, unknown>;
|
|
27
|
+
try {
|
|
28
|
+
const parsed: unknown = JSON.parse(original);
|
|
29
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) continue;
|
|
30
|
+
args = parsed as Record<string, unknown>;
|
|
31
|
+
} catch { continue; }
|
|
32
|
+
if (typeof args._causyne_archived_args === 'string') {
|
|
33
|
+
recoveryPaths.push(args._causyne_archived_args);
|
|
34
|
+
continue;
|
|
35
|
+
}
|
|
36
|
+
if (original.length <= (options.threshold ?? 2500)) continue;
|
|
37
|
+
const stored = processToolOutputWithStore(options.taskId ?? 'history', `arguments-${call.id}`,
|
|
38
|
+
renderSpillDocument(args, { taskId: options.taskId ?? 'history', step: index, tool: call.function?.name ?? 'tool' }));
|
|
39
|
+
if (!stored.diskPath) { spillFailures++; continue; }
|
|
40
|
+
const compact: Record<string, unknown> = {
|
|
41
|
+
_causyne_archived_args: stored.diskPath,
|
|
42
|
+
note: 'Historical executed call; complete parameters are archived. Do not replay this placeholder. Read the current target file or archived parameters if needed.'
|
|
43
|
+
};
|
|
44
|
+
for (const key of ['path', 'file_path', 'target', 'action']) {
|
|
45
|
+
if (typeof args[key] === 'string' && args[key].length <= 500) compact[key] = args[key];
|
|
46
|
+
}
|
|
47
|
+
const replacement = JSON.stringify(compact);
|
|
48
|
+
if (replacement.length >= original.length || !call.function) continue;
|
|
49
|
+
call.function.arguments = replacement;
|
|
50
|
+
recoveryPaths.push(stored.diskPath);
|
|
51
|
+
pruned++;
|
|
52
|
+
reclaimedChars += original.length - replacement.length;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
return { pruned, reclaimedChars, spillFailures, recoveryPaths };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export interface ObservationPruneResult {
|
|
59
|
+
pruned: number;
|
|
60
|
+
reclaimedChars: number;
|
|
61
|
+
spillFailures: number;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Shorten a single oversized observation only after preserving the complete
|
|
66
|
+
* result. Recent observations need this path too: the last-four policy does
|
|
67
|
+
* not make a 60 KB result safe to resend in full on every model call.
|
|
68
|
+
*/
|
|
69
|
+
export function shortenOversizedToolObservations(
|
|
70
|
+
messages: ToolObservation[],
|
|
71
|
+
options: { threshold?: number; taskId?: string } = {}
|
|
72
|
+
): ObservationPruneResult {
|
|
73
|
+
const threshold = Math.max(1, options.threshold ?? 2500);
|
|
74
|
+
let pruned = 0;
|
|
75
|
+
let reclaimedChars = 0;
|
|
76
|
+
let spillFailures = 0;
|
|
77
|
+
for (let index = 0; index < messages.length; index++) {
|
|
78
|
+
const message = messages[index];
|
|
79
|
+
if (!message || message.role !== 'tool' || typeof message.content !== 'string') continue;
|
|
80
|
+
const original = message.content;
|
|
81
|
+
if (original.length <= threshold || original.startsWith(MARKER)) continue;
|
|
82
|
+
let spillPath = message.spillPath;
|
|
83
|
+
if (!spillPath) {
|
|
84
|
+
const spill = spillToolResult(original, {
|
|
85
|
+
taskId: options.taskId ?? 'history', step: index, tool: message.name ?? 'tool'
|
|
86
|
+
});
|
|
87
|
+
if (!spill || typeof spill.path !== 'string') {
|
|
88
|
+
spillFailures++;
|
|
89
|
+
continue;
|
|
90
|
+
}
|
|
91
|
+
spillPath = spill.path;
|
|
92
|
+
}
|
|
93
|
+
const headLen = Math.min(3000, Math.max(200, Math.floor(threshold * 0.45)));
|
|
94
|
+
const tailLen = Math.min(1500, Math.max(200, Math.floor(threshold * 0.35)));
|
|
95
|
+
const head = original.slice(0, headLen);
|
|
96
|
+
const tail = original.slice(-tailLen);
|
|
97
|
+
const omitted = original.length - head.length - tail.length;
|
|
98
|
+
const shortened = `${head}\n[${omitted} middle characters omitted from active context. Full output saved${buildDecayPointer({ path: spillPath })}]\n${tail}`;
|
|
99
|
+
if (shortened.length >= original.length) continue;
|
|
100
|
+
message.content = shortened;
|
|
101
|
+
if (spillPath) message.spillPath = spillPath;
|
|
102
|
+
pruned++;
|
|
103
|
+
reclaimedChars += original.length - shortened.length;
|
|
104
|
+
}
|
|
105
|
+
return { pruned, reclaimedChars, spillFailures };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Keep a small recovery index when old messages leave the active window. */
|
|
109
|
+
export function buildRecoverableDroppedSummary(
|
|
110
|
+
dropped: ToolObservation[],
|
|
111
|
+
baseSummary: string,
|
|
112
|
+
maxPointers = 8
|
|
113
|
+
): string {
|
|
114
|
+
const paths = new Map<string, string>();
|
|
115
|
+
for (const message of dropped) {
|
|
116
|
+
for (const call of message.role === 'assistant' ? message.tool_calls ?? [] : []) {
|
|
117
|
+
try {
|
|
118
|
+
const args: unknown = typeof call.function?.arguments === 'string' ? JSON.parse(call.function.arguments) : null;
|
|
119
|
+
if (args && typeof args === 'object' && '_causyne_archived_args' in args
|
|
120
|
+
&& typeof args._causyne_archived_args === 'string') {
|
|
121
|
+
paths.set(args._causyne_archived_args, `${call.function?.name ?? 'tool'} arguments (outcome unverified): ${args._causyne_archived_args}`);
|
|
122
|
+
}
|
|
123
|
+
} catch { /* Unarchived or malformed historical arguments have no recovery pointer. */ }
|
|
124
|
+
}
|
|
125
|
+
// A later compaction may remove an earlier compaction summary. Carry its
|
|
126
|
+
// recovery index forward so repeated compaction does not orphan files.
|
|
127
|
+
if (message.role === 'user' && typeof message.content === 'string'
|
|
128
|
+
&& message.content.startsWith('[COMPACTED CONTEXT SUMMARY — ')) {
|
|
129
|
+
for (const line of message.content.split('\n')) {
|
|
130
|
+
const prior = /^([^\n]+ \((?:reported success|reported failure|outcome unverified)\): (\/[^\n]+))$/.exec(line);
|
|
131
|
+
if (prior?.[2]) paths.set(prior[2], line);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
if (message.role !== 'tool' || !message.spillPath) continue;
|
|
135
|
+
const verdict = typeof message.content === 'string' && message.content.startsWith(MARKER)
|
|
136
|
+
? (/^\[decayed\] [^:]+: (reported success|reported failure|outcome unverified)/.exec(message.content)?.[1]
|
|
137
|
+
?? 'outcome unverified')
|
|
138
|
+
: typeof message.content === 'string' ? verdictFor(message.content) : 'outcome unverified';
|
|
139
|
+
paths.set(message.spillPath, `${message.name ?? 'tool'} (${verdict}): ${message.spillPath}`);
|
|
140
|
+
}
|
|
141
|
+
if (paths.size === 0) return baseSummary;
|
|
142
|
+
const recent = [...paths.values()].slice(-Math.max(0, maxPointers));
|
|
143
|
+
const omitted = paths.size - recent.length;
|
|
144
|
+
const index = `Recoverable prior tool output (${paths.size} saved; local files expire after retention):\n`
|
|
145
|
+
+ recent.join('\n')
|
|
146
|
+
+ (omitted > 0 ? `\n${omitted} older saved outputs omitted from this summary.` : '');
|
|
147
|
+
return baseSummary ? `${baseSummary}\n${index}` : index;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const MARKER = '[decayed]';
|
|
151
|
+
|
|
152
|
+
function verdictFor(content: string): string {
|
|
153
|
+
try {
|
|
154
|
+
const value: unknown = JSON.parse(content);
|
|
155
|
+
if (value && typeof value === 'object' && !Array.isArray(value)) {
|
|
156
|
+
const record = value as Record<string, unknown>;
|
|
157
|
+
if (record.success === true) return 'reported success';
|
|
158
|
+
if (record.success === false) return 'reported failure';
|
|
159
|
+
}
|
|
160
|
+
} catch {
|
|
161
|
+
// Plain text and provider-specific results have no machine-verifiable verdict.
|
|
162
|
+
}
|
|
163
|
+
return 'outcome unverified';
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function buildCallInfoMap(messages: ToolObservation[]): Map<string, { toolName: string; target?: string | undefined; isInspection: boolean }> {
|
|
167
|
+
const map = new Map<string, { toolName: string; target?: string | undefined; isInspection: boolean }>();
|
|
168
|
+
for (const msg of messages) {
|
|
169
|
+
if (msg.role !== 'assistant') continue;
|
|
170
|
+
for (const call of msg.tool_calls || []) {
|
|
171
|
+
if (!call.id || !call.function?.name) continue;
|
|
172
|
+
const toolName = call.function.name;
|
|
173
|
+
let target: string | undefined;
|
|
174
|
+
const isInspection = /^(?:fs_read|read_file|view_file|cat|head|tail|grep|fs_list|dir_list|fs_search)$/i.test(toolName);
|
|
175
|
+
if (typeof call.function.arguments === 'string') {
|
|
176
|
+
try {
|
|
177
|
+
const args: any = JSON.parse(call.function.arguments);
|
|
178
|
+
if (args && typeof args === 'object') {
|
|
179
|
+
const rawTarget = args.path || args.file_path || args.AbsolutePath || args.target;
|
|
180
|
+
if (typeof rawTarget === 'string' && rawTarget.trim()) {
|
|
181
|
+
target = rawTarget.trim();
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
} catch { /* ignore parse error */ }
|
|
185
|
+
}
|
|
186
|
+
map.set(call.id, { toolName, target, isInspection });
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
return map;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* Preserve recent observations verbatim. Older large observations are replaced
|
|
194
|
+
* only after the complete text is saved to the private output store.
|
|
195
|
+
*
|
|
196
|
+
* Additionally enforces the ClosedWindow pattern (SWE-agent arXiv:2405.15793):
|
|
197
|
+
* Earlier inspections of the same target file within the window are compacted
|
|
198
|
+
* to a lightweight pointer since the latest inspection is already in context.
|
|
199
|
+
*/
|
|
200
|
+
export function pruneStaleToolObservations(
|
|
201
|
+
messages: ToolObservation[],
|
|
202
|
+
options: { keepRecent?: number; minChars?: number; taskId?: string } = {}
|
|
203
|
+
): ObservationPruneResult {
|
|
204
|
+
const keepRecent = Math.max(0, options.keepRecent ?? 4);
|
|
205
|
+
const minChars = Math.max(1, options.minChars ?? 600);
|
|
206
|
+
const callInfoMap = buildCallInfoMap(messages);
|
|
207
|
+
const seenTargets = new Set<string>();
|
|
208
|
+
|
|
209
|
+
let seen = 0;
|
|
210
|
+
let pruned = 0;
|
|
211
|
+
let reclaimedChars = 0;
|
|
212
|
+
let spillFailures = 0;
|
|
213
|
+
|
|
214
|
+
for (let index = messages.length - 1; index >= 0; index--) {
|
|
215
|
+
const message = messages[index];
|
|
216
|
+
if (!message || message.role !== 'tool') continue;
|
|
217
|
+
seen++;
|
|
218
|
+
if (typeof message.content !== 'string') continue;
|
|
219
|
+
const original = message.content;
|
|
220
|
+
if (original.startsWith(MARKER)) continue;
|
|
221
|
+
|
|
222
|
+
const callInfo = message.tool_call_id ? callInfoMap.get(message.tool_call_id) : undefined;
|
|
223
|
+
const target = callInfo?.target;
|
|
224
|
+
const isDuplicateInspection = Boolean(callInfo?.isInspection && target && seenTargets.has(target));
|
|
225
|
+
|
|
226
|
+
if (callInfo?.isInspection && target) {
|
|
227
|
+
seenTargets.add(target);
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
if (seen <= keepRecent && !isDuplicateInspection) continue;
|
|
231
|
+
if (original.length < minChars) continue;
|
|
232
|
+
|
|
233
|
+
let spillPath = message.spillPath;
|
|
234
|
+
if (!spillPath) {
|
|
235
|
+
const spill = spillToolResult(original, {
|
|
236
|
+
taskId: options.taskId ?? 'history',
|
|
237
|
+
step: index,
|
|
238
|
+
tool: message.name ?? 'tool'
|
|
239
|
+
});
|
|
240
|
+
if (!spill || typeof spill.path !== 'string') {
|
|
241
|
+
spillFailures++;
|
|
242
|
+
continue;
|
|
243
|
+
}
|
|
244
|
+
spillPath = spill.path;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
const summary = isDuplicateInspection
|
|
248
|
+
? `${MARKER} ${message.name ?? 'tool'}: [Prior inspection of ${target} omitted; latest inspection is in active context.]`
|
|
249
|
+
+ buildDecayPointer({ path: spillPath })
|
|
250
|
+
: `${MARKER} ${message.name ?? 'tool'}: ${verdictFor(original)}. `
|
|
251
|
+
+ `Earlier output (${original.length} characters) was cleared from context.`
|
|
252
|
+
+ buildDecayPointer({ path: spillPath });
|
|
253
|
+
|
|
254
|
+
if (summary.length >= original.length) continue;
|
|
255
|
+
|
|
256
|
+
message.content = summary;
|
|
257
|
+
if (spillPath) message.spillPath = spillPath;
|
|
258
|
+
pruned++;
|
|
259
|
+
reclaimedChars += original.length - summary.length;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
return { pruned, reclaimedChars, spillFailures };
|
|
263
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file src/infra/atomicWriter.ts
|
|
3
|
+
* Causyne Agent — POSIX Atomic Safe File Writer
|
|
4
|
+
*
|
|
5
|
+
* Implements lock-free atomic file writing using temporary files and POSIX
|
|
6
|
+
* atomic renameSync. Guarantees zero partial writes, zero file corruption,
|
|
7
|
+
* and concurrency safety across parallel subagents.
|
|
8
|
+
*
|
|
9
|
+
* Authorship: Strict TypeScript (Causyne Agent).
|
|
10
|
+
*/
|
|
11
|
+
import * as fs from 'node:fs';
|
|
12
|
+
import * as path from 'node:path';
|
|
13
|
+
import * as crypto from 'node:crypto';
|
|
14
|
+
export function atomicWriteFileSync(targetPath, content, options = {}) {
|
|
15
|
+
const resolved = path.resolve(targetPath);
|
|
16
|
+
const dir = path.dirname(resolved);
|
|
17
|
+
fs.mkdirSync(dir, { recursive: true, mode: options.mode ?? 0o755 });
|
|
18
|
+
const randomSuffix = crypto.randomBytes(6).toString('hex');
|
|
19
|
+
const tempPath = path.join(dir, `.${path.basename(resolved)}.${randomSuffix}.tmp`);
|
|
20
|
+
try {
|
|
21
|
+
if (typeof content === 'string') {
|
|
22
|
+
fs.writeFileSync(tempPath, content, {
|
|
23
|
+
encoding: options.encoding ?? 'utf8',
|
|
24
|
+
mode: options.mode ?? 0o644,
|
|
25
|
+
flag: 'wx'
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
else {
|
|
29
|
+
fs.writeFileSync(tempPath, content, {
|
|
30
|
+
mode: options.mode ?? 0o644,
|
|
31
|
+
flag: 'wx'
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
fs.renameSync(tempPath, resolved);
|
|
35
|
+
}
|
|
36
|
+
catch (err) {
|
|
37
|
+
try {
|
|
38
|
+
if (fs.existsSync(tempPath))
|
|
39
|
+
fs.unlinkSync(tempPath);
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
// Ignore cleanup error
|
|
43
|
+
}
|
|
44
|
+
throw err;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
export async function atomicWriteFile(targetPath, content, options = {}) {
|
|
48
|
+
atomicWriteFileSync(targetPath, content, options);
|
|
49
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file src/infra/atomicWriter.ts
|
|
3
|
+
* Causyne Agent — POSIX Atomic Safe File Writer
|
|
4
|
+
*
|
|
5
|
+
* Implements lock-free atomic file writing using temporary files and POSIX
|
|
6
|
+
* atomic renameSync. Guarantees zero partial writes, zero file corruption,
|
|
7
|
+
* and concurrency safety across parallel subagents.
|
|
8
|
+
*
|
|
9
|
+
* Authorship: Strict TypeScript (Causyne Agent).
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import * as fs from 'node:fs';
|
|
13
|
+
import * as path from 'node:path';
|
|
14
|
+
import * as crypto from 'node:crypto';
|
|
15
|
+
|
|
16
|
+
export interface AtomicWriteOptions {
|
|
17
|
+
mode?: number;
|
|
18
|
+
encoding?: BufferEncoding;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function atomicWriteFileSync(
|
|
22
|
+
targetPath: string,
|
|
23
|
+
content: string | Buffer,
|
|
24
|
+
options: AtomicWriteOptions = {}
|
|
25
|
+
): void {
|
|
26
|
+
const resolved = path.resolve(targetPath);
|
|
27
|
+
const dir = path.dirname(resolved);
|
|
28
|
+
fs.mkdirSync(dir, { recursive: true, mode: options.mode ?? 0o755 });
|
|
29
|
+
|
|
30
|
+
const randomSuffix = crypto.randomBytes(6).toString('hex');
|
|
31
|
+
const tempPath = path.join(dir, `.${path.basename(resolved)}.${randomSuffix}.tmp`);
|
|
32
|
+
|
|
33
|
+
try {
|
|
34
|
+
if (typeof content === 'string') {
|
|
35
|
+
fs.writeFileSync(tempPath, content, {
|
|
36
|
+
encoding: options.encoding ?? 'utf8',
|
|
37
|
+
mode: options.mode ?? 0o644,
|
|
38
|
+
flag: 'wx'
|
|
39
|
+
});
|
|
40
|
+
} else {
|
|
41
|
+
fs.writeFileSync(tempPath, content, {
|
|
42
|
+
mode: options.mode ?? 0o644,
|
|
43
|
+
flag: 'wx'
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
fs.renameSync(tempPath, resolved);
|
|
47
|
+
} catch (err) {
|
|
48
|
+
try {
|
|
49
|
+
if (fs.existsSync(tempPath)) fs.unlinkSync(tempPath);
|
|
50
|
+
} catch {
|
|
51
|
+
// Ignore cleanup error
|
|
52
|
+
}
|
|
53
|
+
throw err;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export async function atomicWriteFile(
|
|
58
|
+
targetPath: string,
|
|
59
|
+
content: string | Buffer,
|
|
60
|
+
options: AtomicWriteOptions = {}
|
|
61
|
+
): Promise<void> {
|
|
62
|
+
atomicWriteFileSync(targetPath, content, options);
|
|
63
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file src/infra/telemetry.ts
|
|
3
|
+
* Causyne Agent — Structured OpenTelemetry-Compatible Turn Telemetry
|
|
4
|
+
*
|
|
5
|
+
* Tracks fine-grained per-turn token metrics, cache hits, tool latency, and
|
|
6
|
+
* memory compaction savings for real-time performance auditing.
|
|
7
|
+
*
|
|
8
|
+
* Authorship: Strict TypeScript (Causyne Agent).
|
|
9
|
+
*/
|
|
10
|
+
export class TelemetryCollector {
|
|
11
|
+
records = [];
|
|
12
|
+
recordTurn(record) {
|
|
13
|
+
const fullRecord = {
|
|
14
|
+
...record,
|
|
15
|
+
timestamp: Date.now()
|
|
16
|
+
};
|
|
17
|
+
this.records.push(fullRecord);
|
|
18
|
+
return fullRecord;
|
|
19
|
+
}
|
|
20
|
+
getRecordsForTask(taskId) {
|
|
21
|
+
return this.records.filter(r => r.taskId === taskId);
|
|
22
|
+
}
|
|
23
|
+
getSummary(taskId) {
|
|
24
|
+
const active = taskId ? this.getRecordsForTask(taskId) : this.records;
|
|
25
|
+
return {
|
|
26
|
+
totalPromptTokens: active.reduce((sum, r) => sum + r.promptTokens, 0),
|
|
27
|
+
totalCompletionTokens: active.reduce((sum, r) => sum + r.completionTokens, 0),
|
|
28
|
+
totalCachedPromptTokens: active.reduce((sum, r) => sum + r.cachedPromptTokens, 0),
|
|
29
|
+
totalNoncachedTokens: active.reduce((sum, r) => sum + r.noncachedTokens, 0),
|
|
30
|
+
totalDurationMs: active.reduce((sum, r) => sum + r.durationMs, 0),
|
|
31
|
+
turnCount: active.length
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
clear() {
|
|
35
|
+
this.records = [];
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
export const defaultTelemetry = new TelemetryCollector();
|