@causyne/agent 1.20.34 → 1.20.36

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 CHANGED
@@ -9,7 +9,7 @@ Parameters
9
9
 
10
10
  Licensor: Ikbal Fadilah
11
11
 
12
- Licensed Work: Causyne Agent 1.20.13
12
+ Licensed Work: Causyne Agent 1.20.36
13
13
  The Licensed Work is (c) 2026 Ikbal Fadilah.
14
14
 
15
15
  Additional Use Grant: You may make use of the Licensed Work, provided that
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@causyne/agent",
3
- "version": "1.20.34",
3
+ "version": "1.20.36",
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
@@ -552,7 +552,7 @@ export class AgentLoop {
552
552
  this.recentActionSignatures = [];
553
553
  this.consecutiveReadOnlySteps = 0;
554
554
  this.stallGuard = new StallGuardController();
555
- this.smartToolsGovernor = new SmartToolsGovernor();
555
+ this.smartToolsGovernor = new SmartToolsGovernor(4);
556
556
  this._smartToolsNudge = null;
557
557
  // Sovereign Progressive Disclosure: which capability packs have entered the
558
558
  // context window for this task. Nothing is disabled — see src/toolPacks.js.
@@ -1322,12 +1322,14 @@ export class AgentLoop {
1322
1322
  return;
1323
1323
  const keepSeeded = Boolean(this._implementationPlanSeeded);
1324
1324
  if (kind === 'complete') {
1325
- if (this._implementationPlan.every((item) => item.status === 'completed'))
1326
- return;
1327
- this.updateImplementationPlan({
1328
- explanation: 'Task completed.',
1329
- plan: this._implementationPlan.map((item) => ({ ...item, status: 'completed' }))
1330
- }, { seeded: keepSeeded });
1325
+ const completedPlan = this._implementationPlan.map((item) => ({ ...item, status: 'completed' }));
1326
+ if (!this._implementationPlan.every((item) => item.status === 'completed')) {
1327
+ this.updateImplementationPlan({
1328
+ explanation: 'Task completed.',
1329
+ plan: completedPlan
1330
+ }, { seeded: keepSeeded });
1331
+ }
1332
+ this.syncCompletedPlanToLatestTurnMessages(completedPlan);
1331
1333
  return;
1332
1334
  }
1333
1335
  if (this._implementationPlan.length < 2)
@@ -1335,7 +1337,13 @@ export class AgentLoop {
1335
1337
  const activeIndex = this._implementationPlan.findIndex((item) => item.status === 'in_progress');
1336
1338
  const currentIndex = activeIndex >= 0 ? activeIndex : 0;
1337
1339
  const lastIndex = this._implementationPlan.length - 1;
1338
- const targetIndex = kind === 'verification'
1340
+ const isInitialPreMutationInspection = kind === 'verification'
1341
+ && !this.smartToolsGovernor.snapshot().mutationAttempted
1342
+ && currentIndex === 0;
1343
+ if (isInitialPreMutationInspection && !keepSeeded)
1344
+ return;
1345
+ const effectiveKind = isInitialPreMutationInspection ? 'mutation' : kind;
1346
+ const targetIndex = effectiveKind === 'verification'
1339
1347
  ? lastIndex
1340
1348
  : Math.min(currentIndex + 1, Math.max(0, lastIndex - 1));
1341
1349
  if (targetIndex <= currentIndex)
@@ -1346,6 +1354,58 @@ export class AgentLoop {
1346
1354
  }));
1347
1355
  this.updateImplementationPlan({ explanation: '', plan: nextPlan }, { seeded: keepSeeded });
1348
1356
  }
1357
+ syncCompletedPlanToLatestTurnMessages(completedPlan) {
1358
+ if (!Array.isArray(this.messages) || this.messages.length === 0)
1359
+ return;
1360
+ let updatedCallId = null;
1361
+ for (let i = this.messages.length - 1; i >= 0; i--) {
1362
+ const msg = this.messages[i];
1363
+ if (!msg)
1364
+ continue;
1365
+ if (msg.role === 'user')
1366
+ break;
1367
+ if (msg.role === 'assistant' && Array.isArray(msg.tool_calls)) {
1368
+ for (let j = msg.tool_calls.length - 1; j >= 0; j--) {
1369
+ const call = msg.tool_calls[j];
1370
+ if (call?.function?.name === 'update_plan' && typeof call.function.arguments === 'string') {
1371
+ try {
1372
+ const parsed = JSON.parse(call.function.arguments);
1373
+ if (parsed && typeof parsed === 'object' && Array.isArray(parsed.plan)) {
1374
+ parsed.plan = completedPlan;
1375
+ call.function.arguments = JSON.stringify(parsed);
1376
+ updatedCallId = call.id || null;
1377
+ break;
1378
+ }
1379
+ }
1380
+ catch { /* ignore non-JSON arguments */ }
1381
+ }
1382
+ }
1383
+ if (updatedCallId)
1384
+ break;
1385
+ }
1386
+ }
1387
+ if (!updatedCallId)
1388
+ return;
1389
+ for (let i = this.messages.length - 1; i >= 0; i--) {
1390
+ const msg = this.messages[i];
1391
+ if (!msg)
1392
+ continue;
1393
+ if (msg.role === 'user')
1394
+ break;
1395
+ if (msg.role === 'tool' && msg.tool_call_id === updatedCallId && typeof msg.content === 'string' && !msg.content.startsWith('[decayed]')) {
1396
+ try {
1397
+ const parsed = JSON.parse(msg.content);
1398
+ if (parsed && typeof parsed === 'object') {
1399
+ parsed.plan = completedPlan;
1400
+ parsed.output = `${completedPlan.length}/${completedPlan.length} completed`;
1401
+ msg.content = JSON.stringify(parsed);
1402
+ }
1403
+ }
1404
+ catch { /* ignore */ }
1405
+ break;
1406
+ }
1407
+ }
1408
+ }
1349
1409
  async requestDecision(request) {
1350
1410
  const fingerprint = createHash('sha256')
1351
1411
  .update(JSON.stringify({ kind: request.kind, question: request.question, options: request.options.map((option) => option.id) }))
@@ -2562,6 +2622,37 @@ You are operating in a text-and-code modality without direct image pixel renderi
2562
2622
  }
2563
2623
  }
2564
2624
  }
2625
+ // If the peer attempted to call a registered Causyne host tool through its
2626
+ // native channel and provided complete, valid arguments (or we can infer
2627
+ // the target for reverse_engineering), auto-bridge it into response.toolCalls
2628
+ // BEFORE recording assistantMsg so it executes immediately in this turn.
2629
+ if ((!response.toolCalls || response.toolCalls.length === 0) && response.toolRoutingError) {
2630
+ const rawName = response.toolRoutingError.tool;
2631
+ const resolved = resolveTool(rawName);
2632
+ if (resolved) {
2633
+ const canonical = canonicalToolName(rawName);
2634
+ const toolParams = { ...(response.toolRoutingError.parameters || {}) };
2635
+ if (canonical === 'reverse_engineering' && !toolParams.filePath && !toolParams.target && !toolParams.file && !toolParams.path) {
2636
+ const promptMatch = (this.currentTaskPrompt || this.userPrompt || '').match(/([a-zA-Z0-9_\-./]+\.(apk|aab|dex|dylib|so|dll|exe|asar))\b/i);
2637
+ if (promptMatch && promptMatch[1]) {
2638
+ toolParams.filePath = promptMatch[1];
2639
+ if (!toolParams.action)
2640
+ toolParams.action = 'inspect';
2641
+ }
2642
+ }
2643
+ if (Object.keys(toolParams).length > 0 && !this.validateToolArgs(canonical, toolParams)) {
2644
+ response.toolCalls = [{
2645
+ id: `host_auto_${Date.now()}`,
2646
+ type: 'function',
2647
+ function: {
2648
+ name: canonical,
2649
+ arguments: JSON.stringify(toolParams)
2650
+ }
2651
+ }];
2652
+ delete response.toolRoutingError;
2653
+ }
2654
+ }
2655
+ }
2565
2656
  // Add assistant response to history. This is the ONLY place the turn is
