@causyne/agent 1.20.45 → 1.20.50

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@causyne/agent",
3
- "version": "1.20.45",
3
+ "version": "1.20.50",
4
4
  "description": "Agentic AI for software, tools, and computer workflows",
5
5
  "main": "bin/causyne.js",
6
6
  "type": "module",
package/src/agentLoop.js CHANGED
@@ -2693,12 +2693,15 @@ You are operating in a text-and-code modality without direct image pixel renderi
2693
2693
  if (response.thinkingBlocks) {
2694
2694
  assistantMsg.thinking_blocks = response.thinkingBlocks;
2695
2695
  }
2696
- this.messages.push(assistantMsg);
2697
- // Prose accompanying pending actions is not an execution result.
2698
- // Tool events provide progress; terminal claims pass completion gates below.
2699
2696
  const externalActions = Array.isArray(response.externalActions)
2700
2697
  ? response.externalActions
2701
2698
  : [];
2699
+ if (externalActions.length > 0) {
2700
+ assistantMsg.external_actions = externalActions;
2701
+ }
2702
+ this.messages.push(assistantMsg);
2703
+ // Prose accompanying pending actions is not an execution result.
2704
+ // Tool events provide progress; terminal claims pass completion gates below.
2702
2705
  const completedExternalActions = externalActions.filter((a) => a && a.status === 'completed');
2703
2706
  const failedExternalActions = externalActions.filter((a) => a && a.status === 'failed');
2704
2707
  const hasExternalActions = completedExternalActions.length > 0;
@@ -2878,6 +2881,28 @@ You are operating in a text-and-code modality without direct image pixel renderi
2878
2881
  this.memoryManager.saveHistory(this.messages);
2879
2882
  continue;
2880
2883
  }
2884
+ if (hasExternalActions && (isIncompleteTurn || isMidTaskProgress) && incompleteTurnContinuations === 3) {
2885
+ incompleteTurnContinuations++;
2886
+ if (response.content) {
2887
+ this.emitEvent({ type: 'agent_message', content: response.content });
2888
+ }
2889
+ this.emitEvent({ type: 'status', message: 'Requesting final deliverable and response...' });
2890
+ this.emitEvent({ type: 'agent_activity', activity: 'Synthesizing final deliverable…' });
2891
+ this.messages.push({
2892
+ role: 'system',
2893
+ content: `[TASK COMPLETION MANDATE: You have completed your tool execution steps (${this.stepsCompleted} steps performed). Provide your complete final response, deliverables, and conclusions directly to the user now. Do not run any more background commands.]`
2894
+ });
2895
+ this.memoryManager.saveHistory(this.messages);
2896
+ continue;
2897
+ }
2898
+ if (hasExternalActions && (isIncompleteTurn || isMidTaskProgress || (typeof contentText === 'string' && (contentText.startsWith('Antigravity executed:') || /^Turn completed by .+ over ACP\.$/i.test(contentText.trim()))))) {
2899
+ this.emitEvent({
2900
+ type: 'error',
2901
+ message: 'The task stopped before completion after repeated incomplete turns without a final response. Work remains unfinished.'
2902
+ });
2903
+ this.memoryManager.saveHistory(this.messages);
2904
+ break;
2905
+ }
2881
2906
  if (hasExternalActions && !isIncompleteTurn && !isMidTaskProgress) {
2882
2907
  incompleteTurnContinuations = 0;
2883
2908
  }
package/src/agentLoop.ts CHANGED
@@ -2816,14 +2816,19 @@ You are operating in a text-and-code modality without direct image pixel renderi
2816
2816
  if (response.thinkingBlocks) {
2817
2817
  assistantMsg.thinking_blocks = response.thinkingBlocks;
2818
2818
  }
2819
+
2820
+ const externalActions = Array.isArray((response as any).externalActions)
2821
+ ? (response as any).externalActions
2822
+ : [];
2823
+ if (externalActions.length > 0) {
2824
+ assistantMsg.external_actions = externalActions;
2825
+ }
2826
+
2819
2827
  this.messages.push(assistantMsg);
2820
2828
 
2821
2829
  // Prose accompanying pending actions is not an execution result.
2822
2830
  // Tool events provide progress; terminal claims pass completion gates below.
2823
2831
 
2824
- const externalActions = Array.isArray((response as any).externalActions)
2825
- ? (response as any).externalActions
2826
- : [];
2827
2832
  const completedExternalActions = externalActions.filter((a: any) => a && a.status === 'completed');
2828
2833
  const failedExternalActions = externalActions.filter((a: any) => a && a.status === 'failed');
2829
2834
  const hasExternalActions = completedExternalActions.length > 0;
@@ -3017,6 +3022,30 @@ You are operating in a text-and-code modality without direct image pixel renderi
3017
3022
  continue;
3018
3023
  }
