@causyne/agent 1.20.35 → 1.20.38

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -9,7 +9,7 @@ Parameters
9
9
 
10
10
  Licensor: Ikbal Fadilah
11
11
 
12
- Licensed Work: Causyne Agent 1.20.35
12
+ Licensed Work: Causyne Agent 1.20.38
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.35",
3
+ "version": "1.20.38",
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) }))
@@ -3199,6 +3259,10 @@ You are operating in a text-and-code modality without direct image pixel renderi
3199
3259
  // makes, so a denied path is never read behind the guard's back.
3200
3260
  // * Only a SUCCESSFUL prefetch is consumed. A failure is discarded and
3201
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();
3202
3266
  const prefetched = this.prefetchReadOnlyCalls(response.toolCalls);
3203
3267
  // 3. ACT (Execute tool calls)
3204
3268
  for (const toolCall of response.toolCalls) {
@@ -3697,7 +3761,11 @@ You are operating in a text-and-code modality without direct image pixel renderi
3697
3761
  this.webVerificationState.screenshotTaken = true;
3698
3762
  }
3699
3763
  if (functionName === 'browser_act' && result?.success === true) {
3700
- 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
+ }
3701
3769
  const browserResults = Array.isArray(result.data) ? result.data : [];
3702
3770
  const allRuntimeErrors = browserResults.flatMap((item) => Array.isArray(item?.data?.runtimeErrors) ? item.data.runtimeErrors : []);
3703
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) }))
@@ -3370,6 +3422,10 @@ You are operating in a text-and-code modality without direct image pixel renderi
3370
3422
  // makes, so a denied path is never read behind the guard's back.
3371
3423
  // * Only a SUCCESSFUL prefetch is consumed. A failure is discarded and
3372
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();
3373
3429
  const prefetched = this.prefetchReadOnlyCalls(response.toolCalls);
3374
3430
 
3375
3431
  // 3. ACT (Execute tool calls)
@@ -3913,7 +3969,11 @@ You are operating in a text-and-code modality without direct image pixel renderi
3913
3969
  this.webVerificationState.screenshotTaken = true;
3914
3970
  }
3915
3971
  if (functionName === 'browser_act' && result?.success === true) {
3916
- 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
+ }
3917
3977
  const browserResults = Array.isArray(result.data) ? result.data : [];
3918
3978
  const allRuntimeErrors = browserResults.flatMap((item: any) =>
3919
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
  }
@@ -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
  }
@@ -29,9 +29,11 @@ export function stripAnsi(str) {
29
29
  * transient progress meters (curl, wget) so agent history and split-panes never glitch.
30
30
  */
31
31
  export function cleanSubprocessOutput(str) {
32
- const normalized = stripAnsi(str)
32
+ const preSplit = str.replace(/\x1b\[(?:[12]K|\d*G)/g, '\n');
33
+ const normalized = stripAnsi(preSplit)
33
34
  .replace(/\r\n/g, '\n')
34
- .replace(/\r/g, '\n');
35
+ .replace(/\r/g, '\n')
36
+ .replace(/(https?:\/\/[^\s"'<>]+?\.[a-z]{2,10})([A-Z][a-z]{2,15}:\s)/g, '$1\n$2');
35
37
  return normalized
36
38
  .split('\n')
37
39
  .filter(line => !/^\s*(?:%\s+Total\b|Dload\s+Upload\b|\d+\s+\d+(?:\.[0-9kKmM]+)?\s+\d+\s+.*--:--:--)/i.test(line))
@@ -314,15 +316,29 @@ export const sysRun = {
314
316
  }
315
317
  }
316
318
  };
317
- const appendToBuffer = (data) => {
318
- outputBuffer += data.toString();
319
+ let lastStream = null;
320
+ const appendToBuffer = (stream, data) => {
321
+ const chunk = data.toString();
322
+ if (!chunk)
323
+ return;
324
+ if (lastStream !== null &&
325
+ lastStream !== stream &&
326
+ outputBuffer.length > 0 &&
327
+ !outputBuffer.endsWith('\n') &&
328
+ !outputBuffer.endsWith('\r') &&
329
+ !chunk.startsWith('\n') &&
330
+ !chunk.startsWith('\r')) {
331
+ outputBuffer += '\n';
332
+ }
333
+ lastStream = stream;
334
+ outputBuffer += chunk;
319
335
  if (outputBuffer.length > MAX_LENGTH) {
320
336
  outputBuffer = '...[OUTPUT TRUNCATED]...\n' + outputBuffer.slice(outputBuffer.length - MAX_LENGTH);
321
337
  }
322
338
  checkServerDetach();
323
339
  };
324
- child.stdout?.on('data', appendToBuffer);
325
- child.stderr?.on('data', appendToBuffer);
340
+ child.stdout?.on('data', (d) => appendToBuffer('stdout', d));
341
+ child.stderr?.on('data', (d) => appendToBuffer('stderr', d));
326
342
  let serverGraceTimer;
327
343
  if (isPersistentServerCommand(rawCommand)) {
328
344
  serverGraceTimer = setTimeout(() => {
@@ -69,9 +69,11 @@ export function stripAnsi(str: string): string {
69
69
  * transient progress meters (curl, wget) so agent history and split-panes never glitch.
70
70
  */
71
71
  export function cleanSubprocessOutput(str: string): string {
72
- const normalized = stripAnsi(str)
72
+ const preSplit = str.replace(/\x1b\[(?:[12]K|\d*G)/g, '\n');
73
+ const normalized = stripAnsi(preSplit)
73
74
  .replace(/\r\n/g, '\n')
74
- .replace(/\r/g, '\n');
75
+ .replace(/\r/g, '\n')
76
+ .replace(/(https?:\/\/[^\s"'<>]+?\.[a-z]{2,10})([A-Z][a-z]{2,15}:\s)/g, '$1\n$2');
75
77
 
76
78
  return normalized
77
79
  .split('\n')
@@ -389,16 +391,31 @@ export const sysRun = {
389
391
  }
390
392
  };
391
393
 
392
- const appendToBuffer = (data: Buffer | string): void => {
393
- outputBuffer += data.toString();
394
+ let lastStream: 'stdout' | 'stderr' | null = null;
395
+ const appendToBuffer = (stream: 'stdout' | 'stderr', data: Buffer | string): void => {
396
+ const chunk = data.toString();
397
+ if (!chunk) return;
398
+ if (
399
+ lastStream !== null &&
400
+ lastStream !== stream &&
401
+ outputBuffer.length > 0 &&
402
+ !outputBuffer.endsWith('\n') &&
403
+ !outputBuffer.endsWith('\r') &&
404
+ !chunk.startsWith('\n') &&
405
+ !chunk.startsWith('\r')
406
+ ) {
407
+ outputBuffer += '\n';
408
+ }
409
+ lastStream = stream;
410
+ outputBuffer += chunk;
394
411
  if (outputBuffer.length > MAX_LENGTH) {
395
412
  outputBuffer = '...[OUTPUT TRUNCATED]...\n' + outputBuffer.slice(outputBuffer.length - MAX_LENGTH);
396
413
  }
397
414
  checkServerDetach();
398
415
  };
399
416
 
400
- child.stdout?.on('data', appendToBuffer);
401
- child.stderr?.on('data', appendToBuffer);
417
+ child.stdout?.on('data', (d: Buffer | string) => appendToBuffer('stdout', d));
418
+ child.stderr?.on('data', (d: Buffer | string) => appendToBuffer('stderr', d));
402
419
 
403
420
  let serverGraceTimer: NodeJS.Timeout | undefined;
404
421
  if (isPersistentServerCommand(rawCommand)) {