2566
2657
  // recorded — the completion and guard branches below used to push it a
2567
2658
  // second time, duplicating every finished turn in the history.
@@ -2641,31 +2732,11 @@ You are operating in a text-and-code modality without direct image pixel renderi
2641
2732
  if (!response.toolCalls || response.toolCalls.length === 0) {
2642
2733
  if (response.toolRoutingError) {
2643
2734
  const rawName = response.toolRoutingError.tool;
2644
- const resolved = resolveTool(rawName);
2645
- if (resolved) {
2646
- const canonical = canonicalToolName(rawName);
2647
- const toolParams = { ...(response.toolRoutingError.parameters || {}) };
2648
- if (canonical === 'reverse_engineering' && !toolParams.filePath && !toolParams.target && !toolParams.file && !toolParams.path) {
2649
- const promptMatch = (this.currentTaskPrompt || this.userPrompt || '').match(/([a-zA-Z0-9_\-./]+\.(apk|aab|dex|dylib|so|dll|exe|asar))\b/i);
2650
- if (promptMatch && promptMatch[1]) {
2651
- toolParams.filePath = promptMatch[1];
2652
- if (!toolParams.action)
2653
- toolParams.action = 'inspect';
2654
- }
2655
- }
2656
- // Direct auto-bridge: peer explicitly targeted a registered host tool
2657
- response.toolCalls = [{
2658
- id: `host_auto_${Date.now()}`,
2659
- type: 'function',
2660
- function: {
2661
- name: canonical,
2662
- arguments: JSON.stringify(toolParams)
2663
- }
2664
- }];
2665
- delete response.toolRoutingError;
2735
+ if (typeof assistantMsg.content === 'string' && /^Turn completed by .+ over ACP\.$/i.test(assistantMsg.content.trim())) {
2736
+ this.messages.pop();
2666
2737
  }
2667
- else if (toolRoutingRecoveries++ >= 3) {
2668
- this.emitEvent({ type: 'error', message: `The peer repeatedly invoked unknown host tool ${rawName}. Work remains unfinished.` });
2738
+ if (toolRoutingRecoveries++ >= 3) {
2739
+ this.emitEvent({ type: 'error', message: `The peer repeatedly invoked host tool ${rawName} through the native channel instead of <tool_call>. Work remains unfinished.` });
2669
2740
  this.memoryManager.saveHistory(this.messages);
2670
2741
  break;
2671
2742
  }
@@ -3188,6 +3259,10 @@ You are operating in a text-and-code modality without direct image pixel renderi
3188
3259
  // makes, so a denied path is never read behind the guard's back.
3189
3260
  // * Only a SUCCESSFUL prefetch is consumed. A failure is discarded and
3190
3261
  // the serial path executes normally, so TimeMachine sees its outcome.
3262
+ // If native peer actions inside llm.chat() reached the synthesis checkpoint,
3263
+ // start a fresh host inspection batch for the returned toolCalls so the
3264
+ // first host inspection in this turn is not rejected on arrival.
3265
+ this.smartToolsGovernor.beginModelStep();
3191
3266
  const prefetched = this.prefetchReadOnlyCalls(response.toolCalls);
3192
3267
  // 3. ACT (Execute tool calls)
3193
3268
  for (const toolCall of response.toolCalls) {
@@ -3686,7 +3761,11 @@ You are operating in a text-and-code modality without direct image pixel renderi
3686
3761
  this.webVerificationState.screenshotTaken = true;
3687
3762
  }
3688
3763
  if (functionName === 'browser_act' && result?.success === true) {
3689
- this.advanceImplementationPlanProgress('verification');
3764
+ const hasExplicitPlanInBatch = Array.isArray(response.toolCalls)
3765
+ && response.toolCalls.some((c) => canonicalToolName(c?.function?.name || '') === 'update_plan');
3766
+ if (!hasExplicitPlanInBatch) {
3767
+ this.advanceImplementationPlanProgress('verification');
3768
+ }
3690
3769
  const browserResults = Array.isArray(result.data) ? result.data : [];
3691
3770
  const allRuntimeErrors = browserResults.flatMap((item) => Array.isArray(item?.data?.runtimeErrors) ? item.data.runtimeErrors : []);
3692
3771
  const hasValidBrowserAction = browserResults.some((item) => ['preview', 'snapshot', 'scrape', 'screenshot'].includes(item?.action));
package/src/agentLoop.ts CHANGED
@@ -651,7 +651,7 @@ export class AgentLoop {
651
651
  this.recentActionSignatures = [];
652
652
  this.consecutiveReadOnlySteps = 0;
653
653
  this.stallGuard = new StallGuardController();
654
- this.smartToolsGovernor = new SmartToolsGovernor();
654
+ this.smartToolsGovernor = new SmartToolsGovernor(4);
655
655
  this._smartToolsNudge = null;
656
656
 
657
657
  // Sovereign Progressive Disclosure: which capability packs have entered the
@@ -1405,18 +1405,26 @@ export class AgentLoop {
1405
1405
  if (!Array.isArray(this._implementationPlan) || this._implementationPlan.length === 0) return;
1406
1406
  const keepSeeded = Boolean(this._implementationPlanSeeded);
1407
1407
  if (kind === 'complete') {
1408
- if (this._implementationPlan.every((item: any) => item.status === 'completed')) return;
1409
- this.updateImplementationPlan({
1410
- explanation: 'Task completed.',
1411
- plan: this._implementationPlan.map((item: any) => ({ ...item, status: 'completed' }))
1412
- }, { seeded: keepSeeded });
1408
+ const completedPlan = this._implementationPlan.map((item: any) => ({ ...item, status: 'completed' }));
1409
+ if (!this._implementationPlan.every((item: any) => item.status === 'completed')) {
1410
+ this.updateImplementationPlan({
1411
+ explanation: 'Task completed.',
1412
+ plan: completedPlan
1413
+ }, { seeded: keepSeeded });
1414
+ }
1415
+ this.syncCompletedPlanToLatestTurnMessages(completedPlan);
1413
1416
  return;
1414
1417
  }
1415
1418
  if (this._implementationPlan.length < 2) return;
1416
1419
  const activeIndex = this._implementationPlan.findIndex((item: any) => item.status === 'in_progress');
1417
1420
  const currentIndex = activeIndex >= 0 ? activeIndex : 0;
1418
1421
  const lastIndex = this._implementationPlan.length - 1;
1419
- const targetIndex = kind === 'verification'
1422
+ const isInitialPreMutationInspection = kind === 'verification'
1423
+ && !this.smartToolsGovernor.snapshot().mutationAttempted
1424
+ && currentIndex === 0;
1425
+ if (isInitialPreMutationInspection && !keepSeeded) return;
1426
+ const effectiveKind = isInitialPreMutationInspection ? 'mutation' : kind;
1427
+ const targetIndex = effectiveKind === 'verification'
1420
1428
  ? lastIndex
1421
1429
  : Math.min(currentIndex + 1, Math.max(0, lastIndex - 1));
1422
1430
  if (targetIndex <= currentIndex) return;
@@ -1427,6 +1435,50 @@ export class AgentLoop {
1427
1435
  this.updateImplementationPlan({ explanation: '', plan: nextPlan }, { seeded: keepSeeded });
1428
1436
  }
1429
1437
 
1438
+ private syncCompletedPlanToLatestTurnMessages(completedPlan: Array<{ id: string; step: string; status: string }>): void {
1439
+ if (!Array.isArray(this.messages) || this.messages.length === 0) return;
1440
+ let updatedCallId: string | null = null;
1441
+ for (let i = this.messages.length - 1; i >= 0; i--) {
1442
+ const msg = this.messages[i];
1443
+ if (!msg) continue;
1444
+ if (msg.role === 'user') break;
1445
+ if (msg.role === 'assistant' && Array.isArray(msg.tool_calls)) {
1446
+ for (let j = msg.tool_calls.length - 1; j >= 0; j--) {
1447
+ const call = msg.tool_calls[j];
1448
+ if (call?.function?.name === 'update_plan' && typeof call.function.arguments === 'string') {
1449
+ try {
1450
+ const parsed = JSON.parse(call.function.arguments);
1451
+ if (parsed && typeof parsed === 'object' && Array.isArray(parsed.plan)) {
1452
+ parsed.plan = completedPlan;
1453
+ call.function.arguments = JSON.stringify(parsed);
1454
+ updatedCallId = call.id || null;
1455
+ break;
1456
+ }
1457
+ } catch { /* ignore non-JSON arguments */ }
1458
+ }
1459
+ }
1460
+ if (updatedCallId) break;
1461
+ }
1462
+ }
1463
+ if (!updatedCallId) return;
1464
+ for (let i = this.messages.length - 1; i >= 0; i--) {
1465
+ const msg = this.messages[i];
1466
+ if (!msg) continue;
1467
+ if (msg.role === 'user') break;
1468
+ if (msg.role === 'tool' && msg.tool_call_id === updatedCallId && typeof msg.content === 'string' && !msg.content.startsWith('[decayed]')) {
1469
+ try {
1470
+ const parsed = JSON.parse(msg.content);
1471
+ if (parsed && typeof parsed === 'object') {
1472
+ parsed.plan = completedPlan;
1473
+ parsed.output = `${completedPlan.length}/${completedPlan.length} completed`;
1474
+ msg.content = JSON.stringify(parsed);
1475
+ }
1476
+ } catch { /* ignore */ }
1477
+ break;
1478
+ }
1479
+ }
1480
+ }
1481
+
1430
1482
  async requestDecision(request: any) {
1431
1483
  const fingerprint = createHash('sha256')
1432
1484
  .update(JSON.stringify({ kind: request.kind, question: request.question, options: request.options.map((option: any) => option.id) }))
@@ -2691,6 +2743,37 @@ You are operating in a text-and-code modality without direct image pixel renderi
2691
2743
  }
2692
2744
  }
2693
2745
 
2746
+ // If the peer attempted to call a registered Causyne host tool through its
2747
+ // native channel and provided complete, valid arguments (or we can infer
2748
+ // the target for reverse_engineering), auto-bridge it into response.toolCalls
2749
+ // BEFORE recording assistantMsg so it executes immediately in this turn.
2750
+ if ((!response.toolCalls || response.toolCalls.length === 0) && response.toolRoutingError) {
2751
+ const rawName = response.toolRoutingError.tool;
2752
+ const resolved = resolveTool(rawName);
2753
+ if (resolved) {
2754
+ const canonical = canonicalToolName(rawName);
2755
+ const toolParams: Record<string, unknown> = { ...(response.toolRoutingError.parameters || {}) };
2756
+ if (canonical === 'reverse_engineering' && !toolParams.filePath && !toolParams.target && !toolParams.file && !toolParams.path) {
2757
+ const promptMatch = (this.currentTaskPrompt || this.userPrompt || '').match(/([a-zA-Z0-9_\-./]+\.(apk|aab|dex|dylib|so|dll|exe|asar))\b/i);
2758
+ if (promptMatch && promptMatch[1]) {
2759
+ toolParams.filePath = promptMatch[1];
2760
+ if (!toolParams.action) toolParams.action = 'inspect';
2761
+ }
2762
+ }
2763
+ if (Object.keys(toolParams).length > 0 && !this.validateToolArgs(canonical, toolParams)) {
2764
+ response.toolCalls = [{
2765
+ id: `host_auto_${Date.now()}`,
2766
+ type: 'function',
2767
+ function: {
2768
+ name: canonical,
2769
+ arguments: JSON.stringify(toolParams)
2770
+ }
2771
+ }];
2772
+ delete response.toolRoutingError;
2773
+ }
2774
+ }
2775
+ }
2776
+
2694
2777
  // Add assistant response to history. This is the ONLY place the turn is
2695
2778
  // recorded — the completion and guard branches below used to push it a
2696
2779
  // second time, duplicating every finished turn in the history.
@@ -2776,29 +2859,11 @@ You are operating in a text-and-code modality without direct image pixel renderi
2776
2859
  if (!response.toolCalls || response.toolCalls.length === 0) {
2777
2860
  if (response.toolRoutingError) {
2778
2861
  const rawName = response.toolRoutingError.tool;
2779
- const resolved = resolveTool(rawName);
2780
- if (resolved) {
2781
- const canonical = canonicalToolName(rawName);
2782
- const toolParams: Record<string, unknown> = { ...(response.toolRoutingError.parameters || {}) };
2783
- if (canonical === 'reverse_engineering' && !toolParams.filePath && !toolParams.target && !toolParams.file && !toolParams.path) {
2784
- const promptMatch = (this.currentTaskPrompt || this.userPrompt || '').match(/([a-zA-Z0-9_\-./]+\.(apk|aab|dex|dylib|so|dll|exe|asar))\b/i);
2785
- if (promptMatch && promptMatch[1]) {
2786
- toolParams.filePath = promptMatch[1];
2787
- if (!toolParams.action) toolParams.action = 'inspect';
2788
- }
2789
- }
2790
- // Direct auto-bridge: peer explicitly targeted a registered host tool
2791
- response.toolCalls = [{
2792
- id: `host_auto_${Date.now()}`,
2793
- type: 'function',
2794
- function: {
2795
- name: canonical,
2796
- arguments: JSON.stringify(toolParams)
2797
- }
2798
- }];
2799
- delete response.toolRoutingError;
2800
- } else if (toolRoutingRecoveries++ >= 3) {
2801
- this.emitEvent({ type: 'error', message: `The peer repeatedly invoked unknown host tool ${rawName}. Work remains unfinished.` });
2862
+ if (typeof assistantMsg.content === 'string' && /^Turn completed by .+ over ACP\.$/i.test(assistantMsg.content.trim())) {
2863
+ this.messages.pop();
2864
+ }
2865
+ if (toolRoutingRecoveries++ >= 3) {
2866
+ this.emitEvent({ type: 'error', message: `The peer repeatedly invoked host tool ${rawName} through the native channel instead of <tool_call>. Work remains unfinished.` });
2802
2867
  this.memoryManager.saveHistory(this.messages);
2803
2868
  break;
2804
2869
  } else {
@@ -3357,6 +3422,10 @@ You are operating in a text-and-code modality without direct image pixel renderi
3357
3422
  // makes, so a denied path is never read behind the guard's back.
3358
3423
  // * Only a SUCCESSFUL prefetch is consumed. A failure is discarded and
3359
3424
  // the serial path executes normally, so TimeMachine sees its outcome.
3425
+ // If native peer actions inside llm.chat() reached the synthesis checkpoint,
3426
+ // start a fresh host inspection batch for the returned toolCalls so the
3427
+ // first host inspection in this turn is not rejected on arrival.
3428
+ this.smartToolsGovernor.beginModelStep();
3360
3429
  const prefetched = this.prefetchReadOnlyCalls(response.toolCalls);
3361
3430
 
3362
3431
  // 3. ACT (Execute tool calls)
@@ -3900,7 +3969,11 @@ You are operating in a text-and-code modality without direct image pixel renderi
3900
3969
  this.webVerificationState.screenshotTaken = true;
3901
3970
  }
3902
3971
  if (functionName === 'browser_act' && result?.success === true) {
3903
- this.advanceImplementationPlanProgress('verification');
3972
+ const hasExplicitPlanInBatch = Array.isArray(response.toolCalls)
3973
+ && response.toolCalls.some((c: any) => canonicalToolName(c?.function?.name || '') === 'update_plan');
3974
+ if (!hasExplicitPlanInBatch) {
3975
+ this.advanceImplementationPlanProgress('verification');
3976
+ }
3904
3977
  const browserResults = Array.isArray(result.data) ? result.data : [];
3905
3978
  const allRuntimeErrors = browserResults.flatMap((item: any) =>
3906
3979
  Array.isArray(item?.data?.runtimeErrors) ? item.data.runtimeErrors : []
@@ -345,16 +345,30 @@ export function sanitizeSequences(messages) {
345
345
  }
346
346
 
347
347
  let validToolBlock = false;
348
+ let activeToolIds = new Set();
349
+ let positionalRemaining = 0;
348
350
  const clean = [];
349
351
  for (const msg of messages) {
350
352
  if (msg.role === 'assistant' && Array.isArray(msg.tool_calls) && msg.tool_calls.length > 0) {
351
353
  validToolBlock = true;
354
+ activeToolIds = new Set(msg.tool_calls.map(tc => tc && tc.id).filter(Boolean));
355
+ positionalRemaining = activeToolIds.size === 0 ? msg.tool_calls.length : 0;
352
356
  clean.push(msg);
353
357
  } else if (msg.role === 'tool') {
354
- if (validToolBlock) clean.push(msg);
358
+ if (validToolBlock) {
359
+ if (msg.tool_call_id && activeToolIds.has(msg.tool_call_id)) {
360
+ activeToolIds.delete(msg.tool_call_id);
361
+ clean.push(msg);
362
+ } else if (!msg.tool_call_id && positionalRemaining > 0) {
363
+ positionalRemaining--;
364
+ clean.push(msg);
365
+ }
366
+ }
355
367
  // otherwise drop the orphan rather than let the provider 400
356
368
  } else {
357
369
  validToolBlock = false;
370
+ activeToolIds.clear();
371
+ positionalRemaining = 0;
358
372
  clean.push(msg);
359
373
  }
360
374
  }
@@ -83,10 +83,44 @@ export function shortenOversizedToolObservations(messages, options = {}) {
83
83
  }
84
84
  const headLen = Math.min(3000, Math.max(200, Math.floor(threshold * 0.45)));
85
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}`;
86
+ let shortened;
87
+ try {
88
+ const parsed = JSON.parse(original);
89
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
90
+ const record = { ...parsed };
91
+ const rawOut = typeof record.output === 'string' ? record.output
92
+ : typeof record.log === 'string' ? record.log
93
+ : null;
94
+ const fieldKey = typeof record.output === 'string' ? 'output'
95
+ : typeof record.log === 'string' ? 'log'
96
+ : null;
97
+ if (rawOut && fieldKey && rawOut.length > headLen + tailLen) {
98
+ const outHead = rawOut.slice(0, headLen);
99
+ const outTail = rawOut.slice(-tailLen);
100
+ const outOmitted = rawOut.length - outHead.length - outTail.length;
101
+ record[fieldKey] = `${outHead}\n[${outOmitted} middle characters omitted from active context.${buildDecayPointer({ path: spillPath })}]\n${outTail}`;
102
+ shortened = JSON.stringify(record);
103
+ }
104
+ else {
105
+ const head = original.slice(0, headLen);
106
+ const tail = original.slice(-tailLen);
107
+ const omitted = original.length - head.length - tail.length;
108
+ shortened = `${head}\n[${omitted} middle characters omitted from active context.${buildDecayPointer({ path: spillPath })}]\n${tail}`;
109
+ }
110
+ }
111
+ else {
112
+ const head = original.slice(0, headLen);
113
+ const tail = original.slice(-tailLen);
114
+ const omitted = original.length - head.length - tail.length;
115
+ shortened = `${head}\n[${omitted} middle characters omitted from active context.${buildDecayPointer({ path: spillPath })}]\n${tail}`;
116
+ }
117
+ }
118
+ catch {
119
+ const head = original.slice(0, headLen);
120
+ const tail = original.slice(-tailLen);
121
+ const omitted = original.length - head.length - tail.length;
122
+ shortened = `${head}\n[${omitted} middle characters omitted from active context.${buildDecayPointer({ path: spillPath })}]\n${tail}`;
123
+ }
90
124
  if (shortened.length >= original.length)
91
125
  continue;
92
126
  message.content = shortened;
@@ -151,7 +185,11 @@ function verdictFor(content) {
151
185
  }
152
186
  }
153
187
  catch {
154
- // Plain text and provider-specific results have no machine-verifiable verdict.
188
+ const prefixMatch = /^\s*\{\s*"success"\s*:\s*(true|false)\b/.exec(content);
189
+ if (prefixMatch?.[1] === 'true')
190
+ return 'reported success';
191
+ if (prefixMatch?.[1] === 'false')
192
+ return 'reported failure';
155
193
  }
156
194
  return 'outcome unverified';
157
195
  }
@@ -92,10 +92,41 @@ export function shortenOversizedToolObservations(
92
92
  }
93
93
  const headLen = Math.min(3000, Math.max(200, Math.floor(threshold * 0.45)));
94
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}`;
95
+ let shortened: string;
96
+ try {
97
+ const parsed: unknown = JSON.parse(original);
98
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
99
+ const record = { ...(parsed as Record<string, unknown>) };
100
+ const rawOut = typeof record.output === 'string' ? record.output
101
+ : typeof record.log === 'string' ? record.log
102
+ : null;
103
+ const fieldKey = typeof record.output === 'string' ? 'output'
104
+ : typeof record.log === 'string' ? 'log'
105
+ : null;
106
+ if (rawOut && fieldKey && rawOut.length > headLen + tailLen) {
107
+ const outHead = rawOut.slice(0, headLen);
108
+ const outTail = rawOut.slice(-tailLen);
109
+ const outOmitted = rawOut.length - outHead.length - outTail.length;
110
+ record[fieldKey] = `${outHead}\n[${outOmitted} middle characters omitted from active context.${buildDecayPointer({ path: spillPath })}]\n${outTail}`;
111
+ shortened = JSON.stringify(record);
112
+ } else {
113
+ const head = original.slice(0, headLen);
114
+ const tail = original.slice(-tailLen);
115
+ const omitted = original.length - head.length - tail.length;
116
+ shortened = `${head}\n[${omitted} middle characters omitted from active context.${buildDecayPointer({ path: spillPath })}]\n${tail}`;
117
+ }
118
+ } else {
119
+ const head = original.slice(0, headLen);
120
+ const tail = original.slice(-tailLen);
121
+ const omitted = original.length - head.length - tail.length;
122
+ shortened = `${head}\n[${omitted} middle characters omitted from active context.${buildDecayPointer({ path: spillPath })}]\n${tail}`;
123
+ }
124
+ } catch {
125
+ const head = original.slice(0, headLen);
126
+ const tail = original.slice(-tailLen);
127
+ const omitted = original.length - head.length - tail.length;
128
+ shortened = `${head}\n[${omitted} middle characters omitted from active context.${buildDecayPointer({ path: spillPath })}]\n${tail}`;
129
+ }
99
130
  if (shortened.length >= original.length) continue;
100
131
  message.content = shortened;
101
132
  if (spillPath) message.spillPath = spillPath;
@@ -158,7 +189,9 @@ function verdictFor(content: string): string {
158
189
  if (record.success === false) return 'reported failure';
159
190
  }
160
191
  } catch {
161
- // Plain text and provider-specific results have no machine-verifiable verdict.
192
+ const prefixMatch = /^\s*\{\s*"success"\s*:\s*(true|false)\b/.exec(content);
193
+ if (prefixMatch?.[1] === 'true') return 'reported success';
194
+ if (prefixMatch?.[1] === 'false') return 'reported failure';
162
195
  }
163
196
  return 'outcome unverified';
164
197
  }
@@ -139,18 +139,18 @@ export function compileToolObservation(params) {
139
139
  ...(params.nowMs !== undefined ? { createdAtEpochMs: params.nowMs } : {})
140
140
  };
141
141
  }
142
- // 3. Browser / Visual Verification
143
- if (['browser_act', 'screenshot', 'vision_inspect_ui'].includes(lowerTool)) {
142
+ // 3. Browser / Visual / Creative Bridge Verification
143
+ if (['browser_act', 'screenshot', 'vision_inspect_ui', 'creative_apps', 'resolve_act', 'blender_act', 'godot_act'].includes(lowerTool)) {
144
144
  const action = String(args.action ?? 'verify').trim();
145
145
  return {
146
146
  taskId,
147
147
  workspace,
148
148
  type: 'verification',
149
- title: `Verified UI via ${normalizedTool} (${action})`,
149
+ title: `Verified via ${normalizedTool} (${action})`,
150
150
  subtitle: `${normalizedTool} ${action}`,
151
- narrative: `Executed UI/browser verification step using ${normalizedTool} (${action}).`,
152
- facts: [`Verified UI with ${normalizedTool}`],
153
- concepts: ['verification', 'ui'],
151
+ narrative: `Executed verification/bridge step using ${normalizedTool} (${action}).`,
152
+ facts: [`Verified with ${normalizedTool} (${action})`],
153
+ concepts: ['verification', ['creative_apps', 'resolve_act', 'blender_act', 'godot_act'].includes(lowerTool) ? 'creative' : 'ui'],
154
154
  filesRead: relPath ? [relPath] : [],
155
155
  filesModified: [],
156
156
  toolName: normalizedTool,
@@ -211,18 +211,18 @@ export function compileToolObservation(params: {
211
211
  };
212
212
  }
213
213
 
214
- // 3. Browser / Visual Verification
215
- if (['browser_act', 'screenshot', 'vision_inspect_ui'].includes(lowerTool)) {
214
+ // 3. Browser / Visual / Creative Bridge Verification
215
+ if (['browser_act', 'screenshot', 'vision_inspect_ui', 'creative_apps', 'resolve_act', 'blender_act', 'godot_act'].includes(lowerTool)) {
216
216
  const action = String(args.action ?? 'verify').trim();
217
217
  return {
218
218
  taskId,
219
219
  workspace,
220
220
  type: 'verification',
221
- title: `Verified UI via ${normalizedTool} (${action})`,
221
+ title: `Verified via ${normalizedTool} (${action})`,
222
222
  subtitle: `${normalizedTool} ${action}`,
223
- narrative: `Executed UI/browser verification step using ${normalizedTool} (${action}).`,
224
- facts: [`Verified UI with ${normalizedTool}`],
225
- concepts: ['verification', 'ui'],
223
+ narrative: `Executed verification/bridge step using ${normalizedTool} (${action}).`,
224
+ facts: [`Verified with ${normalizedTool} (${action})`],
225
+ concepts: ['verification', ['creative_apps', 'resolve_act', 'blender_act', 'godot_act'].includes(lowerTool) ? 'creative' : 'ui'],
226
226
  filesRead: relPath ? [relPath] : [],
227
227
  filesModified: [],
228
228
  toolName: normalizedTool,
@@ -50,7 +50,11 @@ export class SmartToolsGovernor {
50
50
  mutationAttempted = false;
51
51
  verificationObserved = false;
52
52
  nudgeIssued = false;
53
- get inspectionCapacity() { return Math.max(0, 2 - this.consecutiveInspections); }
53
+ batchLimit;
54
+ constructor(batchLimit = 2) {
55
+ this.batchLimit = Math.max(1, batchLimit);
56
+ }
57
+ get inspectionCapacity() { return Math.max(0, this.batchLimit - this.consecutiveInspections); }
54
58
  beginModelStep() {
55
59
  // A synthesis checkpoint yields to the planner; it does not prohibit
56
60
  // additional evidence on research or long engineering tasks forever.
@@ -63,10 +67,10 @@ export class SmartToolsGovernor {
63
67
  interceptAction(toolName, args) {
64
68
  if (!isInspection(toolName, args) || isVerification(toolName, args))
65
69
  return { allowed: true };
66
- if (this.consecutiveInspections < 2)
70
+ if (this.consecutiveInspections < this.batchLimit)
67
71
  return { allowed: true };
68
72
  this.phase = 'synthesis';
69
- return { allowed: false, reason: 'Inspection batch complete (2 actions). Synthesize the observations before another batch. '
73
+ return { allowed: false, reason: `Inspection batch complete (${this.batchLimit} actions). Synthesize the observations before another batch. `
70
74
  + 'Continue with a targeted edit or verification when evidence is sufficient; further research remains available in the next planning step.' };
71
75
  }
72
76
  reset() {
@@ -104,8 +108,8 @@ export class SmartToolsGovernor {
104
108
  if (!isInspection(toolName, args))
105
109
  return null;
106
110
  this.consecutiveInspections++;
107
- this.phase = this.consecutiveInspections >= 2 ? 'synthesis' : 'inspection';
108
- if (this.consecutiveInspections === 2 && !this.nudgeIssued) {
111
+ this.phase = this.consecutiveInspections >= this.batchLimit ? 'synthesis' : 'inspection';
112
+ if (this.consecutiveInspections === this.batchLimit && !this.nudgeIssued) {
109
113
  this.nudgeIssued = true;
110
114
  return 'Inspection batch complete. Synthesize what is known and choose the next useful step. Continue inspecting if the task still needs evidence; avoid repeating unchanged probes.';
111
115
  }
@@ -61,8 +61,13 @@ export class SmartToolsGovernor {
61
61
  private mutationAttempted = false;
62
62
  private verificationObserved = false;
63
63
  private nudgeIssued = false;
64
+ private readonly batchLimit: number;
64
65
 
65
- get inspectionCapacity(): number { return Math.max(0, 2 - this.consecutiveInspections); }
66
+ constructor(batchLimit = 2) {
67
+ this.batchLimit = Math.max(1, batchLimit);
68
+ }
69
+
70
+ get inspectionCapacity(): number { return Math.max(0, this.batchLimit - this.consecutiveInspections); }
66
71
 
67
72
  beginModelStep(): void {
68
73
  // A synthesis checkpoint yields to the planner; it does not prohibit
@@ -76,9 +81,9 @@ export class SmartToolsGovernor {
76
81
 
77
82
  interceptAction(toolName: string, args: Record<string, unknown>): { allowed: boolean; reason?: string } {
78
83
  if (!isInspection(toolName, args) || isVerification(toolName, args)) return { allowed: true };
79
- if (this.consecutiveInspections < 2) return { allowed: true };
84
+ if (this.consecutiveInspections < this.batchLimit) return { allowed: true };
80
85
  this.phase = 'synthesis';
81
- return { allowed: false, reason: 'Inspection batch complete (2 actions). Synthesize the observations before another batch. '
86
+ return { allowed: false, reason: `Inspection batch complete (${this.batchLimit} actions). Synthesize the observations before another batch. `
82
87
  + 'Continue with a targeted edit or verification when evidence is sufficient; further research remains available in the next planning step.' };
83
88
  }
84
89
 
@@ -118,8 +123,8 @@ export class SmartToolsGovernor {
118
123
  }
119
124
  if (!isInspection(toolName, args)) return null;
120
125
  this.consecutiveInspections++;
121
- this.phase = this.consecutiveInspections >= 2 ? 'synthesis' : 'inspection';
122
- if (this.consecutiveInspections === 2 && !this.nudgeIssued) {
126
+ this.phase = this.consecutiveInspections >= this.batchLimit ? 'synthesis' : 'inspection';
127
+ if (this.consecutiveInspections === this.batchLimit && !this.nudgeIssued) {
123
128
  this.nudgeIssued = true;
124
129
  return 'Inspection batch complete. Synthesize what is known and choose the next useful step. Continue inspecting if the task still needs evidence; avoid repeating unchanged probes.';
125
130
  }
@@ -25,6 +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
29
 
29
30
  // Bound the preview AFTER wrapping, not by source newlines: one 400 KB line of
30
31
  // minified output would otherwise become thousands of rows and lock the
@@ -612,33 +613,35 @@ export class ChatRenderer {
612
613
 
613
614
  // Restore active implementation plan if update_plan was called
614
615
  if (toolName === 'update_plan' && args && Array.isArray(args.plan)) {
615
- this.onAgentPlan({ plan: args.plan });
616
+ this.onAgentPlan({
617
+ plan: args.plan.map(item => ({
618
+ ...item,
619
+ text: item.text || item.step || item.content || ''
620
+ }))
621
+ });
616
622
  }
617
623
 
618
- this.onStepStart({ tool: toolName, args });
619
-
620
- // Look up corresponding tool result
624
+ // Look up corresponding tool result before emitting step start so
625
+ // internal synthesis checkpoints (which never emit steps live) can be skipped.
621
626
  const toolMsg = call.id ? toolResultsById.get(call.id) : null;
622
627
  if (toolMsg) {
623
628
  renderedToolMessages.add(toolMsg);
624
- let result = null;
625
- if (typeof toolMsg.content === 'object' && toolMsg.content !== null) {
626
- result = toolMsg.content;
627
- } else if (typeof toolMsg.content === 'string') {
628
- try {
629
- result = JSON.parse(toolMsg.content);
630
- } catch {
631
- result = {
632
- success: !toolMsg.content.toLowerCase().startsWith('error') && !toolMsg.content.toLowerCase().includes('failed'),
633
- output: toolMsg.content
634
- };
635
- }
636
- } else {
637
- result = { success: true, output: '' };
629
+ const normalized = normalizeHistoricalToolResult(toolName, toolMsg);
630
+ if (normalized.skipStep) {
631
+ continue;
632
+ }
633
+ if (toolName === 'update_plan' && Array.isArray(normalized.plan)) {
634
+ this.onAgentPlan({
635
+ plan: normalized.plan.map(item => ({
636
+ ...item,
637
+ text: item.text || item.step || item.content || ''
638
+ }))
639
+ });
638
640
  }
639
- if (result.success === undefined) result.success = true;
640
- if (toolMsg.spillPath && !result.spillPath) result.spillPath = toolMsg.spillPath;
641
- this.onStepComplete({ result, elapsed: '' });
641
+ this.onStepStart({ tool: toolName, args });
642
+ this.onStepComplete({ tool: toolName, result: normalized.result, elapsed: '' });
643
+ } else {
644
+ this.onStepStart({ tool: toolName, args });
642
645
  }
643
646
  }
644
647
  }
@@ -647,26 +650,13 @@ export class ChatRenderer {
647
650
  if (!renderedToolMessages.has(msg)) {
648
651
  renderedToolMessages.add(msg);
649
652
  const toolName = msg.name || 'tool';
650
- let result = null;
651
- if (typeof msg.content === 'object' && msg.content !== null) {
652
- result = msg.content;
653
- } else if (typeof msg.content === 'string') {
654
- try {
655
- result = JSON.parse(msg.content);
656
- } catch {
657
- result = {
658
- success: !msg.content.toLowerCase().startsWith('error') && !msg.content.toLowerCase().includes('failed'),
659
- output: msg.content
660
- };
661
- }
662
- } else {
663
- result = { success: true, output: '' };
653
+ const normalized = normalizeHistoricalToolResult(toolName, msg, { unpaired: true });
654
+ if (normalized.skipStep) {
655
+ continue;
664
656
  }
665
- if (result.success === undefined) result.success = true;
666
- if (msg.spillPath && !result.spillPath) result.spillPath = msg.spillPath;
667
657
 
668
658
  this.onStepStart({ tool: toolName, args: {} });
669
- this.onStepComplete({ result, elapsed: '' });
659
+ this.onStepComplete({ tool: toolName, result: normalized.result, elapsed: '' });
670
660
  }
671
661
  } else if (role === 'system') {
672
662
  const text = typeof msg.content === 'string' ? msg.content : '';
@@ -864,7 +854,8 @@ export class ChatRenderer {
864
854
  const mark = done ? paint('success', GLYPHS.check)
865
855
  : active ? paint('accent', GLYPHS.arrow)
866
856
  : paint('muted', GLYPHS.dot);
867
- const label = done ? dim(safeDisplay(item.text)) : paint('ink', safeDisplay(item.text));
857
+ const text = item.text || item.step || item.content || '';
858
+ const label = done ? dim(safeDisplay(text)) : paint('ink', safeDisplay(text));
868
859
  this.write(` ${mark} ${truncate(label, width - 5, GLYPHS.ellipsis)}`);
869
860
  }
870
861
  this.write();
@@ -904,7 +895,7 @@ export class ChatRenderer {
904
895
  if (result.success) {
905
896
  const elapsedText = elapsed ? ` ${dim(elapsed)}` : '';
906
897
  this.write(` ${paint('success', GLYPHS.check)}${elapsedText}`);
907
- this.renderOutputPreview(result);
898
+ this.renderOutputPreview(result, msg?.tool || '');
908
899
  return;
909
900
  }
910
901
  const detail = `${safeDisplay(result.error || 'failed')}${elapsed ? ` · ${elapsed}` : ''}`;
@@ -961,10 +952,11 @@ export class ChatRenderer {
961
952
  this.lastOutput = { text: payload, spillPath: result.spillPath || null };
962
953
  }
963
954
 
964
- renderOutputPreview(result) {
965
- const payload = typeof result.output === 'string' ? result.output
955
+ renderOutputPreview(result, toolName = '') {
956
+ const rawPayload = typeof result.output === 'string' ? result.output
966
957
  : typeof result.log === 'string' ? result.log
967
958
  : '';
959
+ const payload = cleanToolOutputPreview(rawPayload, toolName);
968
960
  if (!payload) return;
969
961
 
970
962
  const source = payload.length > PREVIEW_SOURCE_BUDGET
@@ -0,0 +1,208 @@
1
+ import fs from 'node:fs';
2
+ const DECAY_MARKER = '[decayed]';
3
+ const SPILL_HEADER_PREFIX = '=== CAUSYNE TOOL OUTPUT';
4
+ /**
5
+ * Strip internal context-compaction markers, ToolOutputStore spill headers,
6
+ * and middle-omission notices so the TUI only displays real tool output.
7
+ */
8
+ export function cleanToolOutputPreview(payload, toolName = '') {
9
+ if (!payload || typeof payload !== 'string')
10
+ return '';
11
+ if (toolName === 'update_plan')
12
+ return '';
13
+ const trimmed = payload.trim();
14
+ if (!trimmed || trimmed.startsWith(DECAY_MARKER))
15
+ return '';
16
+ let text = payload;
17
+ // Strip renderSpillDocument metadata header up to the first `--- field: ... ---` marker
18
+ if (text.startsWith(SPILL_HEADER_PREFIX)) {
19
+ const fieldHeaderMatch = /\n--- field: [^\n]+ ---\n/.exec(text);
20
+ if (fieldHeaderMatch && fieldHeaderMatch.index !== undefined) {
21
+ text = text.slice(fieldHeaderMatch.index + fieldHeaderMatch[0].length);
22
+ }
23
+ else {
24
+ const blankLineIndex = text.indexOf('\n\n');
25
+ if (blankLineIndex !== -1) {
26
+ text = text.slice(blankLineIndex + 2);
27
+ }
28
+ }
29
+ }
30
+ // Strip internal ToolOutputStore and historyPruner middle-omission lines
31
+ const filteredLines = text
32
+ .split('\n')
33
+ .filter(line => {
34
+ const t = line.trim();
35
+ if (t.startsWith('[... Causyne ToolOutputStore:'))
36
+ return false;
37
+ if (t.startsWith('[... Full log persisted to:'))
38
+ return false;
39
+ if (t.startsWith('[... Read or search a relevant range'))
40
+ return false;
41
+ if (/^\[\d+\s+middle characters omitted from active context/i.test(t))
42
+ return false;
43
+ return true;
44
+ });
45
+ return filteredLines.join('\n').trim();
46
+ }
47
+ function readSpillPreview(spillPath, maxBytes = 4096) {
48
+ if (!spillPath || typeof spillPath !== 'string')
49
+ return '';
50
+ try {
51
+ if (!fs.existsSync(spillPath))
52
+ return '';
53
+ const stat = fs.statSync(spillPath);
54
+ if (!stat.isFile() || stat.size <= 0)
55
+ return '';
56
+ const bytesToRead = Math.min(stat.size, maxBytes);
57
+ const fd = fs.openSync(spillPath, 'r');
58
+ try {
59
+ const buf = Buffer.alloc(bytesToRead);
60
+ const read = fs.readSync(fd, buf, 0, bytesToRead, 0);
61
+ return buf.subarray(0, read).toString('utf8');
62
+ }
63
+ finally {
64
+ fs.closeSync(fd);
65
+ }
66
+ }
67
+ catch {
68
+ return '';
69
+ }
70
+ }
71
+ function extractSpillPathFromDecay(content) {
72
+ const match = /\bat (\/[^\s]+)\s+—\s+read or search\b/.exec(content);
73
+ return match?.[1];
74
+ }
75
+ function recoverBrokenJsonOutput(raw, spillPath) {
76
+ const prefixMatch = /^\s*\{\s*"success"\s*:\s*(true|false)\b/.exec(raw);
77
+ if (!prefixMatch)
78
+ return null;
79
+ const success = prefixMatch[1] === 'true';
80
+ if (spillPath) {
81
+ const fromSpill = readSpillPreview(spillPath);
82
+ if (fromSpill) {
83
+ return { success, output: fromSpill, spillPath };
84
+ }
85
+ }
86
+ const outputMatch = /"output"\s*:\s*"([\s\S]*)/.exec(raw);
87
+ if (outputMatch?.[1]) {
88
+ const body = outputMatch[1]
89
+ .replace(/"\s*\}\s*$/, '')
90
+ .replace(/\\n/g, '\n')
91
+ .replace(/\\"/g, '"')
92
+ .replace(/\\\\/g, '\\');
93
+ return {
94
+ success,
95
+ output: body,
96
+ ...(spillPath ? { spillPath } : {})
97
+ };
98
+ }
99
+ return {
100
+ success,
101
+ output: '',
102
+ ...(spillPath ? { spillPath } : {})
103
+ };
104
+ }
105
+ /**
106
+ * Normalize a historical `role: 'tool'` message for TUI session replay.
107
+ * Suppresses internal `checkpoint: 'synthesis'` governor intercepts (which are
108
+ * never emitted during live execution) and recovers clean output previews for
109
+ * `[decayed]` or shortened tool observations.
110
+ */
111
+ export function normalizeHistoricalToolResult(toolName, toolMsg, options = {}) {
112
+ const explicitSpill = typeof toolMsg.spillPath === 'string' && toolMsg.spillPath.trim()
113
+ ? toolMsg.spillPath.trim()
114
+ : undefined;
115
+ if (typeof toolMsg.content === 'string') {
116
+ const raw = toolMsg.content;
117
+ if (raw.startsWith(DECAY_MARKER)) {
118
+ const spillPath = explicitSpill ?? extractSpillPathFromDecay(raw);
119
+ const isFailure = /^\[decayed\] [^:]+: reported failure\b/i.test(raw);
120
+ const success = !isFailure;
121
+ if (toolName === 'update_plan') {
122
+ return {
123
+ skipStep: Boolean(options.unpaired),
124
+ result: { success: true, output: '' }
125
+ };
126
+ }
127
+ const recoveredRaw = spillPath ? readSpillPreview(spillPath) : '';
128
+ const cleaned = cleanToolOutputPreview(recoveredRaw, toolName);
129
+ return {
130
+ skipStep: false,
131
+ result: {
132
+ success,
133
+ output: cleaned,
134
+ ...(spillPath ? { spillPath } : {})
135
+ }
136
+ };
137
+ }
138
+ let parsed = null;
139
+ try {
140
+ const candidate = JSON.parse(raw);
141
+ if (candidate && typeof candidate === 'object' && !Array.isArray(candidate)) {
142
+ parsed = { ...candidate };
143
+ }
144
+ }
145
+ catch {
146
+ parsed = recoverBrokenJsonOutput(raw, explicitSpill);
147
+ }
148
+ if (parsed) {
149
+ if (parsed.checkpoint === 'synthesis') {
150
+ return { skipStep: true, result: parsed };
151
+ }
152
+ if (parsed.success === undefined) {
153
+ parsed.success = !parsed.error;
154
+ }
155
+ if (explicitSpill && typeof parsed.spillPath !== 'string') {
156
+ parsed.spillPath = explicitSpill;
157
+ }
158
+ if (typeof parsed.output === 'string') {
159
+ parsed.output = cleanToolOutputPreview(parsed.output, toolName);
160
+ }
161
+ if (typeof parsed.log === 'string') {
162
+ parsed.log = cleanToolOutputPreview(parsed.log, toolName);
163
+ }
164
+ const plan = Array.isArray(parsed.plan)
165
+ ? parsed.plan
166
+ : undefined;
167
+ return { skipStep: false, result: parsed, plan };
168
+ }
169
+ const lowered = raw.toLowerCase();
170
+ return {
171
+ skipStep: false,
172
+ result: {
173
+ success: !lowered.startsWith('error') && !lowered.includes('failed'),
174
+ output: cleanToolOutputPreview(raw, toolName),
175
+ ...(explicitSpill ? { spillPath: explicitSpill } : {})
176
+ }
177
+ };
178
+ }
179
+ if (toolMsg.content && typeof toolMsg.content === 'object' && !Array.isArray(toolMsg.content)) {
180
+ const copy = { ...toolMsg.content };
181
+ if (copy.checkpoint === 'synthesis') {
182
+ return { skipStep: true, result: copy };
183
+ }
184
+ if (copy.success === undefined)
185
+ copy.success = !copy.error;
186
+ if (explicitSpill && typeof copy.spillPath !== 'string') {
187
+ copy.spillPath = explicitSpill;
188
+ }
189
+ if (typeof copy.output === 'string') {
190
+ copy.output = cleanToolOutputPreview(copy.output, toolName);
191
+ }
192
+ if (typeof copy.log === 'string') {
193
+ copy.log = cleanToolOutputPreview(copy.log, toolName);
194
+ }
195
+ const plan = Array.isArray(copy.plan)
196
+ ? copy.plan
197
+ : undefined;
198
+ return { skipStep: false, result: copy, plan };
199
+ }
200
+ return {
201
+ skipStep: false,
202
+ result: {
203
+ success: true,
204
+ output: '',
205
+ ...(explicitSpill ? { spillPath: explicitSpill } : {})
206
+ }
207
+ };
208
+ }
@@ -0,0 +1,227 @@
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
+
33
+ // Strip renderSpillDocument metadata header up to the first `--- field: ... ---` marker
34
+ if (text.startsWith(SPILL_HEADER_PREFIX)) {
35
+ const fieldHeaderMatch = /\n--- field: [^\n]+ ---\n/.exec(text);
36
+ if (fieldHeaderMatch && fieldHeaderMatch.index !== undefined) {
37
+ text = text.slice(fieldHeaderMatch.index + fieldHeaderMatch[0].length);
38
+ } else {
39
+ const blankLineIndex = text.indexOf('\n\n');
40
+ if (blankLineIndex !== -1) {
41
+ text = text.slice(blankLineIndex + 2);
42
+ }
43
+ }
44
+ }
45
+
46
+ // Strip internal ToolOutputStore and historyPruner middle-omission lines
47
+ const filteredLines = text
48
+ .split('\n')
49
+ .filter(line => {
50
+ const t = line.trim();
51
+ if (t.startsWith('[... Causyne ToolOutputStore:')) return false;
52
+ if (t.startsWith('[... Full log persisted to:')) return false;
53
+ if (t.startsWith('[... Read or search a relevant range')) return false;
54
+ if (/^\[\d+\s+middle characters omitted from active context/i.test(t)) return false;
55
+ return true;
56
+ });
57
+
58
+ return filteredLines.join('\n').trim();
59
+ }
60
+
61
+ function readSpillPreview(spillPath: string, maxBytes = 4096): string {
62
+ if (!spillPath || typeof spillPath !== 'string') return '';
63
+ try {
64
+ if (!fs.existsSync(spillPath)) return '';
65
+ const stat = fs.statSync(spillPath);
66
+ if (!stat.isFile() || stat.size <= 0) return '';
67
+ const bytesToRead = Math.min(stat.size, maxBytes);
68
+ const fd = fs.openSync(spillPath, 'r');
69
+ try {
70
+ const buf = Buffer.alloc(bytesToRead);
71
+ const read = fs.readSync(fd, buf, 0, bytesToRead, 0);
72
+ return buf.subarray(0, read).toString('utf8');
73
+ } finally {
74
+ fs.closeSync(fd);
75
+ }
76
+ } catch {
77
+ return '';
78
+ }
79
+ }
80
+
81
+ function extractSpillPathFromDecay(content: string): string | undefined {
82
+ const match = /\bat (\/[^\s]+)\s+—\s+read or search\b/.exec(content);
83
+ return match?.[1];
84
+ }
85
+
86
+ function recoverBrokenJsonOutput(raw: string, spillPath?: string | undefined): Record<string, unknown> | null {
87
+ const prefixMatch = /^\s*\{\s*"success"\s*:\s*(true|false)\b/.exec(raw);
88
+ if (!prefixMatch) return null;
89
+ const success = prefixMatch[1] === 'true';
90
+ if (spillPath) {
91
+ const fromSpill = readSpillPreview(spillPath);
92
+ if (fromSpill) {
93
+ return { success, output: fromSpill, spillPath };
94
+ }
95
+ }
96
+ const outputMatch = /"output"\s*:\s*"([\s\S]*)/.exec(raw);
97
+ if (outputMatch?.[1]) {
98
+ const body = outputMatch[1]
99
+ .replace(/"\s*\}\s*$/, '')
100
+ .replace(/\\n/g, '\n')
101
+ .replace(/\\"/g, '"')
102
+ .replace(/\\\\/g, '\\');
103
+ return {
104
+ success,
105
+ output: body,
106
+ ...(spillPath ? { spillPath } : {})
107
+ };
108
+ }
109
+ return {
110
+ success,
111
+ output: '',
112
+ ...(spillPath ? { spillPath } : {})
113
+ };
114
+ }
115
+
116
+ /**
117
+ * Normalize a historical `role: 'tool'` message for TUI session replay.
118
+ * Suppresses internal `checkpoint: 'synthesis'` governor intercepts (which are
119
+ * never emitted during live execution) and recovers clean output previews for
120
+ * `[decayed]` or shortened tool observations.
121
+ */
122
+ export function normalizeHistoricalToolResult(
123
+ toolName: string,
124
+ toolMsg: HistoricalToolMessage,
125
+ options: { unpaired?: boolean | undefined } = {}
126
+ ): NormalizedHistoricalToolResult {
127
+ const explicitSpill = typeof toolMsg.spillPath === 'string' && toolMsg.spillPath.trim()
128
+ ? toolMsg.spillPath.trim()
129
+ : undefined;
130
+
131
+ if (typeof toolMsg.content === 'string') {
132
+ const raw = toolMsg.content;
133
+ if (raw.startsWith(DECAY_MARKER)) {
134
+ const spillPath = explicitSpill ?? extractSpillPathFromDecay(raw);
135
+ const isFailure = /^\[decayed\] [^:]+: reported failure\b/i.test(raw);
136
+ const success = !isFailure;
137
+ if (toolName === 'update_plan') {
138
+ return {
139
+ skipStep: Boolean(options.unpaired),
140
+ result: { success: true, output: '' }
141
+ };
142
+ }
143
+ const recoveredRaw = spillPath ? readSpillPreview(spillPath) : '';
144
+ const cleaned = cleanToolOutputPreview(recoveredRaw, toolName);
145
+ return {
146
+ skipStep: false,
147
+ result: {
148
+ success,
149
+ output: cleaned,
150
+ ...(spillPath ? { spillPath } : {})
151
+ }
152
+ };
153
+ }
154
+
155
+ let parsed: Record<string, unknown> | null = null;
156
+ try {
157
+ const candidate: unknown = JSON.parse(raw);
158
+ if (candidate && typeof candidate === 'object' && !Array.isArray(candidate)) {
159
+ parsed = { ...(candidate as Record<string, unknown>) };
160
+ }
161
+ } catch {
162
+ parsed = recoverBrokenJsonOutput(raw, explicitSpill);
163
+ }
164
+
165
+ if (parsed) {
166
+ if (parsed.checkpoint === 'synthesis') {
167
+ return { skipStep: true, result: parsed };
168
+ }
169
+ if (parsed.success === undefined) {
170
+ parsed.success = !parsed.error;
171
+ }
172
+ if (explicitSpill && typeof parsed.spillPath !== 'string') {
173
+ parsed.spillPath = explicitSpill;
174
+ }
175
+ if (typeof parsed.output === 'string') {
176
+ parsed.output = cleanToolOutputPreview(parsed.output, toolName);
177
+ }
178
+ if (typeof parsed.log === 'string') {
179
+ parsed.log = cleanToolOutputPreview(parsed.log, toolName);
180
+ }
181
+ const plan = Array.isArray(parsed.plan)
182
+ ? (parsed.plan as Array<Record<string, unknown>>)
183
+ : undefined;
184
+ return { skipStep: false, result: parsed, plan };
185
+ }
186
+
187
+ const lowered = raw.toLowerCase();
188
+ return {
189
+ skipStep: false,
190
+ result: {
191
+ success: !lowered.startsWith('error') && !lowered.includes('failed'),
192
+ output: cleanToolOutputPreview(raw, toolName),
193
+ ...(explicitSpill ? { spillPath: explicitSpill } : {})
194
+ }
195
+ };
196
+ }
197
+
198
+ if (toolMsg.content && typeof toolMsg.content === 'object' && !Array.isArray(toolMsg.content)) {
199
+ const copy: Record<string, unknown> = { ...(toolMsg.content as Record<string, unknown>) };
200
+ if (copy.checkpoint === 'synthesis') {
201
+ return { skipStep: true, result: copy };
202
+ }
203
+ if (copy.success === undefined) copy.success = !copy.error;
204
+ if (explicitSpill && typeof copy.spillPath !== 'string') {
205
+ copy.spillPath = explicitSpill;
206
+ }
207
+ if (typeof copy.output === 'string') {
208
+ copy.output = cleanToolOutputPreview(copy.output, toolName);
209
+ }
210
+ if (typeof copy.log === 'string') {
211
+ copy.log = cleanToolOutputPreview(copy.log, toolName);
212
+ }
213
+ const plan = Array.isArray(copy.plan)
214
+ ? (copy.plan as Array<Record<string, unknown>>)
215
+ : undefined;
216
+ return { skipStep: false, result: copy, plan };
217
+ }
218
+
219
+ return {
220
+ skipStep: false,
221
+ result: {
222
+ success: true,
223
+ output: '',
224
+ ...(explicitSpill ? { spillPath: explicitSpill } : {})
225
+ }
226
+ };
227
+ }