3019
3024
 
3025
+ if (hasExternalActions && (isIncompleteTurn || isMidTaskProgress) && incompleteTurnContinuations === 3) {
3026
+ incompleteTurnContinuations++;
3027
+ if (response.content) {
3028
+ this.emitEvent({ type: 'agent_message', content: response.content });
3029
+ }
3030
+ this.emitEvent({ type: 'status', message: 'Requesting final deliverable and response...' });
3031
+ this.emitEvent({ type: 'agent_activity', activity: 'Synthesizing final deliverable…' });
3032
+ this.messages.push({
3033
+ role: 'system',
3034
+ content: `[TASK COMPLETION MANDATE: You have completed your tool execution steps (${this.stepsCompleted} steps performed). Provide your complete final response, deliverables, and conclusions directly to the user now. Do not run any more background commands.]`
3035
+ });
3036
+ this.memoryManager.saveHistory(this.messages);
3037
+ continue;
3038
+ }
3039
+
3040
+ if (hasExternalActions && (isIncompleteTurn || isMidTaskProgress || (typeof contentText === 'string' && (contentText.startsWith('Antigravity executed:') || /^Turn completed by .+ over ACP\.$/i.test(contentText.trim()))))) {
3041
+ this.emitEvent({
3042
+ type: 'error',
3043
+ message: 'The task stopped before completion after repeated incomplete turns without a final response. Work remains unfinished.'
3044
+ });
3045
+ this.memoryManager.saveHistory(this.messages);
3046
+ break;
3047
+ }
3048
+
3020
3049
  if (hasExternalActions && !isIncompleteTurn && !isMidTaskProgress) {
3021
3050
  incompleteTurnContinuations = 0;
3022
3051
  }
@@ -1,5 +1,11 @@
1
- const LAUNCH_VERBS = /\b(open|launch|start|run|play|serve|preview)\b/i;
2
- const CHANGE_VERBS = /\b(create|build|make|write|edit|fix|modify|change|update|implement|generate|refactor|delete|remove|install|deploy)\b/i;
1
+ const CREATIVE_WORDS = /\b(?:story|novel|fiction|narrative|lore|essay|poem|poetry|chapter|character|plot|dialogue|scene|cerita|kisah|dongeng|karangan|buku|tulisan|bab|paragraf|halaman)\b/i;
2
+ const INQUIRY_WORDS = /\b(?:explain|why|what|how|who|where|when|analyze|describe|tell\s+me|show\s+me\s+how|difference|summary|summarize|review|audit|jelaskan|kenapa|mengapa|bagaimana|siapa|apakah|analisis)\b/i;
3
+ const CHANGE_VERBS = /\b(?:create|build|make|write|edit|fix|modify|change|update|implement|generate|refactor|delete|remove|install|deploy|add|append|expand|continue|improve|refine|compose|draft|author|design|buat(?:kan)?|bikin|tulis(?:kan)?|ubah|ganti|perbaiki|tambah(?:kan)?|kembangkan|lanjut(?:kan)?|sambung(?:kan)?|membaut|maembuat|merancang|susun|crear|escribir|construir|modificar|actualizar|créer|écrire|modifier|erstellen|schreiben|bauen)\b/i;
4
+ const NON_LAUNCH_PHRASES = /\b(?:(?:run|runs|running)\s+(?:by|on|in|with|out|through)|(?:play|plays|playing)\s+(?:a\s+role|with)|(?:open|opens|opening)\s+(?:to|world|source|mind|ended|door)|(?:start|starts|starting)\s+(?:with|from)|(?:serve|serves|serving)\s+(?:as|to)|in\s+the\s+long\s+run|home\s+run)\b/i;
5
+ const IMPERATIVE_LAUNCH = /^\s*(?:please\s+|can\s+you\s+)?(?:open|launch|start|run|play|serve|preview)(?:\s+(?:it|this|that|app|application|project|game|server|service|dev|preview|up|now|here|locally))?\s*[.!?]?\s*$/i;
6
+ const TARGETED_LAUNCH = /\b(?:open|launch|start|run|play|serve|preview)\s+(?:up\s+)?(?:the\s+|this\s+|an?\s+)?(?:app|application|project|game|server|dev\s+server|website|site|page|ui|preview|demo|localhost|frontend|backend)\b/i;
7
+ const URL_OR_FILE_LAUNCH = /^\s*(?:open|preview)\s+(?:https?:\/\/|\/|~\/|\.\/|[a-zA-Z0-9_\-\.\/]+\.(?:html|htm|php|py|js|ts))\b/i;
8
+ const BROWSER_LAUNCH = /\b(?:open|view)\s+(?:in\s+)?(?:browser|chrome|safari)\b/i;
3
9
  const SERVER_COMMAND = /^\s*(?:python(?:3(?:\.\d+)?)?\s+(?:-u\s+)?(?:\S*\/)?server\.py\b|python(?:3(?:\.\d+)?)?\s+-m\s+http\.server\b|(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:dev|start|serve)\b|(?:npx|bunx)\s+(?:vite|next\s+dev|http-server)\b|uvicorn\b|gunicorn\b|flask\s+run\b)/i;
