@causyne/agent 1.20.13 → 1.20.15

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 (71) hide show
  1. package/package.json +1 -1
  2. package/src/SmartTools.js +33 -0
  3. package/src/SmartTools.ts +37 -0
  4. package/src/acp/client.js +157 -4
  5. package/src/acp/client.ts +152 -5
  6. package/src/agentLoop.js +857 -178
  7. package/src/agentLoop.ts +865 -183
  8. package/src/browser/browserRuntime.js +8 -1
  9. package/src/browser/browserRuntime.ts +8 -1
  10. package/src/browser/causyneBrowser.js +20 -4
  11. package/src/browser/causyneBrowser.ts +20 -4
  12. package/src/browser/urlPolicy.js +35 -0
  13. package/src/browser/urlPolicy.ts +34 -0
  14. package/src/cliMode.js +6 -2
  15. package/src/commands.js +14 -0
  16. package/src/contextManager.d.ts +1 -0
  17. package/src/core/contextCompactor.js +277 -0
  18. package/src/core/contextCompactor.ts +353 -0
  19. package/src/decideTools.js +157 -0
  20. package/src/decideTools.ts +195 -0
  21. package/src/decisionPolicy.js +5 -3
  22. package/src/decisionPolicy.ts +5 -3
  23. package/src/implementationPlan.js +284 -0
  24. package/src/implementationPlan.ts +275 -0
  25. package/src/observer/coldObserver.js +10 -4
  26. package/src/observer/coldObserver.ts +15 -7
  27. package/src/observer/evidence.js +11 -5
  28. package/src/observer/evidence.ts +13 -6
  29. package/src/observer.js +196 -0
  30. package/src/observer.ts +287 -0
  31. package/src/providers/acp.js +362 -109
  32. package/src/providers/acp.ts +359 -111
  33. package/src/providers/antigravity.js +133 -105
  34. package/src/providers/antigravity.ts +130 -109
  35. package/src/providers/base.d.ts +3 -0
  36. package/src/providers/budgetEnforcer.js +23 -2
  37. package/src/providers/budgetEnforcer.ts +20 -5
  38. package/src/provisioning/capabilityProvisioner.js +14 -10
  39. package/src/sandbox.js +4 -2
  40. package/src/saveTools.js +146 -0
  41. package/src/saveTools.ts +169 -0
  42. package/src/session/cachePressure.js +77 -0
  43. package/src/session/cachePressure.ts +122 -0
  44. package/src/smartToolsUse.js +96 -15
  45. package/src/smartToolsUse.ts +133 -15
  46. package/src/taskShape.js +7 -7
  47. package/src/taskShape.ts +7 -7
  48. package/src/timeMachine.js +55 -20
  49. package/src/timeMachine.ts +64 -20
  50. package/src/toolPacks.js +217 -310
  51. package/src/toolPacks.ts +505 -0
  52. package/src/tools/deferredMcpSearch.js +21 -13
  53. package/src/tools/deferredMcpSearch.ts +23 -15
  54. package/src/tools/updatePlan.js +2 -2
  55. package/src/tools/updatePlan.ts +2 -2
  56. package/src/toolsList.js +203 -0
  57. package/src/toolsList.ts +224 -0
  58. package/src/tui/chatRenderer.js +49 -14
  59. package/src/tui/codeStreamRenderer.js +16 -5
  60. package/src/tui/codeStreamRenderer.ts +14 -4
  61. package/src/tui/prompt.js +4 -2
  62. package/src/tui/sessionSidebar.js +10 -2
  63. package/src/tui/sessionSidebar.ts +10 -3
  64. package/src/tui/stageSurface.js +27 -1
  65. package/src/tui/text.d.ts +1 -0
  66. package/src/tui/turnRail.js +274 -0
  67. package/src/tui/turnRail.ts +334 -0
  68. package/src/types/contracts.ts +103 -0
  69. package/src/verificationPlan.js +141 -0
  70. package/src/verificationPlan.ts +166 -0
  71. 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, type ProviderConfig, type ChatOptions, type ChatResponse, type ChatResponseAction, type ChatResponseToolCall, type ChatResponseUsage } from './base.js';
10
+ import { extractToolCallJsonObjects, stripToolCallMarkup, stripThinkBlocks } from '../implementationPlan.js';
9
11
 
