@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.
Files changed (88) hide show
  1. package/LICENSE +1 -1
  2. package/docs/ARCHITECTURE.md +24 -1
  3. package/package.json +1 -1
  4. package/src/acp/client.js +9 -2
  5. package/src/acp/client.ts +11 -2
  6. package/src/acp/protocol.ts +9 -0
  7. package/src/agentLoop.js +504 -119
  8. package/src/agentLoop.ts +477 -121
  9. package/src/browser/browserRuntime.js +47 -0
  10. package/src/browser/browserRuntime.ts +45 -0
  11. package/src/browser/causyneBrowser.js +60 -31
  12. package/src/browser/causyneBrowser.ts +37 -12
  13. package/src/browser/workspacePreview.js +52 -0
  14. package/src/browser/workspacePreview.ts +49 -0
  15. package/src/core/planCache.js +5 -0
  16. package/src/core/planCache.ts +5 -0
  17. package/src/decisionPolicy.js +9 -0
  18. package/src/decisionPolicy.ts +8 -0
  19. package/src/historyPruner.js +251 -0
  20. package/src/historyPruner.ts +263 -0
  21. package/src/infra/atomicWriter.js +49 -0
  22. package/src/infra/atomicWriter.ts +63 -0
  23. package/src/infra/telemetry.js +38 -0
  24. package/src/infra/telemetry.ts +68 -0
  25. package/src/observer/coldObserver.js +12 -7
  26. package/src/observer/coldObserver.ts +12 -7
  27. package/src/observer/evidence.js +8 -2
  28. package/src/observer/evidence.ts +9 -2
  29. package/src/outputRecovery.js +36 -0
  30. package/src/outputRecovery.ts +33 -0
  31. package/src/providers/acp.js +114 -46
  32. package/src/providers/acp.ts +129 -46
  33. package/src/providers/antigravity.js +262 -91
  34. package/src/providers/antigravity.ts +270 -99
  35. package/src/providers/antigravityBridge.js +58 -0
  36. package/src/providers/antigravityBridge.ts +51 -0
  37. package/src/providers/base.d.ts +9 -0
  38. package/src/providers/budgetEnforcer.js +110 -0
  39. package/src/providers/budgetEnforcer.ts +122 -0
  40. package/src/providers/collaborationPolicy.js +6 -0
  41. package/src/providers/collaborationPolicy.ts +7 -0
  42. package/src/providers/loopGuard.js +84 -0
  43. package/src/providers/loopGuard.ts +105 -0
  44. package/src/providers/pi.js +19 -6
  45. package/src/providers/pi.ts +19 -7
  46. package/src/providers/toolContracts.js +36 -0
  47. package/src/providers/toolContracts.ts +48 -0
  48. package/src/session/sidechainEvents.js +49 -0
  49. package/src/session/sidechainEvents.ts +98 -0
  50. package/src/skillsManager.d.ts +1 -0
  51. package/src/smartToolsUse.js +123 -4
  52. package/src/smartToolsUse.ts +136 -4
  53. package/src/stallGuard.js +3 -12
  54. package/src/stallGuard.ts +3 -12
  55. package/src/subagent/sidechainHarness.js +66 -0
  56. package/src/subagent/sidechainHarness.ts +91 -0
  57. package/src/taskContinuation.js +12 -0
  58. package/src/taskContinuation.ts +13 -0
  59. package/src/tokenTracker.js +406 -539
  60. package/src/tokenTracker.ts +569 -0
  61. package/src/toolPacks.d.ts +2 -0
  62. package/src/toolPacks.js +1 -1
  63. package/src/tools/argumentValidation.js +56 -0
  64. package/src/tools/argumentValidation.ts +50 -0
  65. package/src/tools/browserAutomator.js +2 -2
  66. package/src/tools/browserAutomator.ts +3 -2
  67. package/src/tools/deferredMcpSearch.js +188 -201
  68. package/src/tools/deferredMcpSearch.ts +250 -0
  69. package/src/tools/generateMediaViaApi.js +305 -331
  70. package/src/tools/generateMediaViaApi.ts +330 -0
  71. package/src/tools/historyPruner.js +5 -0
  72. package/src/tools/historyPruner.ts +5 -0
  73. package/src/tools/payloadSanitizer.js +92 -0
  74. package/src/tools/payloadSanitizer.ts +113 -0
  75. package/src/tools/registry.d.ts +1 -0
  76. package/src/tools/sysRun.js +47 -18
  77. package/src/tools/sysRun.ts +52 -20
  78. package/src/tools/toolOutputStore.js +180 -0
  79. package/src/tools/toolOutputStore.ts +209 -0
  80. package/src/tools/toolSelfRepair.js +26 -1
  81. package/src/tools/toolSelfRepair.ts +25 -1
  82. package/src/tui/chatRenderer.d.ts +1 -0
  83. package/src/tui/chatRenderer.js +4 -2
  84. package/src/tui/codeStreamRenderer.js +36 -8
  85. package/src/tui/codeStreamRenderer.ts +38 -8
  86. package/src/tui/stageSurface.js +1 -0
  87. package/src/tui/text.js +4 -1
  88. package/src/tokenTracker.d.ts +0 -1