4
10
  const READ_ONLY_COMMAND = /^\s*(?:pwd|ls|rg|grep|cat|head|tail|find|which|where|ps|pgrep|lsof|netstat|ss|git\s+(?:status|diff|log|show)|node\s+(?:-v|--version)|python(?:3(?:\.\d+)?)?\s+(?:-V|--version))\b/i;
5
11
  const OPEN_COMMAND = /^\s*(?:open|xdg-open|start)\s+\S+/i;
@@ -11,11 +17,29 @@ const MUTATION_TOOLS = new Set([
11
17
  'create_skill', 'manage_local_dependencies'
12
18
  ]);
13
19
  export function isLaunchOnlyPrompt(prompt) {
20
+ if (!prompt || typeof prompt !== 'string')
21
+ return false;
22
+ const trimmed = prompt.trim();
23
+ if (trimmed.length === 0)
24
+ return false;
25
+ if (trimmed.split(/\s+/).length > 25 || trimmed.length > 150)
26
+ return false;
14
27
  if (/\b(?:run|execute)\s+(?:the\s+)?(?:tests?|checks?|lint|benchmarks?|scripts?|commands?|tools?|creative_apps|resolve_act|memory_recall|native_engine|browser_act|fs_read|sysRun)\b/i.test(prompt))
15
28
  return false;
16
29
  if (/\b(?:verify|verification|verify_bridge|inspectActive|simulate|probe|audit|analyze|diagnose)\b/i.test(prompt))
17
30
  return false;
18
- return LAUNCH_VERBS.test(prompt) && !CHANGE_VERBS.test(prompt);
31
+ if (CREATIVE_WORDS.test(prompt))
32
+ return false;
33
+ if (INQUIRY_WORDS.test(prompt))
34
+ return false;
35
+ if (CHANGE_VERBS.test(prompt))
36
+ return false;
37
+ if (NON_LAUNCH_PHRASES.test(prompt))
38
+ return false;
39
+ return IMPERATIVE_LAUNCH.test(prompt)
40
+ || TARGETED_LAUNCH.test(prompt)
41
+ || URL_OR_FILE_LAUNCH.test(prompt)
42
+ || BROWSER_LAUNCH.test(prompt);
19
43
  }