10
12
  /**
11
13
  * Baseline fallback models for instant offline availability.
@@ -791,82 +793,29 @@ export class AntigravityProvider extends LLMProvider {
791
793
  extractToolCalls(text: string): ChatResponseToolCall[] {
792
794
  const calls: ChatResponseToolCall[] = [];
793
795
  if (!text || typeof text !== 'string') return calls;
794
- const regex = /<tool_call>([\s\S]*?)<\/tool_call>/g;
795
- let match: RegExpExecArray | null;
796
796
  let index = 0;
797
- while ((match = regex.exec(text)) !== null) {
798
- try {
799
- const raw = match[1]?.trim() || '';
800
- const parsed = JSON.parse(raw);
801
- const name = parsed.name || parsed.tool || parsed.function?.name;
802
- if (name) {
803
- const rawArgs = parsed.arguments !== undefined ? parsed.arguments : (parsed.parameters !== undefined ? parsed.parameters : (parsed.input !== undefined ? parsed.input : (parsed.function?.arguments || {})));
804
- calls.push({
805
- id: `agy_call_${Date.now()}_${index++}`,
806
- type: 'function',
807
- function: {
808
- name,
809
- arguments: typeof rawArgs === 'string' ? rawArgs : JSON.stringify(rawArgs || {})
810
- }
811
- });
812
- }
813
- } catch {
814
- // ignore malformed tool_call blocks
815
- }
816
- }
817
-
818
- if (calls.length === 0) {
819
- const fenceRegex = /```(?:tool_call|json)?\s*(\{[\s\S]*?"name"\s*:\s*[\s\S]*?\})\s*```/g;
820
- while ((match = fenceRegex.exec(text)) !== null) {
821
- try {
822
- const raw = match[1]?.trim() || '';
823
- const parsed = JSON.parse(raw);
824
- const name = parsed.name || parsed.tool || parsed.function?.name;
825
- if (name) {
826
- const rawArgs = parsed.arguments !== undefined ? parsed.arguments : (parsed.parameters !== undefined ? parsed.parameters : (parsed.input !== undefined ? parsed.input : (parsed.function?.arguments || {})));
827
- calls.push({
828
- id: `agy_call_${Date.now()}_${index++}`,
829
- type: 'function',
830
- function: {
831
- name,
832
- arguments: typeof rawArgs === 'string' ? rawArgs : JSON.stringify(rawArgs || {})
833
- }
834
- });
835
- }
836
- } catch {
837
- // ignore
838
- }
839
- }
840
- }
841
-
842
- // Unclosed tool_call recovery (when model generated large file content and closed turn)
843
- if (calls.length === 0) {
844
- const openIndex = text.lastIndexOf('<tool_call>');
845
- if (openIndex !== -1 && text.indexOf('</tool_call>', openIndex) === -1) {
846
- const partial = text.slice(openIndex + '<tool_call>'.length).trim();
847
- for (const suffix of ['', '}', '}}', '}}}', '"}', '"}}', '"}}}', '"}]}}', '"]}}', '"]}}}']) {
848
- try {
849
- const parsed = JSON.parse(partial + suffix);
850
- const name = parsed.name || parsed.tool || parsed.function?.name;
851
- if (name) {
852
- const rawArgs = parsed.arguments !== undefined ? parsed.arguments : (parsed.parameters !== undefined ? parsed.parameters : (parsed.input !== undefined ? parsed.input : (parsed.function?.arguments || {})));
853
- calls.push({
854
- id: `agy_call_${Date.now()}_0`,
855
- type: 'function',
856
- function: {
857
- name,
858
- arguments: typeof rawArgs === 'string' ? rawArgs : JSON.stringify(rawArgs || {})
859
- }
860
- });
861
- break;
862
- }
863
- } catch {
864
- // try next candidate
865
- }
797
+ for (const parsed of extractToolCallJsonObjects(text)) {
798
+ const fnObj = parsed.function && typeof parsed.function === 'object'
799
+ ? (parsed.function as Record<string, unknown>)
800
+ : null;
801
+ const name = String(parsed.name || parsed.tool || fnObj?.name || '').trim();
802
+ if (!name) continue;
803
+ const rawArgs = parsed.arguments !== undefined
804
+ ? parsed.arguments
805
+ : parsed.parameters !== undefined
806
+ ? parsed.parameters
807
+ : parsed.input !== undefined
808
+ ? parsed.input
809
+ : (fnObj?.arguments ?? {});
810
+ calls.push({
811
+ id: `agy_call_${Date.now()}_${index++}`,
812
+ type: 'function',
813
+ function: {
814
+ name,
815
+ arguments: typeof rawArgs === 'string' ? rawArgs : JSON.stringify(rawArgs || {})
866
816
  }
867
- }
817
+ });
868
818
  }
869
-
870
819
  return calls;
871
820
  }
872
821
 
@@ -944,6 +893,16 @@ export class AntigravityProvider extends LLMProvider {
944
893
  'Keep native tool actions within 12; use Causyne tool calls when a native action is blocked.\n\n' + promptText;
945
894
  }
946
895
 
896
+ const taskArchetype = (options as any).taskArchetype || determineToolScope(latestPrompt).archetype;
897
+ const webOrGameTask = taskArchetype === 'web_engineering' || taskArchetype === 'game_development';
898
+ if (webOrGameTask) {
899
+ promptText = '[Web & Interactive Verification Directive]\n' +
900
+ 'Causyne provides native host tools for browser verification: `browser_act` (preview and snapshot) and `screenshot`/`vision_inspect_ui`. ' +
901
+ 'DO NOT write custom Node.js/Python headless Chrome or CDP WebSocket scripts to inspect console logs or take screenshots. ' +
902
+ 'Causyne automatically captures browser console errors and renders WebGL/Canvas with hardware acceleration. ' +
903
+ 'Use <tool_call>{"name": "browser_act", "arguments": {"action": "preview", "filePath": "index.html"}}</tool_call> to verify rendered output directly.\n\n' + promptText;
904
+ }
905
+
947
906
  const modelSlug = resolveAgyModelId(this.model);
948
907
  const effort = resolveAgyEffort(this.model);
949
908
 
@@ -984,6 +943,7 @@ export class AntigravityProvider extends LLMProvider {
984
943
  let sawToolAfterLastText = false;
985
944
  let sawProviderProgress = false;
986
945
  let reasoningChars = 0;
946
+ let inInlineThinkBlock = false;
987
947
  let usageBaselineCommitted = false;
988
948
  const nativeActions: ChatResponseAction[] = [];
989
949
  const attemptedNativeTools: {
@@ -1028,11 +988,12 @@ export class AntigravityProvider extends LLMProvider {
1028
988
  const hasExplicitLimit = (Number.isFinite(remainingTaskBudget) && remainingTaskBudget > 0)
1029
989
  || (Number.isFinite(rawTokenLimit) && rawTokenLimit > 0);
1030
990
  const countReportedTotal = options.tokenBudgetBasis !== 'noncached';
991
+ const defaultTokenLimit = turnTokenLimitFor(taskArchetype);
1031
992
  const tokenLimit = Number.isFinite(remainingTaskBudget) && remainingTaskBudget > 0
1032
993
  ? remainingTaskBudget
1033
994
  : (Number.isFinite(rawTokenLimit) && rawTokenLimit > 0
1034
995
  ? rawTokenLimit
1035
- : 100_000);
996
+ : defaultTokenLimit);
1036
997
  const wallTimer = desktopTask ? setTimeout(() => {
1037
998
  const error = new Error('Antigravity exceeded the 180-second desktop task limit. Outcome is unverified.') as Error & { code: string };
1038
999
  error.code = 'AGY_DESKTOP_TASK_LIMIT';
@@ -1151,18 +1112,30 @@ export class AntigravityProvider extends LLMProvider {
1151
1112
  const spentAgainstLimit = countReportedTotal ? reportedTotal : uncachedTotal;
1152
1113
  if (Number.isFinite(tokenLimit) && tokenLimit > 0
1153
1114
  && spentAgainstLimit >= tokenLimit) {
1154
- const error = Object.assign(
1155
- new Error(`Antigravity reported ${spentAgainstLimit} tokens against a ${tokenLimit}-token per-call ceiling. This turn stopped and its outcome is unverified.`),
1156
- { code: 'AGY_TOKEN_BUDGET', tokenLimit, partialUsage: { ...partialUsage } }
1157
- );
1158
- safeReject(error);
1159
- terminateChild();
1160
- return;
1115
+ if ((options as any).hardBudget === false) {
1116
+ if (process.env.CAUSYNE_DEBUG === '1') {
1117
+ console.log(`[BUDGET] Turn spent ${spentAgainstLimit} tokens against soft checkpoint ${tokenLimit}. Continuing execution.`);
1118
+ }
1119
+ } else {
1120
+ const error = Object.assign(
1121
+ new Error(`Antigravity reported ${spentAgainstLimit} tokens against a ${tokenLimit}-token per-call ceiling. This turn stopped and its outcome is unverified.`),
1122
+ { code: 'AGY_TOKEN_BUDGET', tokenLimit, partialUsage: { ...partialUsage } }
1123
+ );
1124
+ safeReject(error);
1125
+ terminateChild();
1126
+ return;
1127
+ }
1161
1128
  }
1162
1129
  }
1163
1130
  }
1164
- const delta = stepUpdate?.text_delta;
1165
- const stepType = stepUpdate?.step_type;
1131
+ const delta = stepUpdate?.text_delta
1132
+ ?? stepUpdate?.delta
1133
+ ?? stepUpdate?.thought_delta
1134
+ ?? stepUpdate?.thought
1135
+ ?? (typeof stepUpdate?.content === 'string' ? stepUpdate.content : undefined)
1136
+ ?? event?.text_delta
1137
+ ?? event?.delta;
1138
+ const stepType = stepUpdate?.step_type || event?.step_type || event?.type;
1166
1139
  if (stepType === 'tool') {
1167
1140
  const state = stepUpdate?.state;
1168
1141
  const stepIndex = Number(stepUpdate?.step_index ?? event?.step_index);
@@ -1249,36 +1222,75 @@ export class AntigravityProvider extends LLMProvider {
1249
1222
  if (existing) existing.status = status;
1250
1223
  else nativeActions.push(action);
1251
1224
  }
1252
- // Stream the start; completion is reported only after the
1253
- // final result has checked for denied actions.
1254
- if (status === 'running' && typeof options.onNativeAction === 'function') {
1225
+ // Stream the action lifecycle immediately (running, completed, failed)
1226
+ // so the caller receives real-time progress and does not appear frozen.
1227
+ if (typeof options.onNativeAction === 'function') {
1255
1228
  const parameters = rawParams && typeof rawParams === 'object'
1256
1229
  ? rawParams as Record<string, unknown>
1257
1230
  : {};
1258
- options.onNativeAction({ ...action, parameters });
1231
+ options.onNativeAction({ ...action, status, parameters });
1259
1232
  }
1260
1233
  }
1261
1234
  }
1235
+ const isExplicitThought = stepType === 'thought'
1236
+ || stepType === 'agent_thought'
1237
+ || stepType === 'thinking'
1238
+ || stepType === 'reasoning'
1239
+ || stepType === 'agent_reasoning'
1240
+ || Boolean(stepUpdate?.thought_delta || stepUpdate?.thought);
1241
+
1262
1242
  if (delta && typeof delta === 'string') {
1263
- if (stepType === 'thought' || stepType === 'agent_thought') {
1243
+ if (isExplicitThought) {
1264
1244
  reasoningChars += delta.length;
1265
1245
  if (typeof options.onReasoningChunk === 'function') {
1266
1246
  options.onReasoningChunk(delta);
1267
1247
  }
1268
1248
  } else {
1269
- if (sawToolAfterLastText && streamedResponse.length > 0 && !/\s$/.test(streamedResponse) && !/^\s/.test(delta)) {
1270
- streamedResponse += '\n';
1271
- if (typeof options.onChunk === 'function') {
1272
- options.onChunk('\n');
1249
+ // Progressive inline think block filtering (<think>...</think>, <thought>...</thought>, etc.)
1250
+ let remaining = delta;
1251
+ while (remaining.length > 0) {
1252
+ if (inInlineThinkBlock) {
1253
+ const closeMatch = remaining.match(/<\/(?:think|thought|reasoning|thinking|REASONING_SCRATCHPAD)>/i);
1254
+ if (closeMatch && closeMatch.index !== undefined) {
1255
+ const thinkPart = remaining.slice(0, closeMatch.index);
1256
+ if (thinkPart) {
1257
+ reasoningChars += thinkPart.length;
1258
+ options.onReasoningChunk?.(thinkPart);
1259
+ }
1260
+ inInlineThinkBlock = false;
1261
+ remaining = remaining.slice(closeMatch.index + closeMatch[0].length);
1262
+ } else {
1263
+ reasoningChars += remaining.length;
1264
+ options.onReasoningChunk?.(remaining);
1265
+ remaining = '';
1266
+ }
1267
+ } else {
1268
+ const openMatch = remaining.match(/<(?:think|thought|reasoning|thinking|REASONING_SCRATCHPAD)>/i);
1269
+ if (openMatch && openMatch.index !== undefined) {
1270
+ const textPart = remaining.slice(0, openMatch.index);
1271
+ if (textPart) {
1272
+ if (sawToolAfterLastText && streamedResponse.length > 0 && !/\s$/.test(streamedResponse) && !/^\s/.test(textPart)) {
1273
+ streamedResponse += '\n';
1274
+ options.onChunk?.('\n');
1275
+ }
1276
+ if (textPart.trim().length > 0) sawToolAfterLastText = false;
1277
+ streamedResponse += textPart;
1278
+ options.onChunk?.(textPart);
1279
+ }
1280
+ inInlineThinkBlock = true;
1281
+ remaining = remaining.slice(openMatch.index + openMatch[0].length);
1282
+ } else {
1283
+ if (sawToolAfterLastText && streamedResponse.length > 0 && !/\s$/.test(streamedResponse) && !/^\s/.test(remaining)) {
1284
+ streamedResponse += '\n';
1285
+ options.onChunk?.('\n');
1286
+ }
1287
+ if (remaining.trim().length > 0) sawToolAfterLastText = false;
1288
+ streamedResponse += remaining;
1289
+ options.onChunk?.(remaining);
1290
+ remaining = '';
1291
+ }
1273
1292
  }
1274
1293
  }
1275
- if (delta.trim().length > 0) {
1276
- sawToolAfterLastText = false;
1277
- }
1278
- streamedResponse += delta;
1279
- if (typeof options.onChunk === 'function') {
1280
- options.onChunk(delta);
1281
- }
1282
1294
  }
1283
1295
  }
1284
1296
  } else if (event.event === 'result') {
@@ -1351,8 +1363,8 @@ export class AntigravityProvider extends LLMProvider {
1351
1363
 
1352
1364
  const toolCalls = this.extractToolCalls(rawContent);
1353
1365
 
1354
- // Strip tool call tags from prose so raw XML does not leak into chat display
1355
- let content = rawContent.replace(/<tool_call>[\s\S]*?<\/tool_call>/g, '').trim();
1366
+ // Strip tool call tags and think tags from prose so raw XML/DSML/think does not leak into chat display
1367
+ let content = stripThinkBlocks(stripToolCallMarkup(rawContent));
1356
1368
 
1357
1369
  const deniedActions: any[] = Array.isArray(finalResultObj?.denied_actions)
1358
1370
  ? finalResultObj.denied_actions : [];
@@ -1361,12 +1373,15 @@ export class AntigravityProvider extends LLMProvider {
1361
1373
  const deniedNames = new Set(deniedActions.flatMap(action =>
1362
1374
  [normalizeAction(action?.action), normalizeAction(action?.display_name)]).filter(Boolean));
1363
1375
  for (const action of nativeActions) {
1364
- if (deniedNames.has(normalizeAction(action.name))) action.status = 'failed';
1365
- if (typeof options.onNativeAction === 'function') {
1376
+ const wasDenied = deniedNames.has(normalizeAction(action.name));
1377
+ if (wasDenied) action.status = 'failed';
1378
+ else if (action.status === 'running') action.status = 'failed';
1379
+ // Only re-emit on terminal close if the action was denied or left unfinished
1380
+ if (wasDenied && typeof options.onNativeAction === 'function') {
1366
1381
  const attempt = [...attemptedNativeTools].reverse().find(candidate => action.id
1367
1382
  ? candidate.id === action.id
1368
1383
  : normalizeAction(candidate.name) === normalizeAction(action.name) && candidate.detail === action.detail);
1369
- options.onNativeAction({ ...action, parameters: attempt?.parameters || {} });
1384
+ options.onNativeAction({ ...action, status: 'failed', parameters: attempt?.parameters || {} });
1370
1385
  }
1371
1386
  }
1372
1387
 
@@ -1502,10 +1517,16 @@ export class AntigravityProvider extends LLMProvider {
1502
1517
  const uncachedTotal = noncachedTokens(response.usage);
1503
1518
  const spentAgainstLimit = countReportedTotal ? reportedTotal : uncachedTotal;
1504
1519
  if (spentAgainstLimit >= tokenLimit) {
1505
- Object.assign(partialUsage, response.usage);
1506
- safeReject(Object.assign(new Error(`Antigravity reached its ${tokenLimit}-token checkpoint. Work remains unverified.`),
1507
- { code: 'AGY_TOKEN_BUDGET', tokenLimit, partialUsage: { ...partialUsage } }));
1508
- return;
1520
+ if ((options as any).hardBudget === false) {
1521
+ if (process.env.CAUSYNE_DEBUG === '1') {
1522
+ console.log(`[BUDGET] Turn finished with ${spentAgainstLimit} tokens against soft checkpoint ${tokenLimit}. Preserving result.`);
1523
+ }
1524
+ } else {
1525
+ Object.assign(partialUsage, response.usage);
1526
+ safeReject(Object.assign(new Error(`Antigravity reached its ${tokenLimit}-token checkpoint. Work remains unverified.`),
1527
+ { code: 'AGY_TOKEN_BUDGET', tokenLimit, partialUsage: { ...partialUsage } }));
1528
+ return;
1529
+ }
1509
1530
  }
1510
1531
  safeResolve(response);
1511
1532
  });
@@ -19,6 +19,7 @@ export interface ChatResponseUsage {
19
19
  uncachedPromptTokens?: number | undefined;
20
20
  measurement?: 'provider_reported' | 'text_estimate' | undefined;
21
21
  cacheMeasurement?: 'provider_reported' | 'unavailable' | undefined;
22
+ measurementScope?: 'last_model_call' | 'peer_reported' | undefined;
22
23
  totalTokens?: number | undefined;
23
24
  thinkingTokens?: number | undefined;
24
25
  }
@@ -47,6 +48,7 @@ export interface ChatResponse {
47
48
  reasoningContent?: string | undefined;
48
49
  thinkingBlocks?: any[] | undefined;
49
50
  externalActions?: ChatResponseAction[] | undefined;
51
+ toolRoutingError?: { tool: string; message: string } | undefined;
50
52
  incompleteTurn?: boolean | undefined;
51
53
  }
52
54
 
@@ -63,6 +65,7 @@ export interface ChatOptions {
63
65
  onChunk?: ((chunk: string) => void) | undefined;
64
66
  onReasoningChunk?: ((chunk: string) => void) | undefined;
65
67
  onNativeAction?: ((action: ChatResponseAction) => void) | undefined;
68
+ onPlanUpdate?: ((plan: unknown) => void) | undefined;
66
69
  coreToolCount?: number | undefined;
67
70
  [key: string]: any;
68
71
  }
@@ -14,11 +14,21 @@ export function actionLimitFor(archetype) {
14
14
  return 12;
15
15
  if (archetype === 'media_3d_generation')
16
16
  return 25;
17
+ if (archetype === 'game_development' || archetype === 'game')
18
+ return 250;
19
+ if (archetype === 'software_engineering' || archetype === 'backend_engineering')
20
+ return 200;
21
+ if (archetype === 'web_engineering')
22
+ return 120;
17
23
  return 35;
18
24
  }
19
25
  export function tokenLimitFor(archetype) {
20
26
  if (archetype === 'desktop_personalization')
21
27
  return 150_000;
28
+ if (archetype === 'game_development' || archetype === 'game')
29
+ return 3_000_000;
30
+ if (archetype === 'software_engineering' || archetype === 'backend_engineering')
31
+ return 2_500_000;
22
32
  if (archetype === 'media_3d_generation')
23
33
  return 400_000;
24
34
  if (archetype === 'web_engineering' || archetype === 'web_fullstack')
@@ -26,6 +36,10 @@ export function tokenLimitFor(archetype) {
26
36
  return 100_000;
27
37
  }
28
38
  export function turnTokenLimitFor(archetype) {
39
+ if (archetype === 'game_development' || archetype === 'game')
40
+ return 1_000_000;
41
+ if (archetype === 'software_engineering' || archetype === 'backend_engineering')
42
+ return 1_000_000;
29
43
  if (archetype === 'web_engineering' || archetype === 'web_fullstack')
30
44
  return 250_000;
31
45
  if (archetype === 'media_3d_generation')
@@ -42,8 +56,10 @@ export class EfficiencyCheckpoint extends Error {
42
56
  scope;
43
57
  constructor(reason, used, limit, scope = 'task') {
44
58
  const scopeLabel = scope === 'turn' ? 'single-turn' : 'task';
45
- super(`Efficiency checkpoint: ${used.toLocaleString()} ${reason} reached the ${limit.toLocaleString()} ${scopeLabel} limit. `
46
- + 'Work is unfinished. Session history is retained; continue from this checkpoint without repeating completed actions.');
59
+ const guidance = scope === 'turn'
60
+ ? 'Auto-compacting context and continuing task execution.'
61
+ : 'Session history is retained; continue from this checkpoint without repeating completed actions.';
62
+ super(`Efficiency checkpoint: ${used.toLocaleString()} ${reason} reached the ${limit.toLocaleString()} ${scopeLabel} limit. ${guidance}`);
47
63
  this.name = 'EfficiencyCheckpoint';
48
64
  this.reason = reason;
49
65
  this.used = used;
@@ -69,6 +85,11 @@ export class UnifiedBudgetEnforcer {
69
85
  ? Math.max(maxTaskTokens, maxTurnTokens)
70
86
  : maxTurnTokens;
71
87
  }
88
+ extendBudget(extraTokens, extraActions) {
89
+ this.maxTaskTokens = Math.max(this.maxTaskTokens, this.tokens + extraTokens);
90
+ this.maxTurnTokens = Math.max(this.maxTurnTokens, extraTokens);
91
+ this.maxTurnActions = Math.max(this.maxTurnActions, this.actions + extraActions);
92
+ }
72
93
  recordUsage(usage) {
73
94
  const fresh = noncachedTokens(usage);
74
95
  if (fresh >= this.maxTurnTokens) {
@@ -22,17 +22,24 @@ export function noncachedTokens(usage: BudgetUsage): number {
22
22
  export function actionLimitFor(archetype: string): number {
23
23
  if (archetype === 'desktop_personalization') return 12;
24
24
  if (archetype === 'media_3d_generation') return 25;
25
+ if (archetype === 'game_development' || archetype === 'game') return 250;
26
+ if (archetype === 'software_engineering' || archetype === 'backend_engineering') return 200;
27
+ if (archetype === 'web_engineering') return 120;
25
28
  return 35;
26
29
  }
27
30
 
28
31
  export function tokenLimitFor(archetype: string): number {
29
32
  if (archetype === 'desktop_personalization') return 150_000;
33
+ if (archetype === 'game_development' || archetype === 'game') return 3_000_000;
34
+ if (archetype === 'software_engineering' || archetype === 'backend_engineering') return 2_500_000;
30
35
  if (archetype === 'media_3d_generation') return 400_000;
31
36
  if (archetype === 'web_engineering' || archetype === 'web_fullstack') return 500_000;
32
37
  return 100_000;
33
38
  }
34
39
 
35
40
  export function turnTokenLimitFor(archetype: string): number {
41
+ if (archetype === 'game_development' || archetype === 'game') return 1_000_000;
42
+ if (archetype === 'software_engineering' || archetype === 'backend_engineering') return 1_000_000;
36
43
  if (archetype === 'web_engineering' || archetype === 'web_fullstack') return 250_000;
37
44
  if (archetype === 'media_3d_generation') return 200_000;
38
45
  if (archetype === 'desktop_personalization') return 100_000;
@@ -48,8 +55,10 @@ export class EfficiencyCheckpoint extends Error {
48
55
 
49
56
  constructor(reason: 'tokens' | 'actions', used: number, limit: number, scope: 'turn' | 'task' = 'task') {
50
57
  const scopeLabel = scope === 'turn' ? 'single-turn' : 'task';
51
- super(`Efficiency checkpoint: ${used.toLocaleString()} ${reason} reached the ${limit.toLocaleString()} ${scopeLabel} limit. `
52
- + 'Work is unfinished. Session history is retained; continue from this checkpoint without repeating completed actions.');
58
+ const guidance = scope === 'turn'
59
+ ? 'Auto-compacting context and continuing task execution.'
60
+ : 'Session history is retained; continue from this checkpoint without repeating completed actions.';
61
+ super(`Efficiency checkpoint: ${used.toLocaleString()} ${reason} reached the ${limit.toLocaleString()} ${scopeLabel} limit. ${guidance}`);
53
62
  this.name = 'EfficiencyCheckpoint';
54
63
  this.reason = reason;
55
64
  this.used = used;
@@ -59,9 +68,9 @@ export class EfficiencyCheckpoint extends Error {
59
68
  }
60
69
 
61
70
  export class UnifiedBudgetEnforcer {
62
- readonly maxTurnTokens: number;
63
- readonly maxTurnActions: number;
64
- readonly maxTaskTokens: number;
71
+ maxTurnTokens: number;
72
+ maxTurnActions: number;
73
+ maxTaskTokens: number;
65
74
  private tokens = 0;
66
75
  private actions = 0;
67
76
  private readonly nativeIds = new Set<string>();
@@ -78,6 +87,12 @@ export class UnifiedBudgetEnforcer {
78
87
  : maxTurnTokens;
79
88
  }
80
89
 
90
+ extendBudget(extraTokens: number, extraActions: number): void {
91
+ this.maxTaskTokens = Math.max(this.maxTaskTokens, this.tokens + extraTokens);
92
+ this.maxTurnTokens = Math.max(this.maxTurnTokens, extraTokens);
93
+ this.maxTurnActions = Math.max(this.maxTurnActions, this.actions + extraActions);
94
+ }
95
+
81
96
  recordUsage(usage: BudgetUsage): void {
82
97
  const fresh = noncachedTokens(usage);
83
98
  if (fresh >= this.maxTurnTokens) {
@@ -10,7 +10,9 @@ import { isGroupGranted, isGroupDeclined } from './capabilityConsent.js';
10
10
  import { causyneHome } from '../utils/paths.js';
11
11
  import { currentToolAutonomyMode } from '../approvalPolicy.js';
12
12
 
13
- const CAPABILITY_DIR = path.join(causyneHome(), 'capabilities');
13
+ function capabilityDir() {
14
+ return path.join(causyneHome(), 'capabilities');
15
+ }
14
16
 
15
17
  // Groups exist so consent is asked once per capability a human recognises
16
18
  // ("let it see the screen"), not once per npm package. Names stay in value
@@ -109,7 +111,7 @@ export function revokeGroup(group) {
109
111
 
110
112
  /** True when the package is already on disk in the sovereign directory. */
