@causyne/agent 1.20.12 → 1.20.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/LICENSE +1 -1
  2. package/package.json +1 -1
  3. package/src/SmartTools.js +33 -0
  4. package/src/SmartTools.ts +37 -0
  5. package/src/acp/client.js +157 -4
  6. package/src/acp/client.ts +152 -5
  7. package/src/agentLoop.js +857 -178
  8. package/src/agentLoop.ts +865 -183
  9. package/src/browser/browserRuntime.js +8 -1
  10. package/src/browser/browserRuntime.ts +8 -1
  11. package/src/browser/causyneBrowser.js +20 -4
  12. package/src/browser/causyneBrowser.ts +20 -4
  13. package/src/browser/urlPolicy.js +35 -0
  14. package/src/browser/urlPolicy.ts +34 -0
  15. package/src/cliMode.js +6 -2
  16. package/src/commands.js +14 -0
  17. package/src/contextManager.d.ts +1 -0
  18. package/src/core/contextCompactor.js +277 -0
  19. package/src/core/contextCompactor.ts +353 -0
  20. package/src/decideTools.js +157 -0
  21. package/src/decideTools.ts +195 -0
  22. package/src/decisionPolicy.js +5 -3
  23. package/src/decisionPolicy.ts +5 -3
  24. package/src/implementationPlan.js +284 -0
  25. package/src/implementationPlan.ts +275 -0
  26. package/src/observer/coldObserver.js +10 -4
  27. package/src/observer/coldObserver.ts +15 -7
  28. package/src/observer/evidence.js +11 -5
  29. package/src/observer/evidence.ts +13 -6
  30. package/src/observer.js +196 -0
  31. package/src/observer.ts +287 -0
  32. package/src/providers/acp.js +362 -109
  33. package/src/providers/acp.ts +359 -111
  34. package/src/providers/antigravity.js +133 -105
  35. package/src/providers/antigravity.ts +130 -109
  36. package/src/providers/base.d.ts +3 -0
  37. package/src/providers/budgetEnforcer.js +13 -0
  38. package/src/providers/budgetEnforcer.ts +13 -3
  39. package/src/provisioning/capabilityProvisioner.js +14 -10
  40. package/src/sandbox.js +4 -2
  41. package/src/saveTools.js +146 -0
  42. package/src/saveTools.ts +169 -0
  43. package/src/session/cachePressure.js +77 -0
  44. package/src/session/cachePressure.ts +122 -0
  45. package/src/smartToolsUse.js +69 -12
  46. package/src/smartToolsUse.ts +103 -12
  47. package/src/taskShape.js +7 -7
  48. package/src/taskShape.ts +7 -7
  49. package/src/timeMachine.js +55 -20
  50. package/src/timeMachine.ts +64 -20
  51. package/src/toolPacks.js +217 -310
  52. package/src/toolPacks.ts +505 -0
  53. package/src/tools/deferredMcpSearch.js +21 -13
  54. package/src/tools/deferredMcpSearch.ts +23 -15
  55. package/src/tools/updatePlan.js +2 -2
  56. package/src/tools/updatePlan.ts +2 -2
  57. package/src/toolsList.js +203 -0
  58. package/src/toolsList.ts +224 -0
  59. package/src/tui/chatRenderer.js +49 -14
  60. package/src/tui/codeStreamRenderer.js +16 -5
  61. package/src/tui/codeStreamRenderer.ts +14 -4
  62. package/src/tui/prompt.js +4 -2
  63. package/src/tui/sessionSidebar.js +10 -2
  64. package/src/tui/sessionSidebar.ts +10 -3
  65. package/src/tui/stageSurface.js +27 -1
  66. package/src/tui/text.d.ts +1 -0
  67. package/src/tui/turnRail.js +274 -0
  68. package/src/tui/turnRail.ts +334 -0
  69. package/src/types/contracts.ts +103 -0
  70. package/src/verificationPlan.js +141 -0
  71. package/src/verificationPlan.ts +166 -0
  72. package/src/toolPacks.d.ts +0 -10