@@ -0,0 +1,209 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import crypto from 'node:crypto';
4
+ import { causyneHome } from '../utils/paths.js';
5
+
6
+ export interface ToolOutputStoreConfig {
7
+ maxChars: number;
8
+ maxLines: number;
9
+ maxBytes: number;
10
+ headLines: number;
11
+ tailLines: number;
12
+ storageDir: string;
13
+ }
14
+
15
+ export interface StoredOutputResult {
16
+ contentForModel: string;
17
+ isTruncated: boolean;
18
+ totalLines: number;
19
+ totalBytes: number;
20
+ contentHash: string;
21
+ diskPath?: string;
22
+ }
23
+
24
+ function sanitizeIdentifier(id: string): string {
25
+ const cleaned = String(id || '').replace(/[^a-zA-Z0-9_-]/g, '_');
26
+ return cleaned.length > 0 ? cleaned.slice(0, 64) : 'tool';
27
+ }
28
+
29
+ export class ToolOutputStore {
30
+ private config: ToolOutputStoreConfig;
31
+
32
+ constructor(customConfig?: Partial<ToolOutputStoreConfig>) {
33
+ this.config = {
34
+ maxChars: customConfig?.maxChars ?? 2500,
35
+ maxLines: customConfig?.maxLines ?? 100,
36
+ maxBytes: customConfig?.maxBytes ?? 50 * 1024,
37
+ headLines: customConfig?.headLines ?? 35,
38
+ tailLines: customConfig?.tailLines ?? 35,
39
+ storageDir: customConfig?.storageDir ?? path.join(causyneHome(), 'tool-output')
40
+ };
41
+ }
42
+
43
+ public getConfig(): Readonly<ToolOutputStoreConfig> {
44
+ return { ...this.config };
45
+ }
46
+
47
+ public processToolOutput(sessionId: string, toolCallId: string, rawOutput: string): StoredOutputResult {
48
+ const text = typeof rawOutput === 'string' ? rawOutput : String(rawOutput ?? '');
49
+ const totalBytes = Buffer.byteLength(text, 'utf8');
50
+ const lines = text.split('\n');
51
+ const totalLines = lines.length;
52
+ const contentHash = crypto.createHash('sha256').update(text).digest('hex').slice(0, 12);
53
+
54
+ if (process.env.CAUSYNE_OUTPUT_SPILL === '0'
55
+ || (text.length <= this.config.maxChars && totalLines <= this.config.maxLines && totalBytes <= this.config.maxBytes)) {
56
+ return {
57
+ contentForModel: text,
58
+ isTruncated: false,
59
+ totalLines,
60
+ totalBytes,
61
+ contentHash
62
+ };
63
+ }
64
+
65
+ const safeSession = sanitizeIdentifier(sessionId);
66
+ const safeToolId = sanitizeIdentifier(toolCallId);
67
+ const sessionDir = path.join(this.config.storageDir, safeSession);
68
+ const diskPath = path.join(sessionDir, `${safeToolId}_${contentHash}.log`);
69
+ let temporaryPath: string | undefined;
70
+ try {
71
+ fs.mkdirSync(sessionDir, { recursive: true, mode: 0o700 });
72
+ if (fs.lstatSync(sessionDir).isSymbolicLink()) throw new Error('Output directory is a symlink');
73
+ temporaryPath = path.join(sessionDir, `.${crypto.randomUUID()}.tmp`);
74
+ fs.writeFileSync(temporaryPath, text, { encoding: 'utf8', mode: 0o600, flag: 'wx' });
75
+ fs.renameSync(temporaryPath, diskPath);
76
+ } catch {
77
+ if (temporaryPath) { try { fs.unlinkSync(temporaryPath); } catch { /* already renamed or unavailable */ } }
78
+ // Never discard an observation when its recovery file could not be saved.
79
+ return { contentForModel: text, isTruncated: false, totalLines, totalBytes, contentHash };
80
+ }
81
+
82
+ // Line bounds alone do not bound a minified file or a single huge JSON line.
83
+ const omittedLines = Math.max(0, totalLines - (this.config.headLines + this.config.tailLines));
84
+ const notice = [
85
+ `\n[... Causyne ToolOutputStore: ${omittedLines} lines (${Math.max(1, Math.round(totalBytes / 1024))} KB) truncated. Content Hash: ${contentHash} ...]`,
86
+ `[... Full log persisted to: ${diskPath} ...]`,
87
+ '[... Read or search a relevant range with fs_read or code_search_ripgrep; do not rerun the original tool ...]\n'
88
+ ].join('\n');
89
+
90
+ let head = '';
91
+ let tail = '';
92
+ if (lines.length === 1) {
93
+ const budget = Math.max(0, this.config.maxChars - notice.length);
94
+ const half = Math.floor(budget / 2);
95
+ head = text.slice(0, half);
96
+ tail = text.slice(-half);
97
+ } else {
98
+ const rawHead = lines.slice(0, this.config.headLines).join('\n');
99
+ const rawTail = lines.slice(-this.config.tailLines).join('\n');
100
+ const maxBudget = this.config.maxChars;
101
+ if (rawHead.length + rawTail.length + notice.length > maxBudget) {
102
+ const budget = Math.max(0, maxBudget - notice.length);
103
+ const half = Math.floor(budget / 2);
104
+ head = rawHead.slice(0, half);
105
+ tail = rawTail.slice(-half);
106
+ } else {
107
+ head = rawHead;
108
+ tail = rawTail;
109
+ }
110
+ }
111
+ const contentForModel = head + notice + tail;
112
+
113
+ return {
114
+ contentForModel,
115
+ isTruncated: true,
116
+ totalLines,
117
+ totalBytes,
118
+ contentHash,
119
+ diskPath
120
+ };
121
+ }
122
+
123
+ public readSlice(diskPath: string, startLine: number, endLine: number): string {
124
+ const resolvedPath = path.resolve(diskPath);
125
+ if (!fs.existsSync(resolvedPath)) {
126
+ throw new Error(`ToolOutputStore: Log file not found at ${resolvedPath}`);
127
+ }
128
+ const relative = path.relative(fs.realpathSync(this.config.storageDir), fs.realpathSync(resolvedPath));
129
+ if (relative.startsWith(`..${path.sep}`) || relative === '..' || path.isAbsolute(relative)) {
130
+ throw new Error('ToolOutputStore: Requested file is outside the output store');
131
+ }
132
+ const lines = fs.readFileSync(resolvedPath, 'utf8').split('\n');
133
+ const clampedStart = Math.max(1, Math.min(startLine, lines.length));
134
+ const clampedEnd = Math.max(clampedStart, Math.min(endLine, lines.length));
135
+ return lines.slice(clampedStart - 1, clampedEnd).join('\n');
136
+ }
137
+
138
+ public pruneOldOutputs(maxAgeMs = 7 * 24 * 60 * 60 * 1000): number {
139
+ if (!fs.existsSync(this.config.storageDir)) return 0;
140
+ let pruned = 0;
141
+ const now = Date.now();
142
+ try {
143
+ const sessions = fs.readdirSync(this.config.storageDir);
144
+ for (const session of sessions) {
145
+ const sessionPath = path.join(this.config.storageDir, session);
146
+ const stat = fs.lstatSync(sessionPath);
147
+ if (stat.isDirectory()) {
148
+ const files = fs.readdirSync(sessionPath);
149
+ for (const file of files) {
150
+ const filePath = path.join(sessionPath, file);
151
+ const fileStat = fs.statSync(filePath);
152
+ if (now - fileStat.mtimeMs > maxAgeMs) {
153
+ fs.unlinkSync(filePath);
154
+ pruned++;
155
+ }
156
+ }
157
+ if (fs.readdirSync(sessionPath).length === 0) {
158
+ fs.rmdirSync(sessionPath);
159
+ }
160
+ }
161
+ }
162
+ } catch {
163
+ // Non-fatal cleanup
164
+ }
165
+ return pruned;
166
+ }
167
+ }
168
+
169
+ export const defaultToolOutputStore = new ToolOutputStore();
170
+
171
+ export function processToolOutputWithStore(
172
+ sessionId: string,
173
+ toolCallId: string,
174
+ rawOutput: string,
175
+ store = defaultToolOutputStore
176
+ ): StoredOutputResult {
177
+ return store.processToolOutput(sessionId, toolCallId, rawOutput);
178
+ }
179
+
180
+ export function renderSpillDocument(
181
+ result: unknown,
182
+ meta: { taskId?: string; step?: number | string; tool?: string } = {}
183
+ ): string {
184
+ if (typeof result === 'string') return result;
185
+ if (result === null || typeof result !== 'object') return String(result);
186
+
187
+ const header = [
188
+ '=== CAUSYNE TOOL OUTPUT (full, untruncated) ===',
189
+ `tool : ${meta.tool || 'unknown'}`,
190
+ `task : ${meta.taskId || 'unknown'} step: ${meta.step == null ? 'unknown' : meta.step}`,
191
+ `saved: ${new Date().toISOString()}`
192
+ ];
193
+
194
+ const sections: string[] = [];
195
+ const scalars: string[] = [];
196
+
197
+ for (const [key, value] of Object.entries(result as Record<string, unknown>)) {
198
+ if (typeof value === 'string' && value.length > 500) {
199
+ sections.push(`\n--- field: ${key} (${value.length} chars) ---\n${value}`);
200
+ } else if (value !== null && typeof value === 'object') {
201
+ sections.push(`\n--- field: ${key} (JSON) ---\n${JSON.stringify(value, null, 2)}`);
202
+ } else {
203
+ scalars.push(`${key}: ${JSON.stringify(value)}`);
204
+ }
205
+ }
206
+
207
+ if (scalars.length > 0) header.push('', ...scalars);
208
+ return header.join('\n') + '\n' + sections.join('\n') + '\n';
209
+ }
@@ -544,6 +544,31 @@ export function resolveParameterAliases(toolName, args, schema) {
544
544
  });