111
113
  export function isPackageInstalled(packageName) {
112
- return fs.existsSync(path.join(CAPABILITY_DIR, 'node_modules', packageName));
114
+ return fs.existsSync(path.join(capabilityDir(), 'node_modules', packageName));
113
115
  }
114
116
 
115
117
  export function isGroupInstalled(group) {
@@ -149,11 +151,12 @@ export async function provisionCapabilities(groups = []) {
149
151
  const target = [...new Set([...grantedGroups(), ...groups])].filter(g => GROUP_PACKAGES[g]);
150
152
  if (target.length === 0) return { installed: [], skipped: true };
151
153
 
152
- if (!fs.existsSync(CAPABILITY_DIR)) {
153
- fs.mkdirSync(CAPABILITY_DIR, { recursive: true, mode: 0o700 });
154
+ const dir = capabilityDir();
155
+ if (!fs.existsSync(dir)) {
156
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
154
157
  }
155
158
 
156
- const manifestPath = path.join(CAPABILITY_DIR, 'package.json');
159
+ const manifestPath = path.join(dir, 'package.json');
157
160
  const desired = JSON.stringify(manifestFor(target), null, 2);
158
161
 
159
162
  let needsInstall = true;
@@ -162,14 +165,14 @@ export async function provisionCapabilities(groups = []) {
162
165
  }
163
166
  if (needsInstall) fs.writeFileSync(manifestPath, desired);
164
167
 
165
- if (!fs.existsSync(path.join(CAPABILITY_DIR, 'package-lock.json'))) needsInstall = true;
168
+ if (!fs.existsSync(path.join(dir, 'package-lock.json'))) needsInstall = true;
166
169
  for (const group of target) {
167
170
  if (!isGroupInstalled(group)) { needsInstall = true; break; }
168
171
  }
169
172
 
170
173
  if (!needsInstall) return { installed: target, skipped: true };
171
174
 
172
- installCapabilityManifest(CAPABILITY_DIR);
175
+ installCapabilityManifest(dir);
173
176
  return { installed: target, skipped: false };
174
177
  }
175
178
 
@@ -233,12 +236,13 @@ export async function ensureCapability(group) {
233
236
  * which is the bug that silently disabled the entire V5 Cortex once already.
234
237
  */
235
238
  export async function requireCapabilityModule(packageName) {
236
- const modulePath = path.join(CAPABILITY_DIR, 'node_modules', packageName);
239
+ const dir = capabilityDir();
240
+ const modulePath = path.join(dir, 'node_modules', packageName);
237
241
  if (!fs.existsSync(modulePath)) {
238
242
  throw new Error(`Capability module ${packageName} is not provisioned.`);
239
243
  }
240
244
 
241
- const capabilityRequire = createRequire(path.join(CAPABILITY_DIR, 'package.json'));
245
+ const capabilityRequire = createRequire(path.join(dir, 'package.json'));
242
246
  let entryPoint;
243
247
  try {
244
248
  entryPoint = capabilityRequire.resolve(packageName);
@@ -284,5 +288,5 @@ export async function loadCapabilityPackage(packageName) {
284
288
  }
285
289
 
286
290
  export function capabilityDirectory() {
287
- return CAPABILITY_DIR;
291
+ return capabilityDir();
288
292
  }
package/src/sandbox.js CHANGED
@@ -290,7 +290,7 @@ export class Sandbox {
290
290
  return validateBrowserActSandbox(
291
291
  args,
292
292
  this.workspacePaths[0],
293
- url => this.isInternalUrl(url),
293
+ url => this.isInternalUrl(url, { allowLoopback: true }),
294
294
  targetPath => this.isPathAllowed(targetPath)
295
295
  );
296
296
  }
@@ -415,11 +415,13 @@ export class Sandbox {
415
415
  });
416
416
  }
417
417
 
418
- isInternalUrl(urlString) {
418
+ isInternalUrl(urlString, { allowLoopback = false } = {}) {
419
419
  try {
420
420
  const url = new URL(urlString);
421
421
  if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) return true;
422
422
  const host = url.hostname.toLowerCase().replace(/^\[|\]$/g, '').replace(/\.$/, '');
423
+ const isLoopback = host === 'localhost' || host.endsWith('.localhost') || /^127\.\d+\.\d+\.\d+$/.test(host) || host === '::1';
424
+ if (allowLoopback && isLoopback) return false;
423
425
  if (host === 'localhost' || host.endsWith('.localhost') || host.endsWith('.local') || host.endsWith('.internal')) return true;
424
426
 
425
427
  // Block localhost, private IPs, cloud metadata