@causyne/agent 1.20.35 → 1.20.38

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.
@@ -0,0 +1,229 @@
1
+ import fs from 'node:fs';
2
+
3
+ export interface HistoricalToolMessage {
4
+ role?: string | undefined;
5
+ name?: string | undefined;
6
+ tool_call_id?: string | undefined;
7
+ content?: unknown;
8
+ spillPath?: string | undefined;
9
+ }
10
+
11
+ export interface NormalizedHistoricalToolResult {
12
+ skipStep: boolean;
13
+ result: Record<string, unknown>;
14
+ plan?: Array<Record<string, unknown>> | undefined;
15
+ }
16
+
17
+ const DECAY_MARKER = '[decayed]';
18
+ const SPILL_HEADER_PREFIX = '=== CAUSYNE TOOL OUTPUT';
19
+
20
+ /**
21
+ * Strip internal context-compaction markers, ToolOutputStore spill headers,
22
+ * and middle-omission notices so the TUI only displays real tool output.
23
+ */
24
+ export function cleanToolOutputPreview(payload: string, toolName = ''): string {
25
+ if (!payload || typeof payload !== 'string') return '';
26
+ if (toolName === 'update_plan') return '';
27
+
28
+ const trimmed = payload.trim();
29
+ if (!trimmed || trimmed.startsWith(DECAY_MARKER)) return '';
30
+
31
+ let text = payload
32
+ .replace(/\x1b\[(?:[12]K|\d*G)/g, '\n')
33
+ .replace(/(https?:\/\/[^\s"'<>]+?\.[a-z]{2,10})([A-Z][a-z]{2,15}:\s)/g, '$1\n$2');
34
+
35
+ // Strip renderSpillDocument metadata header up to the first `--- field: ... ---` marker
36
+ if (text.startsWith(SPILL_HEADER_PREFIX)) {
37
+ const fieldHeaderMatch = /\n--- field: [^\n]+ ---\n/.exec(text);
38
+ if (fieldHeaderMatch && fieldHeaderMatch.index !== undefined) {
39
+ text = text.slice(fieldHeaderMatch.index + fieldHeaderMatch[0].length);
40
+ } else {
41
+ const blankLineIndex = text.indexOf('\n\n');
42
+ if (blankLineIndex !== -1) {
43
+ text = text.slice(blankLineIndex + 2);
44
+ }
45
+ }
46
+ }
47
+
48
+ // Strip internal ToolOutputStore and historyPruner middle-omission lines
49
+ const filteredLines = text
50
+ .split('\n')
51
+ .filter(line => {
52
+ const t = line.trim();
53
+ if (t.startsWith('[... Causyne ToolOutputStore:')) return false;
54
+ if (t.startsWith('[... Full log persisted to:')) return false;
55
+ if (t.startsWith('[... Read or search a relevant range')) return false;
56
+ if (/^\[\d+\s+middle characters omitted from active context/i.test(t)) return false;
57
+ return true;
58
+ });
59
+
60
+ return filteredLines.join('\n').trim();
61
+ }
62
+
63
+ function readSpillPreview(spillPath: string, maxBytes = 4096): string {
64
+ if (!spillPath || typeof spillPath !== 'string') return '';
65
+ try {
66
+ if (!fs.existsSync(spillPath)) return '';
67
+ const stat = fs.statSync(spillPath);
68
+ if (!stat.isFile() || stat.size <= 0) return '';
69
+ const bytesToRead = Math.min(stat.size, maxBytes);
70
+ const fd = fs.openSync(spillPath, 'r');
71
+ try {
72
+ const buf = Buffer.alloc(bytesToRead);
73
+ const read = fs.readSync(fd, buf, 0, bytesToRead, 0);
74
+ return buf.subarray(0, read).toString('utf8');
75
+ } finally {
76
+ fs.closeSync(fd);
77
+ }
78
+ } catch {
79
+ return '';
80
+ }
81
+ }
82
+
83
+ function extractSpillPathFromDecay(content: string): string | undefined {
84
+ const match = /\bat (\/[^\s]+)\s+—\s+read or search\b/.exec(content);
85
+ return match?.[1];
86
+ }
87
+
88
+ function recoverBrokenJsonOutput(raw: string, spillPath?: string | undefined): Record<string, unknown> | null {
89
+ const prefixMatch = /^\s*\{\s*"success"\s*:\s*(true|false)\b/.exec(raw);
90
+ if (!prefixMatch) return null;
91
+ const success = prefixMatch[1] === 'true';
92
+ if (spillPath) {
93
+ const fromSpill = readSpillPreview(spillPath);
94
+ if (fromSpill) {
95
+ return { success, output: fromSpill, spillPath };
96
+ }
97
+ }
98
+ const outputMatch = /"output"\s*:\s*"([\s\S]*)/.exec(raw);
99
+ if (outputMatch?.[1]) {
100
+ const body = outputMatch[1]
101
+ .replace(/"\s*\}\s*$/, '')
102
+ .replace(/\\n/g, '\n')
103
+ .replace(/\\"/g, '"')
104
+ .replace(/\\\\/g, '\\');
105
+ return {
106
+ success,
107
+ output: body,
108
+ ...(spillPath ? { spillPath } : {})
109
+ };
110
+ }
111
+ return {
112
+ success,
113
+ output: '',
114
+ ...(spillPath ? { spillPath } : {})
115
+ };
116
+ }
117
+
118
+ /**
119
+ * Normalize a historical `role: 'tool'` message for TUI session replay.
120
+ * Suppresses internal `checkpoint: 'synthesis'` governor intercepts (which are
121
+ * never emitted during live execution) and recovers clean output previews for
122
+ * `[decayed]` or shortened tool observations.
123
+ */
124
+ export function normalizeHistoricalToolResult(
125
+ toolName: string,
126
+ toolMsg: HistoricalToolMessage,
127
+ options: { unpaired?: boolean | undefined } = {}
128
+ ): NormalizedHistoricalToolResult {
129
+ const explicitSpill = typeof toolMsg.spillPath === 'string' && toolMsg.spillPath.trim()
130
+ ? toolMsg.spillPath.trim()
131
+ : undefined;
132
+
133
+ if (typeof toolMsg.content === 'string') {
134
+ const raw = toolMsg.content;
135
+ if (raw.startsWith(DECAY_MARKER)) {
136
+ const spillPath = explicitSpill ?? extractSpillPathFromDecay(raw);
137
+ const isFailure = /^\[decayed\] [^:]+: reported failure\b/i.test(raw);
138
+ const success = !isFailure;
139
+ if (toolName === 'update_plan') {
140
+ return {
141
+ skipStep: Boolean(options.unpaired),
142
+ result: { success: true, output: '' }
143
+ };
144
+ }
145
+ const recoveredRaw = spillPath ? readSpillPreview(spillPath) : '';
146
+ const cleaned = cleanToolOutputPreview(recoveredRaw, toolName);
147
+ return {
148
+ skipStep: false,
149
+ result: {
150
+ success,
151
+ output: cleaned,
152
+ ...(spillPath ? { spillPath } : {})
153
+ }
154
+ };
155
+ }
156
+
157
+ let parsed: Record<string, unknown> | null = null;
158
+ try {
159
+ const candidate: unknown = JSON.parse(raw);
160
+ if (candidate && typeof candidate === 'object' && !Array.isArray(candidate)) {
161
+ parsed = { ...(candidate as Record<string, unknown>) };
162
+ }
163
+ } catch {
164
+ parsed = recoverBrokenJsonOutput(raw, explicitSpill);
165
+ }
166
+
167
+ if (parsed) {
168
+ if (parsed.checkpoint === 'synthesis') {
169
+ return { skipStep: true, result: parsed };
170
+ }
171
+ if (parsed.success === undefined) {
172
+ parsed.success = !parsed.error;
173
+ }
174
+ if (explicitSpill && typeof parsed.spillPath !== 'string') {
175
+ parsed.spillPath = explicitSpill;
176
+ }
177
+ if (typeof parsed.output === 'string') {
178
+ parsed.output = cleanToolOutputPreview(parsed.output, toolName);
179
+ }
180
+ if (typeof parsed.log === 'string') {
181
+ parsed.log = cleanToolOutputPreview(parsed.log, toolName);
182
+ }
183
+ const plan = Array.isArray(parsed.plan)
184
+ ? (parsed.plan as Array<Record<string, unknown>>)
185
+ : undefined;
186
+ return { skipStep: false, result: parsed, plan };
187
+ }
188
+
189
+ const lowered = raw.toLowerCase();
190
+ return {
191
+ skipStep: false,
192
+ result: {
193
+ success: !lowered.startsWith('error') && !lowered.includes('failed'),
194
+ output: cleanToolOutputPreview(raw, toolName),
195
+ ...(explicitSpill ? { spillPath: explicitSpill } : {})
196
+ }
197
+ };
198
+ }
199
+
200
+ if (toolMsg.content && typeof toolMsg.content === 'object' && !Array.isArray(toolMsg.content)) {
201
+ const copy: Record<string, unknown> = { ...(toolMsg.content as Record<string, unknown>) };
202
+ if (copy.checkpoint === 'synthesis') {
203
+ return { skipStep: true, result: copy };
204
+ }
205
+ if (copy.success === undefined) copy.success = !copy.error;
206
+ if (explicitSpill && typeof copy.spillPath !== 'string') {
207
+ copy.spillPath = explicitSpill;
208
+ }
209
+ if (typeof copy.output === 'string') {
210
+ copy.output = cleanToolOutputPreview(copy.output, toolName);
211
+ }
212
+ if (typeof copy.log === 'string') {
213
+ copy.log = cleanToolOutputPreview(copy.log, toolName);
214
+ }
215
+ const plan = Array.isArray(copy.plan)
216
+ ? (copy.plan as Array<Record<string, unknown>>)
217
+ : undefined;
218
+ return { skipStep: false, result: copy, plan };
219
+ }
220
+
221
+ return {
222
+ skipStep: false,
223
+ result: {
224
+ success: true,
225
+ output: '',
226
+ ...(explicitSpill ? { spillPath: explicitSpill } : {})
227
+ }
228
+ };
229
+ }
@@ -124,7 +124,17 @@ export function sliceFromColumn(source, startCol) {
124
124
  }
125
125
  }
126
126
  if (col >= startCol) {
127
- return activeStyles + source.slice(index);
127
+ const tail = source.slice(index);
128
+ // Ensure any OSC 8 hyperlink opened inside `tail` is closed at the end of the slice
129
+ let openOsc8Term = '';
130
+ const osc8Re = /\x1b\]8;[^;]*;([^\x07\x1b]*)(\x07|\x1b\\)/g;
131
+ let oscMatch;
132
+ while ((oscMatch = osc8Re.exec(tail)) !== null) {
133
+ const uri = oscMatch[1] ?? '';
134
+ const term = oscMatch[2] ?? '\x1b\\';
135
+ openOsc8Term = uri.length > 0 ? term : '';
136
+ }
137
+ return activeStyles + tail + (openOsc8Term ? `\x1b]8;;${openOsc8Term}` : '');
128
138
  }
129
139
  const code = source.codePointAt(index);
130
140
  if (code === undefined)
@@ -158,7 +158,17 @@ export function sliceFromColumn(source: string, startCol: number): string {
158
158
  }
159
159
 
160
160
  if (col >= startCol) {
161
- return activeStyles + source.slice(index);
161
+ const tail = source.slice(index);
162
+ // Ensure any OSC 8 hyperlink opened inside `tail` is closed at the end of the slice
163
+ let openOsc8Term = '';
164
+ const osc8Re = /\x1b\]8;[^;]*;([^\x07\x1b]*)(\x07|\x1b\\)/g;
165
+ let oscMatch: RegExpExecArray | null;
166
+ while ((oscMatch = osc8Re.exec(tail)) !== null) {
167
+ const uri = oscMatch[1] ?? '';
168
+ const term = oscMatch[2] ?? '\x1b\\';
169
+ openOsc8Term = uri.length > 0 ? term : '';
170
+ }
171
+ return activeStyles + tail + (openOsc8Term ? `\x1b]8;;${openOsc8Term}` : '');
162
172
  }
163
173
 
164
174
  const code = source.codePointAt(index);
package/src/tui/text.d.ts DELETED
@@ -1,7 +0,0 @@
1
- export function safeDisplay(value: string): string;
2
- export function stripAnsi(text: string): string;
3
- export function truncate(value: string, width: number, ellipsis?: string): string;
4
- export function padEnd(value: string, width: number): string;
5
- export function visibleWidth(value: string): number;
6
- export function wrap(value: string, width: number, options?: { hang?: number }): string[];
7
- export function wrapBlock(value: string, width: number, options?: { hang?: number }): string[];