545
545
  }
546
546
  }
547
+ else if (canonicalName === 'generate_media_via_api') {
548
+ if (!modified.mediaType && modified.type) {
549
+ modified.mediaType = modified.type;
550
+ delete modified.type;
551
+ repairs.push("Mapped 'type' to 'mediaType' parameter for 'generate_media_via_api'");
552
+ }
553
+ if (!modified.prompt && (modified.text || modified.description || modified.query)) {
554
+ modified.prompt = modified.text || modified.description || modified.query;
555
+ delete modified.text;
556
+ delete modified.description;
557
+ delete modified.query;
558
+ repairs.push("Mapped prompt alias to 'prompt' parameter for 'generate_media_via_api'");
559
+ }
560
+ if (!modified.outputPath && (modified.output || modified.path || modified.destination || modified.file)) {
561
+ modified.outputPath = modified.output || modified.path || modified.destination || modified.file;
562
+ delete modified.output;
563
+ delete modified.destination;
564
+ delete modified.file;
565
+ repairs.push("Mapped output path alias to 'outputPath' parameter for 'generate_media_via_api'");
566
+ }
567
+ if (!modified.mediaType) {
568
+ modified.mediaType = 'image';
569
+ repairs.push("Defaulted missing 'mediaType' to 'image' for 'generate_media_via_api'");
570
+ }
571
+ }
547
572
  else if (canonicalName === 'browser_act') {
548
573
  if (!modified.actions) {
549
574
  if (Array.isArray(modified.steps) || Array.isArray(modified.items)) {
@@ -788,7 +813,7 @@ export function coerceArgumentTypes(toolName, args, schema) {
788
813
  export function normalizePaths(args, cwd = process.cwd()) {
789
814
  const repairs = [];
790
815
  const modified = { ...args };
791
- const pathKeys = ['path', 'file_path', 'source', 'destination', 'targetFile', 'target'];
816
+ const pathKeys = ['path', 'file_path', 'source', 'destination', 'targetFile', 'target', 'outputPath', 'output_path', 'outputFileName'];
792
817
  for (const key of pathKeys) {
793
818
  const val = modified[key];
794
819
  if (typeof val === 'string' && val.trim() !== '') {
@@ -595,6 +595,30 @@ export function resolveParameterAliases(
595
595
  return norm;
596
596
  });
597
597
  }
598
+ } else if (canonicalName === 'generate_media_via_api') {
599
+ if (!modified.mediaType && modified.type) {
600
+ modified.mediaType = modified.type;
601
+ delete modified.type;
602
+ repairs.push("Mapped 'type' to 'mediaType' parameter for 'generate_media_via_api'");
603
+ }
604
+ if (!modified.prompt && (modified.text || modified.description || modified.query)) {
605
+ modified.prompt = modified.text || modified.description || modified.query;
606
+ delete modified.text;
607
+ delete modified.description;
608
+ delete modified.query;
609
+ repairs.push("Mapped prompt alias to 'prompt' parameter for 'generate_media_via_api'");
610
+ }
611
+ if (!modified.outputPath && (modified.output || modified.path || modified.destination || modified.file)) {
612
+ modified.outputPath = modified.output || modified.path || modified.destination || modified.file;
613
+ delete modified.output;
614
+ delete modified.destination;
615
+ delete modified.file;
616
+ repairs.push("Mapped output path alias to 'outputPath' parameter for 'generate_media_via_api'");
617
+ }
618
+ if (!modified.mediaType) {
619
+ modified.mediaType = 'image';
620
+ repairs.push("Defaulted missing 'mediaType' to 'image' for 'generate_media_via_api'");
621
+ }
598
622
  } else if (canonicalName === 'browser_act') {
599
623
  if (!modified.actions) {
600
624
  if (Array.isArray(modified.steps) || Array.isArray(modified.items)) {
@@ -842,7 +866,7 @@ export function normalizePaths(
842
866
  ): RepairResult {
843
867
  const repairs: string[] = [];
844
868
  const modified = { ...args };
845
- const pathKeys = ['path', 'file_path', 'source', 'destination', 'targetFile', 'target'];
869
+ const pathKeys = ['path', 'file_path', 'source', 'destination', 'targetFile', 'target', 'outputPath', 'output_path', 'outputFileName'];
846
870
 
847
871
  for (const key of pathKeys) {
848
872
  const val = modified[key];
@@ -18,6 +18,7 @@ export class ChatRenderer {
18
18
  stopSpinner(): void;
19
19
  frame(kind: string, produce: () => void, meta?: Record<string, unknown> | null): void;
20
20
  updateTailFrame(kind: string, produce: () => void, meta?: Record<string, unknown> | null): void;
21
+ capture(width: number, produce: () => void): string[];
21
22
  measure(): number;
22
23
  write(line?: string): void;
23
24
  }
@@ -839,9 +839,11 @@ export class ChatRenderer {
839
839
  const cleaned = safeDisplay(source).replace(/\n{3,}/g, '\n\n').trim();
840
840
 
841
841
  // Wrap first, THEN cut — bounding by source newlines lets a single long
842
- // line through as thousands of wrapped rows.
842
+ // line through as thousands of wrapped rows. Filter out transient curl progress noise.
843
843
  const wrapped = [];
844
- for (const line of cleaned.split('\n')) {
844
+ for (const rawLine of cleaned.split('\n')) {
845
+ const line = rawLine.replace(/\r/g, '').trimEnd();
846
+ if (/^\s*(?:% Total\b|Dload\s+Upload\b|\d+\s+\d+\s+\d+\s+.*--:--:--)/i.test(line)) continue;
845
847
  for (const part of wrap(line, width)) {
846
848
  wrapped.push(part);
847
849
  if (wrapped.length > PREVIEW_LINES + 1) break;
@@ -110,9 +110,24 @@ export class CodeStreamRenderer extends ChatRenderer {
110
110
  }
111
111
  paintCodePanel(event) {
112
112
  const transcript = this.transcript;
113
- const last = transcript?.frames.at(-1);
114
- const samePanel = last?.meta?.codePreview === true && last.meta.id === event.id;
115
- const state = samePanel && last ? this.codePanels.get(last) : undefined;
113
+ const frames = transcript?.frames || [];
114
+ const last = frames.at(-1);
115
+ const sameTail = last?.meta?.codePreview === true && (last.meta.id === event.id || last.meta.id === 'model-draft');
116
+ // Look back for an existing code panel frame for this operation (e.g. model-draft or same id)
117
+ let targetFrame;
118
+ if (sameTail && last) {
119
+ targetFrame = last;
120
+ }
121
+ else {
122
+ for (let i = frames.length - 1; i >= Math.max(0, frames.length - 6); i--) {
123
+ const f = frames[i];
124
+ if (f?.meta?.codePreview === true && (f.meta.id === event.id || (f.meta.id === 'model-draft' && event.id !== 'model-draft'))) {
125
+ targetFrame = f;
126
+ break;
127
+ }
128
+ }
129
+ }
130
+ const state = targetFrame ? this.codePanels.get(targetFrame) : undefined;
116
131
  const panelState = state || {
117
132
  event,
118
133
  modelNote: this.modelNote,
@@ -126,12 +141,25 @@ export class CodeStreamRenderer extends ChatRenderer {
126
141
  for (const row of renderCodeProgress(panelState.event, this.measure(), panelState.modelNote, panelState.start))
127
142
  this.write(row);
128
143
  };
129
- if (samePanel)
144
+ if (targetFrame && targetFrame === last) {
130
145
  this.updateTailFrame('step', produce, { codePreview: true, id: event.id, phase: event.phase });
131
- else
146
+ this.codePanels.set(last, panelState);
147
+ }
148
+ else if (targetFrame && transcript) {
149
+ targetFrame.produce = (width) => this.capture(width, produce);
150
+ targetFrame.meta = { ...(targetFrame.meta || {}), codePreview: true, id: event.id, phase: event.phase };
151
+ targetFrame.rows = null;
152
+ targetFrame.renderedWidth = -1;
153
+ transcript.cache = null;
154
+ transcript.revision++;
155
+ transcript.changed();
156
+ this.codePanels.set(targetFrame, panelState);
157
+ }
158
+ else {
132
159
  this.frame('step', produce, { codePreview: true, id: event.id, phase: event.phase });
133
- const current = transcript?.frames.at(-1);
134
- if (current)
135
- this.codePanels.set(current, panelState);
160
+ const current = transcript?.frames.at(-1);
161
+ if (current)
162
+ this.codePanels.set(current, panelState);
163
+ }
136
164
  }
137
165
  }
@@ -3,7 +3,7 @@ import { CODE_PANEL_LINES, codePreviewLineCount, defaultPreviewStart, renderCode
3
3
 
4
4
  type RendererEvent = { type: string; [key: string]: unknown };
5
5
  type CodePanelState = { event: CodeProgressEvent; modelNote: string; start: number; followTail: boolean };
6
- type CodeFrame = { id: number; meta?: Record<string, unknown> | null; rows?: string[] | null; renderedWidth?: number };
6
+ type CodeFrame = { id: number; meta?: Record<string, unknown> | null; rows?: string[] | null; renderedWidth?: number; produce?: (width: number) => string[] };
7
7
  type CodeTranscript = {
8
8
  frames: CodeFrame[];
9
9
  cache: unknown;
@@ -123,9 +123,25 @@ export class CodeStreamRenderer extends ChatRenderer {
123
123
 
124
124
  private paintCodePanel(event: CodeProgressEvent): void {
125
125
  const transcript = this.transcript as unknown as CodeTranscript | null;
126
- const last = transcript?.frames.at(-1);
127
- const samePanel = last?.meta?.codePreview === true && last.meta.id === event.id;
128
- const state = samePanel && last ? this.codePanels.get(last) : undefined;
126
+ const frames = transcript?.frames || [];
127
+ const last = frames.at(-1);
128
+ const sameTail = last?.meta?.codePreview === true && (last.meta.id === event.id || last.meta.id === 'model-draft');
129
+
130
+ // Look back for an existing code panel frame for this operation (e.g. model-draft or same id)
131
+ let targetFrame: CodeFrame | undefined;
132
+ if (sameTail && last) {
133
+ targetFrame = last;
134
+ } else {
135
+ for (let i = frames.length - 1; i >= Math.max(0, frames.length - 6); i--) {
136
+ const f = frames[i];
137
+ if (f?.meta?.codePreview === true && (f.meta.id === event.id || (f.meta.id === 'model-draft' && event.id !== 'model-draft'))) {
138
+ targetFrame = f;
139
+ break;
140
+ }
141
+ }
142
+ }
143
+
144
+ const state = targetFrame ? this.codePanels.get(targetFrame) : undefined;
129
145
  const panelState: CodePanelState = state || {
130
146
  event,
131
147
  modelNote: this.modelNote,
@@ -138,9 +154,23 @@ export class CodeStreamRenderer extends ChatRenderer {
138
154
  const produce = (): void => {
139
155
  for (const row of renderCodeProgress(panelState.event, this.measure(), panelState.modelNote, panelState.start)) this.write(row);
140
156
  };
141
- if (samePanel) this.updateTailFrame('step', produce, { codePreview: true, id: event.id, phase: event.phase });
142
- else this.frame('step', produce, { codePreview: true, id: event.id, phase: event.phase });
143
- const current = transcript?.frames.at(-1);
144
- if (current) this.codePanels.set(current, panelState);
157
+
158
+ if (targetFrame && targetFrame === last) {
159
+ this.updateTailFrame('step', produce, { codePreview: true, id: event.id, phase: event.phase });
160
+ this.codePanels.set(last, panelState);
161
+ } else if (targetFrame && transcript) {
162
+ targetFrame.produce = (width: number) => this.capture(width, produce);
163
+ targetFrame.meta = { ...(targetFrame.meta || {}), codePreview: true, id: event.id, phase: event.phase };
164
+ targetFrame.rows = null;
165
+ targetFrame.renderedWidth = -1;
166
+ transcript.cache = null;
167
+ transcript.revision++;
168
+ transcript.changed();
169
+ this.codePanels.set(targetFrame, panelState);
170
+ } else {
171
+ this.frame('step', produce, { codePreview: true, id: event.id, phase: event.phase });
172
+ const current = transcript?.frames.at(-1);
173
+ if (current) this.codePanels.set(current, panelState);
174
+ }
145
175
  }
146
176
  }
@@ -269,6 +269,7 @@ export class StageSurface {
269
269
 
270
270
 
271
271
  armTeardown() {
272
+ if (this.signalHooks.length > 0 || this.exitHook) this.disarmTeardown();
272
273
  this.exitHook = () => { try { this.close(); } catch { /* nothing left to do */ } };
273
274
  process.once('exit', this.exitHook);
274
275
 
package/src/tui/text.js CHANGED
@@ -309,7 +309,10 @@ export function sanitize(text) {
309
309
  // columnar output into an unreadable run, and leaving them corrupts the
310
310
  // frame. Expansion is the only option that preserves what the user meant to
311
311
  // see. Everything else in this class is genuinely unwanted and is removed.
312
- return expandTabs(stripAnsi(text))
312
+ const normalized = String(text == null ? '' : text)
313
+ .replace(/\r\n/g, '\n')
314
+ .replace(/\r/g, '\n');
315
+ return expandTabs(stripAnsi(normalized))
313
316
  // eslint-disable-next-line no-control-regex
314
317
  .replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, '');
315
318
  }
@@ -1 +0,0 @@
1
- export const TokenTracker: any;