@@ -1,11 +1,13 @@
1
1
  import { formatToolContracts, toolContractUpdate, contractFingerprint } from './toolContracts.js';
2
- import { noncachedTokens } from './budgetEnforcer.js';
2
+ import { noncachedTokens, turnTokenLimitFor } from './budgetEnforcer.js';
3
+ import { determineToolScope } from '../smartToolsUse.js';
3
4
  import { PEER_COLLABORATION_POLICY } from './collaborationPolicy.js';
4
5
  import { spawn } from 'node:child_process';
5
6
  import fs from 'node:fs';
6
7
  import path from 'node:path';
7
8
  import { isLaunchOnlyPrompt } from '../launchIntent.js';
8
9
  import { LLMProvider } from './base.js';
10
+ import { extractToolCallJsonObjects, stripToolCallMarkup, stripThinkBlocks } from '../implementationPlan.js';
9
11
  /**
10
12
  * Baseline fallback models for instant offline availability.
11
13
  * Live models are autodetected dynamically from `agy models`
@@ -761,81 +763,29 @@ export class AntigravityProvider extends LLMProvider {
761
763
  const calls = [];
762
764
  if (!text || typeof text !== 'string')
763
765
  return calls;
764
- const regex = /<tool_call>([\s\S]*?)<\/tool_call>/g;
765
- let match;
766
766
  let index = 0;
767
- while ((match = regex.exec(text)) !== null) {
768
- try {
769
- const raw = match[1]?.trim() || '';
770
- const parsed = JSON.parse(raw);
771
- const name = parsed.name || parsed.tool || parsed.function?.name;
772
- if (name) {
773
- const rawArgs = parsed.arguments !== undefined ? parsed.arguments : (parsed.parameters !== undefined ? parsed.parameters : (parsed.input !== undefined ? parsed.input : (parsed.function?.arguments || {})));
774
- calls.push({
775
- id: `agy_call_${Date.now()}_${index++}`,
776
- type: 'function',
777
- function: {
778
- name,
779
- arguments: typeof rawArgs === 'string' ? rawArgs : JSON.stringify(rawArgs || {})
780
- }
781
- });
782
- }
783
- }
784
- catch {
785
- // ignore malformed tool_call blocks
786
- }
787
- }
788
- if (calls.length === 0) {
789
- const fenceRegex = /```(?:tool_call|json)?\s*(\{[\s\S]*?"name"\s*:\s*[\s\S]*?\})\s*```/g;
790
- while ((match = fenceRegex.exec(text)) !== null) {
791
- try {
792
- const raw = match[1]?.trim() || '';
793
- const parsed = JSON.parse(raw);
794
- const name = parsed.name || parsed.tool || parsed.function?.name;
795
- if (name) {
796
- const rawArgs = parsed.arguments !== undefined ? parsed.arguments : (parsed.parameters !== undefined ? parsed.parameters : (parsed.input !== undefined ? parsed.input : (parsed.function?.arguments || {})));
797
- calls.push({
798
- id: `agy_call_${Date.now()}_${index++}`,
799
- type: 'function',
800
- function: {
801
- name,
802
- arguments: typeof rawArgs === 'string' ? rawArgs : JSON.stringify(rawArgs || {})
803
- }
804
- });
805
- }
806
- }
807
- catch {
808
- // ignore
809
- }
810
- }
811
- }
812
- // Unclosed tool_call recovery (when model generated large file content and closed turn)
813
- if (calls.length === 0) {
814
- const openIndex = text.lastIndexOf('<tool_call>');
815
- if (openIndex !== -1 && text.indexOf('</tool_call>', openIndex) === -1) {
816
- const partial = text.slice(openIndex + '<tool_call>'.length).trim();
817
- for (const suffix of ['', '}', '}}', '}}}', '"}', '"}}', '"}}}', '"}]}}', '"]}}', '"]}}}']) {
818
- try {
819
- const parsed = JSON.parse(partial + suffix);
820
- const name = parsed.name || parsed.tool || parsed.function?.name;
821
- if (name) {
822
- const rawArgs = parsed.arguments !== undefined ? parsed.arguments : (parsed.parameters !== undefined ? parsed.parameters : (parsed.input !== undefined ? parsed.input : (parsed.function?.arguments || {})));
823
- calls.push({
824
- id: `agy_call_${Date.now()}_0`,
825
- type: 'function',
826
- function: {
827
- name,
828
- arguments: typeof rawArgs === 'string' ? rawArgs : JSON.stringify(rawArgs || {})
829
- }
830
- });
831
- break;
832
- }
833
- }
834
- catch {
835
- // try next candidate
836
- }
767
+ for (const parsed of extractToolCallJsonObjects(text)) {
768
+ const fnObj = parsed.function && typeof parsed.function === 'object'
769
+ ? parsed.function
770
+ : null;
771
+ const name = String(parsed.name || parsed.tool || fnObj?.name || '').trim();
772
+ if (!name)
773
+ continue;
774
+ const rawArgs = parsed.arguments !== undefined
775
+ ? parsed.arguments
776
+ : parsed.parameters !== undefined
777
+ ? parsed.parameters
778
+ : parsed.input !== undefined
779
+ ? parsed.input
780
+ : (fnObj?.arguments ?? {});
781
+ calls.push({
782
+ id: `agy_call_${Date.now()}_${index++}`,
783
+ type: 'function',
784
+ function: {
785
+ name,
786
+ arguments: typeof rawArgs === 'string' ? rawArgs : JSON.stringify(rawArgs || {})
837
787
  }
838
- }
788
+ });
839
789
  }
840
790
  return calls;
841
791
  }
@@ -910,6 +860,15 @@ export class AntigravityProvider extends LLMProvider {
910
860
  'If a command is denied or the readback does not confirm the change, report the blocker honestly. ' +
911
861
  'Keep native tool actions within 12; use Causyne tool calls when a native action is blocked.\n\n' + promptText;
912
862
  }
863
+ const taskArchetype = options.taskArchetype || determineToolScope(latestPrompt).archetype;
864
+ const webOrGameTask = taskArchetype === 'web_engineering' || taskArchetype === 'game_development';
865
+ if (webOrGameTask) {
866
+ promptText = '[Web & Interactive Verification Directive]\n' +
867
+ 'Causyne provides native host tools for browser verification: `browser_act` (preview and snapshot) and `screenshot`/`vision_inspect_ui`. ' +
868
+ 'DO NOT write custom Node.js/Python headless Chrome or CDP WebSocket scripts to inspect console logs or take screenshots. ' +
869
+ 'Causyne automatically captures browser console errors and renders WebGL/Canvas with hardware acceleration. ' +
870
+ 'Use <tool_call>{"name": "browser_act", "arguments": {"action": "preview", "filePath": "index.html"}}</tool_call> to verify rendered output directly.\n\n' + promptText;
871
+ }
913
872
  const modelSlug = resolveAgyModelId(this.model);
914
873
  const effort = resolveAgyEffort(this.model);
915
874
  // Run the user's normal peer in the selected project. Do not substitute a
@@ -946,6 +905,7 @@ export class AntigravityProvider extends LLMProvider {
946
905
  let sawToolAfterLastText = false;
947
906
  let sawProviderProgress = false;
948
907
  let reasoningChars = 0;
908
+ let inInlineThinkBlock = false;
949
909
  let usageBaselineCommitted = false;
950
910
  const nativeActions = [];
951
911
  const attemptedNativeTools = [];
@@ -985,11 +945,12 @@ export class AntigravityProvider extends LLMProvider {
985
945
  const hasExplicitLimit = (Number.isFinite(remainingTaskBudget) && remainingTaskBudget > 0)
986
946
  || (Number.isFinite(rawTokenLimit) && rawTokenLimit > 0);
987
947
  const countReportedTotal = options.tokenBudgetBasis !== 'noncached';
948
+ const defaultTokenLimit = turnTokenLimitFor(taskArchetype);
988
949
  const tokenLimit = Number.isFinite(remainingTaskBudget) && remainingTaskBudget > 0
989
950
  ? remainingTaskBudget
990
951
  : (Number.isFinite(rawTokenLimit) && rawTokenLimit > 0
991
952
  ? rawTokenLimit
992
- : 100_000);
953
+ : defaultTokenLimit);
993
954
  const wallTimer = desktopTask ? setTimeout(() => {
994
955
  const error = new Error('Antigravity exceeded the 180-second desktop task limit. Outcome is unverified.');
995
956
  error.code = 'AGY_DESKTOP_TASK_LIMIT';
@@ -1108,15 +1069,28 @@ export class AntigravityProvider extends LLMProvider {
1108
1069
  const spentAgainstLimit = countReportedTotal ? reportedTotal : uncachedTotal;
1109
1070
  if (Number.isFinite(tokenLimit) && tokenLimit > 0
1110
1071
  && spentAgainstLimit >= tokenLimit) {
1111
- const error = Object.assign(new Error(`Antigravity reported ${spentAgainstLimit} tokens against a ${tokenLimit}-token per-call ceiling. This turn stopped and its outcome is unverified.`), { code: 'AGY_TOKEN_BUDGET', tokenLimit, partialUsage: { ...partialUsage } });
1112
- safeReject(error);
1113
- terminateChild();
1114
- return;
1072
+ if (options.hardBudget === false) {
1073
+ if (process.env.CAUSYNE_DEBUG === '1') {
1074
+ console.log(`[BUDGET] Turn spent ${spentAgainstLimit} tokens against soft checkpoint ${tokenLimit}. Continuing execution.`);
1075
+ }
1076
+ }
1077
+ else {
1078
+ const error = Object.assign(new Error(`Antigravity reported ${spentAgainstLimit} tokens against a ${tokenLimit}-token per-call ceiling. This turn stopped and its outcome is unverified.`), { code: 'AGY_TOKEN_BUDGET', tokenLimit, partialUsage: { ...partialUsage } });
1079
+ safeReject(error);
1080
+ terminateChild();
1081
+ return;
1082
+ }
1115
1083
  }
1116
1084
  }
1117
1085
  }
1118
- const delta = stepUpdate?.text_delta;
1119
- const stepType = stepUpdate?.step_type;
1086
+ const delta = stepUpdate?.text_delta
1087
+ ?? stepUpdate?.delta
1088
+ ?? stepUpdate?.thought_delta
1089
+ ?? stepUpdate?.thought
1090
+ ?? (typeof stepUpdate?.content === 'string' ? stepUpdate.content : undefined)
1091
+ ?? event?.text_delta
1092
+ ?? event?.delta;
1093
+ const stepType = stepUpdate?.step_type || event?.step_type || event?.type;
1120
1094
  if (stepType === 'tool') {
1121
1095
  const state = stepUpdate?.state;
1122
1096
  const stepIndex = Number(stepUpdate?.step_index ?? event?.step_index);
@@ -1204,36 +1178,79 @@ export class AntigravityProvider extends LLMProvider {
1204
1178
  else
1205
1179
  nativeActions.push(action);
1206
1180
  }
1207
- // Stream the start; completion is reported only after the
1208
- // final result has checked for denied actions.
1209
- if (status === 'running' && typeof options.onNativeAction === 'function') {
1181
+ // Stream the action lifecycle immediately (running, completed, failed)
1182
+ // so the caller receives real-time progress and does not appear frozen.
1183
+ if (typeof options.onNativeAction === 'function') {
1210
1184
  const parameters = rawParams && typeof rawParams === 'object'
1211
1185
  ? rawParams
1212
1186
  : {};
1213
- options.onNativeAction({ ...action, parameters });
1187
+ options.onNativeAction({ ...action, status, parameters });
1214
1188
  }
1215
1189
  }
1216
1190
  }
1191
+ const isExplicitThought = stepType === 'thought'
1192
+ || stepType === 'agent_thought'
1193
+ || stepType === 'thinking'
1194
+ || stepType === 'reasoning'
1195
+ || stepType === 'agent_reasoning'
1196
+ || Boolean(stepUpdate?.thought_delta || stepUpdate?.thought);
1217
1197
  if (delta && typeof delta === 'string') {
1218
- if (stepType === 'thought' || stepType === 'agent_thought') {
1198
+ if (isExplicitThought) {
1219
1199
  reasoningChars += delta.length;
1220
1200
  if (typeof options.onReasoningChunk === 'function') {
1221
1201
  options.onReasoningChunk(delta);
1222
1202
  }
1223
1203
  }
1224
1204
  else {
1225
- if (sawToolAfterLastText && streamedResponse.length > 0 && !/\s$/.test(streamedResponse) && !/^\s/.test(delta)) {
1226
- streamedResponse += '\n';
1227
- if (typeof options.onChunk === 'function') {
1228
- options.onChunk('\n');
1205
+ // Progressive inline think block filtering (<think>...</think>, <thought>...</thought>, etc.)
1206
+ let remaining = delta;
1207
+ while (remaining.length > 0) {
1208
+ if (inInlineThinkBlock) {
1209
+ const closeMatch = remaining.match(/<\/(?:think|thought|reasoning|thinking|REASONING_SCRATCHPAD)>/i);
1210
+ if (closeMatch && closeMatch.index !== undefined) {
1211
+ const thinkPart = remaining.slice(0, closeMatch.index);
1212
+ if (thinkPart) {
1213
+ reasoningChars += thinkPart.length;
1214
+ options.onReasoningChunk?.(thinkPart);
1215
+ }
1216
+ inInlineThinkBlock = false;
1217
+ remaining = remaining.slice(closeMatch.index + closeMatch[0].length);
1218
+ }
1219
+ else {
1220
+ reasoningChars += remaining.length;
1221
+ options.onReasoningChunk?.(remaining);
1222
+ remaining = '';
1223
+ }
1224
+ }
1225
+ else {
1226
+ const openMatch = remaining.match(/<(?:think|thought|reasoning|thinking|REASONING_SCRATCHPAD)>/i);
1227
+ if (openMatch && openMatch.index !== undefined) {
1228
+ const textPart = remaining.slice(0, openMatch.index);
1229
+ if (textPart) {
1230
+ if (sawToolAfterLastText && streamedResponse.length > 0 && !/\s$/.test(streamedResponse) && !/^\s/.test(textPart)) {
1231
+ streamedResponse += '\n';
1232
+ options.onChunk?.('\n');
1233
+ }
1234
+ if (textPart.trim().length > 0)
1235
+ sawToolAfterLastText = false;
1236
+ streamedResponse += textPart;
1237
+ options.onChunk?.(textPart);
1238
+ }
1239
+ inInlineThinkBlock = true;
1240
+ remaining = remaining.slice(openMatch.index + openMatch[0].length);
1241
+ }
1242
+ else {
1243
+ if (sawToolAfterLastText && streamedResponse.length > 0 && !/\s$/.test(streamedResponse) && !/^\s/.test(remaining)) {
1244
+ streamedResponse += '\n';
1245
+ options.onChunk?.('\n');
1246
+ }
1247
+ if (remaining.trim().length > 0)
1248
+ sawToolAfterLastText = false;
1249
+ streamedResponse += remaining;
1250
+ options.onChunk?.(remaining);
1251
+ remaining = '';
1252
+ }
1229
1253
  }
1230
- }
1231
- if (delta.trim().length > 0) {
1232
- sawToolAfterLastText = false;
1233
- }
1234
- streamedResponse += delta;
1235
- if (typeof options.onChunk === 'function') {
1236
- options.onChunk(delta);
1237
1254
  }
1238
1255
  }
1239
1256
  }
@@ -1309,20 +1326,24 @@ export class AntigravityProvider extends LLMProvider {
1309
1326
  rawContent = rawContent.replace(/<(?:thought|thinking)>[\s\S]*?<\/(?:thought|thinking)>/gi, '').trim();
1310
1327
  }
1311
1328
  const toolCalls = this.extractToolCalls(rawContent);
1312
- // Strip tool call tags from prose so raw XML does not leak into chat display
1313
- let content = rawContent.replace(/<tool_call>[\s\S]*?<\/tool_call>/g, '').trim();
1329
+ // Strip tool call tags and think tags from prose so raw XML/DSML/think does not leak into chat display
1330
+ let content = stripThinkBlocks(stripToolCallMarkup(rawContent));
1314
1331
  const deniedActions = Array.isArray(finalResultObj?.denied_actions)
1315
1332
  ? finalResultObj.denied_actions : [];
1316
1333
  const normalizeAction = (value) => String(value || '').toLowerCase().replace(/[^a-z0-9]/g, '');
1317
1334
  const deniedNames = new Set(deniedActions.flatMap(action => [normalizeAction(action?.action), normalizeAction(action?.display_name)]).filter(Boolean));
1318
1335
  for (const action of nativeActions) {
1319
- if (deniedNames.has(normalizeAction(action.name)))
1336
+ const wasDenied = deniedNames.has(normalizeAction(action.name));
1337
+ if (wasDenied)
1338
+ action.status = 'failed';
1339
+ else if (action.status === 'running')
1320
1340
  action.status = 'failed';
1321
- if (typeof options.onNativeAction === 'function') {
1341
+ // Only re-emit on terminal close if the action was denied or left unfinished
1342
+ if (wasDenied && typeof options.onNativeAction === 'function') {
1322
1343
  const attempt = [...attemptedNativeTools].reverse().find(candidate => action.id
1323
1344
  ? candidate.id === action.id
1324
1345
  : normalizeAction(candidate.name) === normalizeAction(action.name) && candidate.detail === action.detail);
1325
- options.onNativeAction({ ...action, parameters: attempt?.parameters || {} });
1346
+ options.onNativeAction({ ...action, status: 'failed', parameters: attempt?.parameters || {} });
1326
1347
  }
1327
1348
  }
1328
1349
  if (deniedActions.length > 0) {
@@ -1442,9 +1463,16 @@ export class AntigravityProvider extends LLMProvider {
1442
1463
  const uncachedTotal = noncachedTokens(response.usage);
1443
1464
  const spentAgainstLimit = countReportedTotal ? reportedTotal : uncachedTotal;
1444
1465
  if (spentAgainstLimit >= tokenLimit) {
1445
- Object.assign(partialUsage, response.usage);
1446
- safeReject(Object.assign(new Error(`Antigravity reached its ${tokenLimit}-token checkpoint. Work remains unverified.`), { code: 'AGY_TOKEN_BUDGET', tokenLimit, partialUsage: { ...partialUsage } }));
1447
- return;
1466
+ if (options.hardBudget === false) {
1467
+ if (process.env.CAUSYNE_DEBUG === '1') {
1468
+ console.log(`[BUDGET] Turn finished with ${spentAgainstLimit} tokens against soft checkpoint ${tokenLimit}. Preserving result.`);
1469
+ }
1470
+ }
1471
+ else {
1472
+ Object.assign(partialUsage, response.usage);
1473
+ safeReject(Object.assign(new Error(`Antigravity reached its ${tokenLimit}-token checkpoint. Work remains unverified.`), { code: 'AGY_TOKEN_BUDGET', tokenLimit, partialUsage: { ...partialUsage } }));
1474
+ return;
1475
+ }
1448
1476
  }
1449
1477
  safeResolve(response);
1450
1478
  });