20
44
  export function isServerLaunchCommand(command) {
21
45
  return SERVER_COMMAND.test(command.trim());
@@ -1,5 +1,12 @@
1
- const LAUNCH_VERBS = /\b(open|launch|start|run|play|serve|preview)\b/i;
2
- const CHANGE_VERBS = /\b(create|build|make|write|edit|fix|modify|change|update|implement|generate|refactor|delete|remove|install|deploy)\b/i;
1
+ const CREATIVE_WORDS = /\b(?:story|novel|fiction|narrative|lore|essay|poem|poetry|chapter|character|plot|dialogue|scene|cerita|kisah|dongeng|karangan|buku|tulisan|bab|paragraf|halaman)\b/i;
2
+ const INQUIRY_WORDS = /\b(?:explain|why|what|how|who|where|when|analyze|describe|tell\s+me|show\s+me\s+how|difference|summary|summarize|review|audit|jelaskan|kenapa|mengapa|bagaimana|siapa|apakah|analisis)\b/i;
3
+ const CHANGE_VERBS = /\b(?:create|build|make|write|edit|fix|modify|change|update|implement|generate|refactor|delete|remove|install|deploy|add|append|expand|continue|improve|refine|compose|draft|author|design|buat(?:kan)?|bikin|tulis(?:kan)?|ubah|ganti|perbaiki|tambah(?:kan)?|kembangkan|lanjut(?:kan)?|sambung(?:kan)?|membaut|maembuat|merancang|susun|crear|escribir|construir|modificar|actualizar|créer|écrire|modifier|erstellen|schreiben|bauen)\b/i;
4
+ const NON_LAUNCH_PHRASES = /\b(?:(?:run|runs|running)\s+(?:by|on|in|with|out|through)|(?:play|plays|playing)\s+(?:a\s+role|with)|(?:open|opens|opening)\s+(?:to|world|source|mind|ended|door)|(?:start|starts|starting)\s+(?:with|from)|(?:serve|serves|serving)\s+(?:as|to)|in\s+the\s+long\s+run|home\s+run)\b/i;
5
+
6
+ const IMPERATIVE_LAUNCH = /^\s*(?:please\s+|can\s+you\s+)?(?:open|launch|start|run|play|serve|preview)(?:\s+(?:it|this|that|app|application|project|game|server|service|dev|preview|up|now|here|locally))?\s*[.!?]?\s*$/i;
7
+ const TARGETED_LAUNCH = /\b(?:open|launch|start|run|play|serve|preview)\s+(?:up\s+)?(?:the\s+|this\s+|an?\s+)?(?:app|application|project|game|server|dev\s+server|website|site|page|ui|preview|demo|localhost|frontend|backend)\b/i;
8
+ const URL_OR_FILE_LAUNCH = /^\s*(?:open|preview)\s+(?:https?:\/\/|\/|~\/|\.\/|[a-zA-Z0-9_\-\.\/]+\.(?:html|htm|php|py|js|ts))\b/i;
9
+ const BROWSER_LAUNCH = /\b(?:open|view)\s+(?:in\s+)?(?:browser|chrome|safari)\b/i;
3
10
  const SERVER_COMMAND = /^\s*(?:python(?:3(?:\.\d+)?)?\s+(?:-u\s+)?(?:\S*\/)?server\.py\b|python(?:3(?:\.\d+)?)?\s+-m\s+http\.server\b|(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:dev|start|serve)\b|(?:npx|bunx)\s+(?:vite|next\s+dev|http-server)\b|uvicorn\b|gunicorn\b|flask\s+run\b)/i;
4
11
  const READ_ONLY_COMMAND = /^\s*(?:pwd|ls|rg|grep|cat|head|tail|find|which|where|ps|pgrep|lsof|netstat|ss|git\s+(?:status|diff|log|show)|node\s+(?:-v|--version)|python(?:3(?:\.\d+)?)?\s+(?:-V|--version))\b/i;
5
12
  const OPEN_COMMAND = /^\s*(?:open|xdg-open|start)\s+\S+/i;
@@ -13,9 +20,23 @@ const MUTATION_TOOLS = new Set([
13
20
  ]);
14
21
 
15
22
  export function isLaunchOnlyPrompt(prompt: string): boolean {
23
+ if (!prompt || typeof prompt !== 'string') return false;
24
+ const trimmed = prompt.trim();
25
+ if (trimmed.length === 0) return false;
26
+ if (trimmed.split(/\s+/).length > 25 || trimmed.length > 150) return false;
27
+
16
28
  if (/\b(?:run|execute)\s+(?:the\s+)?(?:tests?|checks?|lint|benchmarks?|scripts?|commands?|tools?|creative_apps|resolve_act|memory_recall|native_engine|browser_act|fs_read|sysRun)\b/i.test(prompt)) return false;
17
29
  if (/\b(?:verify|verification|verify_bridge|inspectActive|simulate|probe|audit|analyze|diagnose)\b/i.test(prompt)) return false;
18
- return LAUNCH_VERBS.test(prompt) && !CHANGE_VERBS.test(prompt);
30
+
31
+ if (CREATIVE_WORDS.test(prompt)) return false;
32
+ if (INQUIRY_WORDS.test(prompt)) return false;
33
+ if (CHANGE_VERBS.test(prompt)) return false;
34
+ if (NON_LAUNCH_PHRASES.test(prompt)) return false;
35
+
36
+ return IMPERATIVE_LAUNCH.test(prompt)
37
+ || TARGETED_LAUNCH.test(prompt)
38
+ || URL_OR_FILE_LAUNCH.test(prompt)
39
+ || BROWSER_LAUNCH.test(prompt);
19
40
  }
20
41
 
21
42
  export function isServerLaunchCommand(command: string): boolean {
@@ -14,6 +14,7 @@ export class ChatRenderer {
14
14
  _activeReasoning?: boolean;
15
15
  handle(message: { type: string; [key: string]: unknown }): boolean;
16
16
  resetTurn(): void;
17
+ turnFooter(durationMs?: number): void;
17
18
  onAgentReasoning(message: { content?: string; streaming?: boolean; elapsedMs?: number }): void;
18
19
  renderReasoning(content: string, options?: { streaming?: boolean; durationText?: string; collapsed?: boolean; startLine?: number }): void;
19
20
  scrollThinkingPanel?(key: unknown, surface: unknown): boolean;
@@ -25,7 +25,7 @@ import { composerWidth, openingRows, sessionRows } from './layout.js';
25
25
  import { sessionComposerWidth } from './sessionSidebar.js';
26
26
  import { chatProseWidth, wrappedChatRows } from './textLayout.js';
27
27
  import { activityRows } from './activityLayout.js';
28
- import { cleanToolOutputPreview, normalizeHistoricalToolResult } from './toolOutputNormalizer.js';
28
+ import { cleanToolOutputPreview, normalizeHistoricalToolResult, normalizeHistoricalExternalAction } from './toolOutputNormalizer.js';
29
29
  import { formatMarkdownMath } from './markdownMath.js';
30
30
  import { renderThinkingFrame } from './thinkingBox.js';
31
31
 
@@ -590,17 +590,40 @@ export class ChatRenderer {
590
590
  this.resetTurn();
591
591
  this.renderUserMessage(msg.content);
592
592
  } else if (role === 'assistant') {
593
- // If assistant has textual content, render it
594
- const text = typeof msg.content === 'string'
595
- ? msg.content
596
- : (Array.isArray(msg.content)
597
- ? msg.content.map(p => (typeof p === 'string' ? p : (p && p.text) || '')).filter(Boolean).join('\n')
598
- : String(msg.content || ''));
599
- if (text.trim()) {
600
- this.renderAssistantMessage(text);
593
+ // 1. Restore reasoning content as an auto-minimized thinking box
594
+ const reasoning = typeof msg.reasoning_content === 'string'
595
+ ? msg.reasoning_content.trim()
596
+ : (Array.isArray(msg.thinking_blocks)
597
+ ? msg.thinking_blocks.map(b => (typeof b === 'string' ? b : b?.thinking || b?.text || '')).filter(Boolean).join('\n').trim()
598
+ : '');
599
+ if (reasoning) {
600
+ const meta = {
601
+ reasoning: true,
602
+ done: true,
603
+ streaming: false,
604
+ collapsed: true,
605
+ durationText: '',
606
+ content: reasoning,
607
+ scrollStart: 0
608
+ };
609
+ this.frame('reasoning', () => this.renderReasoning(meta.content, {
610
+ streaming: false,
611
+ durationText: '',
612
+ collapsed: Boolean(meta.collapsed),
613
+ startLine: 0
614
+ }), meta);
615
+ }
616
+
617
+ // 2. Restore external / native ACP tool executions
618
+ if (Array.isArray(msg.external_actions) && msg.external_actions.length > 0) {
619
+ for (const ext of msg.external_actions) {
620
+ const { toolName, args, result } = normalizeHistoricalExternalAction(ext);
621
+ this.onStepStart({ tool: toolName, args });
622
+ this.onStepComplete({ tool: toolName, result, elapsed: '' });
623
+ }
601
624
  }
602
625
 
603
- // If assistant invoked tool calls, render each tool step and pair with its result
626
+ // 3. If assistant invoked tool calls, render each tool step and pair with its result
604
627
  if (Array.isArray(msg.tool_calls) && msg.tool_calls.length > 0) {
605
628
  for (const call of msg.tool_calls) {
606
629
  const toolName = call.function?.name || call.name || 'tool';
@@ -647,6 +670,16 @@ export class ChatRenderer {
647
670
  }
648
671
  }
649
672
  }
673
+
674
+ // 4. If assistant has textual content, render it
675
+ const text = typeof msg.content === 'string'
676
+ ? msg.content
677
+ : (Array.isArray(msg.content)
678
+ ? msg.content.map(p => (typeof p === 'string' ? p : (p && p.text) || '')).filter(Boolean).join('\n')
679
+ : String(msg.content || ''));
680
+ if (text.trim()) {
681
+ this.renderAssistantMessage(text);
682
+ }
650
683
  } else if (role === 'tool') {
651
684
  // Standalone or un-paired tool message (e.g. from compacted session turns)
652
685
  if (!renderedToolMessages.has(msg)) {
@@ -757,7 +790,7 @@ export class ChatRenderer {
757
790
  scrollStart: 0
758
791
  };
759
792
  this.frame('reasoning', () => this.renderReasoning(meta.content, {
760
- streaming: true,
793
+ streaming: Boolean(meta.streaming),
761
794
  durationText: meta.durationText,
762
795
  collapsed: Boolean(meta.collapsed),
763
796
  startLine: Number(meta.scrollStart) || 0
@@ -770,7 +803,7 @@ export class ChatRenderer {
770
803
  if (meta.collapsed === undefined) meta.collapsed = false;
771
804
  if (meta.scrollStart === undefined) meta.scrollStart = 0;
772
805
  this.updateTailFrame('reasoning', () => this.renderReasoning(meta.content, {
773
- streaming: true,
806
+ streaming: Boolean(meta.streaming),
774
807
  durationText: meta.durationText,
775
808
  collapsed: Boolean(meta.collapsed),
776
809
  startLine: Number(meta.scrollStart) || 0
@@ -786,10 +819,10 @@ export class ChatRenderer {
786
819
  meta.done = true;
787
820
  meta.durationText = durationText;
788
821
  meta.content = content;
789
- if (meta.collapsed === undefined) meta.collapsed = false;
822
+ if (meta.collapsed === undefined) meta.collapsed = Boolean(msg.collapsed);
790
823
  if (meta.scrollStart === undefined) meta.scrollStart = 0;
791
824
  this.updateTailFrame('reasoning', () => this.renderReasoning(meta.content, {
792
- streaming: false,
825
+ streaming: Boolean(meta.streaming),
793
826
  durationText: meta.durationText,
794
827
  collapsed: Boolean(meta.collapsed),
795
828
  startLine: Number(meta.scrollStart) || 0
@@ -801,11 +834,11 @@ export class ChatRenderer {
801
834
  streaming: false,
802
835
  durationText,
803
836
  content,
804
- collapsed: false,
837
+ collapsed: Boolean(msg.collapsed),
805
838
  scrollStart: 0
806
839
  };
807
840
  this.frame('reasoning', () => this.renderReasoning(meta.content, {
808
- streaming: false,
841
+ streaming: Boolean(meta.streaming),
809
842
  durationText: meta.durationText,
810
843
  collapsed: Boolean(meta.collapsed),
811
844
  startLine: Number(meta.scrollStart) || 0
@@ -81,8 +81,37 @@ export class CodeStreamRenderer extends ChatRenderer {
81
81
  this.activeCode = null;
82
82
  this.modelNote = '';
83
83
  this.lastReasoning = '';
84
+ this.collapseFinishedReasoningFrames(true);
84
85
  super.resetTurn();
85
86
  }
87
+ turnFooter(durationMs) {
88
+ this.collapseFinishedReasoningFrames(true);
89
+ super.turnFooter(durationMs);
90
+ }
91
+ /**
92
+ * Auto-collapses completed thinking box frames when a session turn finishes,
93
+ * keeping the conversation viewport clean while preserving interactive click-to-expand.
94
+ */
95
+ collapseFinishedReasoningFrames(forceAll = false) {
96
+ const transcript = this.transcript;
97
+ if (!transcript || !Array.isArray(transcript.frames))
98
+ return;
99
+ let changed = false;
100
+ for (const frame of transcript.frames) {
101
+ if (frame?.meta?.reasoning === true && (forceAll || frame.meta.userInteracted !== true) && frame.meta.collapsed !== true) {
102
+ frame.meta.collapsed = true;
103
+ frame.meta.streaming = false;
104
+ frame.rows = null;
105
+ frame.renderedWidth = -1;
106
+ changed = true;
107
+ }
108
+ }
109
+ if (changed) {
110
+ transcript.cache = null;
111
+ transcript.revision++;
112
+ transcript.changed();
113
+ }
114
+ }
86
115
  handle(message) {
87
116
  if (message?.type === 'notice' && message.nativeStep === true) {
88
117
  this.stepCount = (this.stepCount || 0) + 1;
@@ -104,13 +133,15 @@ export class CodeStreamRenderer extends ChatRenderer {
104
133
  const note = content.trim().split('\n').at(-1) || '';
105
134
  this.modelNote = note.slice(-140);
106
135
  this.paintCodePanel(this.activeCode);
107
- if (message.streaming === false)
136
+ if (message.streaming === false) {
108
137
  this.lastReasoning = '';
138
+ }
109
139
  return true;
110
140
  }
111
141
  const handled = super.handle(message);
112
- if (message.streaming === false)
142
+ if (message.streaming === false) {
113
143
  this.lastReasoning = '';
144
+ }
114
145
  return handled;
115
146
  }
116
147
  if (['agent_message', 'agent_activity', 'notice', 'budget_warning', 'step_start', 'task_complete', 'error', 'agent_plan'].includes(message?.type || '')) {
@@ -119,6 +150,9 @@ export class CodeStreamRenderer extends ChatRenderer {
119
150
  }
120
151
  this._activeReasoning = false;
121
152
  this.lastReasoning = '';
153
+ if (message?.type === 'task_complete' || (message?.type === 'agent_message' && message.streaming !== true)) {
154
+ this.collapseFinishedReasoningFrames(true);
155
+ }
122
156
  if (['step_start', 'task_complete', 'error'].includes(message?.type || '')
123
157
  || (message?.type === 'agent_message' && message.streaming !== true)) {
124
158
  this.activeCode = null;
@@ -99,9 +99,39 @@ export class CodeStreamRenderer extends ChatRenderer {
99
99
  this.activeCode = null;
100
100
  this.modelNote = '';
101
101
  this.lastReasoning = '';
102
+ this.collapseFinishedReasoningFrames(true);
102
103
  super.resetTurn();
103
104
  }
104
105
 
106
+ override turnFooter(durationMs: number): void {
107
+ this.collapseFinishedReasoningFrames(true);
108
+ super.turnFooter(durationMs);
109
+ }
110
+
111
+ /**
112
+ * Auto-collapses completed thinking box frames when a session turn finishes,
113
+ * keeping the conversation viewport clean while preserving interactive click-to-expand.
114
+ */
115
+ collapseFinishedReasoningFrames(forceAll = false): void {
116
+ const transcript = this.transcript as unknown as CodeTranscript | null;
117
+ if (!transcript || !Array.isArray(transcript.frames)) return;
118
+ let changed = false;
119
+ for (const frame of transcript.frames) {
120
+ if (frame?.meta?.reasoning === true && (forceAll || frame.meta.userInteracted !== true) && frame.meta.collapsed !== true) {
121
+ frame.meta.collapsed = true;
122
+ frame.meta.streaming = false;
123
+ frame.rows = null;
124
+ frame.renderedWidth = -1;
125
+ changed = true;
126
+ }
127
+ }
128
+ if (changed) {
129
+ transcript.cache = null;
130
+ transcript.revision++;
131
+ transcript.changed();
132
+ }
133
+ }
134
+
105
135
  override handle(message: RendererEvent): boolean {
106
136
  if (message?.type === 'notice' && message.nativeStep === true) {
107
137
  this.stepCount = (this.stepCount || 0) + 1;
@@ -122,11 +152,15 @@ export class CodeStreamRenderer extends ChatRenderer {
122
152
  const note = content.trim().split('\n').at(-1) || '';
123
153
  this.modelNote = note.slice(-140);
124
154
  this.paintCodePanel(this.activeCode);
125
- if (message.streaming === false) this.lastReasoning = '';
155
+ if (message.streaming === false) {
156
+ this.lastReasoning = '';
157
+ }
126
158
  return true;
127
159
  }
128
160
  const handled = super.handle(message);
129
- if (message.streaming === false) this.lastReasoning = '';
161
+ if (message.streaming === false) {
162
+ this.lastReasoning = '';
163
+ }
130
164
  return handled;
131
165
  }
132
166
  if (['agent_message', 'agent_activity', 'notice', 'budget_warning', 'step_start', 'task_complete', 'error', 'agent_plan'].includes(message?.type || '')) {
@@ -135,6 +169,9 @@ export class CodeStreamRenderer extends ChatRenderer {
135
169
  }
136
170
  this._activeReasoning = false;
137
171
  this.lastReasoning = '';
172
+ if (message?.type === 'task_complete' || (message?.type === 'agent_message' && message.streaming !== true)) {
173
+ this.collapseFinishedReasoningFrames(true);
174
+ }
138
175
  if (['step_start', 'task_complete', 'error'].includes(message?.type || '')
139
176
  || (message?.type === 'agent_message' && message.streaming !== true)) {
140
177
  this.activeCode = null;
@@ -115,6 +115,7 @@ export function handleMessageMouse(host, loop, event) {
115
115
  const frame = Array.isArray(frames) ? frames.find(f => f.id === rawMarker.id) : null;
116
116
  if (frame && frame.meta && frame.meta.reasoning) {
117
117
  frame.meta.collapsed = !frame.meta.collapsed;
118
+ frame.meta.userInteracted = true;
118
119
  frame.rows = null;
119
120
  frame.renderedWidth = -1;
120
121
  if (transcript) {
@@ -22,7 +22,7 @@ export interface MessageMarker {
22
22
  id: number;
23
23
  kind: string;
24
24
  row: number;
25
- meta?: { messageText?: string; reasoning?: boolean; collapsed?: boolean } | null;
25
+ meta?: { messageText?: string; reasoning?: boolean; collapsed?: boolean; userInteracted?: boolean } | null;
26
26
  }
27
27
 
28
28
  interface MousePoint { x: number; y: number }
@@ -188,7 +188,7 @@ export function handleMessageMouse(
188
188
  const transcript = surface.transcript as unknown as {
189
189
  frames?: Array<{
190
190
  id: number;
191
- meta?: { reasoning?: boolean; collapsed?: boolean } | null;
191
+ meta?: { reasoning?: boolean; collapsed?: boolean; userInteracted?: boolean } | null;
192
192
  rows?: unknown;
193
193
  renderedWidth?: number;
194
194
  }>;
@@ -200,6 +200,7 @@ export function handleMessageMouse(
200
200
  const frame = Array.isArray(frames) ? frames.find(f => f.id === rawMarker.id) : null;
201
201
  if (frame && frame.meta && frame.meta.reasoning) {
202
202
  frame.meta.collapsed = !frame.meta.collapsed;
203
+ frame.meta.userInteracted = true;
203
204
  frame.rows = null;
204
205
  frame.renderedWidth = -1;
205
206
  if (transcript) {
@@ -1,4 +1,33 @@
1
1
  import fs from 'node:fs';
2
+ /**
3
+ * Normalizes an external/native action record for historical transcript restoration,
4
+ * reconstructing arguments and ensuring verified success/failure status.
5
+ */
6
+ export function normalizeHistoricalExternalAction(ext) {
7
+ const toolName = typeof ext?.name === 'string' && ext.name.trim() ? ext.name.trim() : 'tool';
8
+ const detail = typeof ext?.detail === 'string' ? ext.detail.trim() : '';
9
+ const status = typeof ext?.status === 'string' ? ext.status.toLowerCase().trim() : '';
10
+ const isFailed = status === 'failed' || status === 'error';
11
+ const success = !isFailed;
12
+ const rawParams = ext?.parameters && typeof ext.parameters === 'object' && !Array.isArray(ext.parameters)
13
+ ? { ...ext.parameters }
14
+ : {};
15
+ const lowerTool = toolName.toLowerCase();
16
+ const isFileTool = ['read_file', 'write_file', 'edit_file', 'fs_read', 'fs_write', 'fs_edit', 'view_file'].includes(lowerTool);
17
+ const isCommandTool = ['run_command', 'bash', 'terminal', 'sh', 'zsh', 'sysrun', 'sysrunbg'].includes(lowerTool);
18
+ const args = {
19
+ ...rawParams,
20
+ ...(detail ? { detail } : {}),
21
+ ...(detail && isFileTool && !rawParams.path && !rawParams.file_path && !rawParams.filePath ? { path: detail } : {}),
22
+ ...(detail && isCommandTool && !rawParams.command && !rawParams.cmd ? { command: detail } : {})
23
+ };
24
+ const result = {
25
+ success,
26
+ output: '',
27
+ ...(isFailed ? { error: typeof ext?.error === 'string' && ext.error ? ext.error : (detail || 'failed') } : {})
28
+ };
29
+ return { toolName, args, result };
30
+ }
2
31
  const DECAY_MARKER = '[decayed]';
3
32
  const SPILL_HEADER_PREFIX = '=== CAUSYNE TOOL OUTPUT';
4
33
  /**
@@ -14,6 +14,59 @@ export interface NormalizedHistoricalToolResult {
14
14
  plan?: Array<Record<string, unknown>> | undefined;
15
15
  }
16
16
 
17
+ export interface HistoricalExternalAction {
18
+ id?: string | undefined;
19
+ name?: string | undefined;
20
+ status?: string | undefined;
21
+ detail?: string | undefined;
22
+ parameters?: Record<string, unknown> | undefined;
23
+ error?: string | undefined;
24
+ }
25
+
26
+ export interface NormalizedExternalActionResult {
27
+ toolName: string;
28
+ args: Record<string, unknown>;
29
+ result: {
30
+ success: boolean;
31
+ output: string;
32
+ error?: string | undefined;
33
+ };
34
+ }
35
+
36
+ /**
37
+ * Normalizes an external/native action record for historical transcript restoration,
38
+ * reconstructing arguments and ensuring verified success/failure status.
39
+ */
40
+ export function normalizeHistoricalExternalAction(ext: HistoricalExternalAction | null | undefined): NormalizedExternalActionResult {
41
+ const toolName = typeof ext?.name === 'string' && ext.name.trim() ? ext.name.trim() : 'tool';
42
+ const detail = typeof ext?.detail === 'string' ? ext.detail.trim() : '';
43
+ const status = typeof ext?.status === 'string' ? ext.status.toLowerCase().trim() : '';
44
+ const isFailed = status === 'failed' || status === 'error';
45
+ const success = !isFailed;
46
+
47
+ const rawParams = ext?.parameters && typeof ext.parameters === 'object' && !Array.isArray(ext.parameters)
48
+ ? { ...ext.parameters }
49
+ : {};
50
+ const lowerTool = toolName.toLowerCase();
51
+ const isFileTool = ['read_file', 'write_file', 'edit_file', 'fs_read', 'fs_write', 'fs_edit', 'view_file'].includes(lowerTool);
52
+ const isCommandTool = ['run_command', 'bash', 'terminal', 'sh', 'zsh', 'sysrun', 'sysrunbg'].includes(lowerTool);
53
+
54
+ const args: Record<string, unknown> = {
55
+ ...rawParams,
56
+ ...(detail ? { detail } : {}),
57
+ ...(detail && isFileTool && !rawParams.path && !rawParams.file_path && !rawParams.filePath ? { path: detail } : {}),
58
+ ...(detail && isCommandTool && !rawParams.command && !rawParams.cmd ? { command: detail } : {})
59
+ };
60
+
61
+ const result: { success: boolean; output: string; error?: string | undefined } = {
62
+ success,
63
+ output: '',
64
+ ...(isFailed ? { error: typeof ext?.error === 'string' && ext.error ? ext.error : (detail || 'failed') } : {})
65
+ };
66
+
67
+ return { toolName, args, result };
68
+ }
69
+
17
70
  const DECAY_MARKER = '[decayed]';
18
71
  const SPILL_HEADER_PREFIX = '=== CAUSYNE TOOL OUTPUT';
19
72