@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
@@ -10,6 +10,7 @@
10
10
 
11
11
  import { PACK_PLAYBOOKS, isWebIntent } from './toolPacks.js';
12
12
  import { isMutatingToolCall } from './decisionPolicy.js';
13
+ import type { ToolDecision } from './decideTools.js';
13
14
 
14
15
  export type ExecutionPhase = 'inspection' | 'synthesis' | 'execution' | 'verification';
15
16
 
@@ -23,7 +24,8 @@ export interface ToolPhaseSnapshot {
23
24
  const INSPECTION_TOOLS = new Set([
24
25
  'fs_read', 'fs_list', 'fs_find', 'fs_search', 'grep_search', 'code_searcher',
25
26
  'codebase_search', 'web_search', 'web_fetch', 'browser_snapshot',
26
- 'browser_get_dom', 'view_image', 'pdf_read', 'dir_list'
27
+ 'browser_get_dom', 'view_image', 'pdf_read', 'dir_list',
28
+ 'read', 'read_file', 'view_file', 'viewfile', 'cat', 'glob', 'grep', 'search', 'list_dir', 'ls'
27
29
  ]);
28
30
  const VERIFICATION_TOOLS = new Set([
29
31
  'screenshot', 'vision_inspect_ui', 'browser_console', 'ax_snapshot'
@@ -31,16 +33,21 @@ const VERIFICATION_TOOLS = new Set([
31
33
 
32
34
  function isInspection(toolName: string, args: Record<string, unknown>): boolean {
33
35
  if (INSPECTION_TOOLS.has(toolName)) return true;
34
- if (toolName !== 'sysRun') return false;
36
+ if (!['sysRun', 'bash', 'terminal', 'execute', 'sh', 'zsh'].includes(toolName)) return false;
35
37
  return /^\s*(?:pwd|ls|find|rg|grep|cat|sed|head|tail|git\s+(?:status|diff|log|show)|npm\s+(?:view|audit))\b/i
36
- .test(String(args.command ?? ''));
38
+ .test(String(args.command ?? args.cmd ?? ''));
37
39
  }
38
40
 
39
41
  function isVerification(toolName: string, args: Record<string, unknown>): boolean {
40
42
  if (VERIFICATION_TOOLS.has(toolName)) return true;
41
- if (toolName !== 'sysRun') return false;
42
- return /^\s*(?:npm\s+(?:test|run\s+(?:test|typecheck|build))|node\s+--check|pytest|cargo\s+test|go\s+test)\b/i
43
- .test(String(args.command ?? ''));
43
+ if (toolName === 'browser_act') {
44
+ const actions = Array.isArray(args.actions) ? args.actions : [args];
45
+ return actions.some((item: unknown) => item !== null && typeof item === 'object'
46
+ && ['preview', 'screenshot', 'inspect', 'snapshot'].includes(String((item as Record<string, unknown>).action ?? (item as Record<string, unknown>).type ?? '')));
47
+ }
48
+ if (!['sysRun', 'bash', 'terminal', 'execute', 'sh', 'zsh'].includes(toolName)) return false;
49
+ return /^\s*(?:npm\s+(?:test|run\s+(?:test|typecheck|build))|node\s+--check|pytest|cargo\s+test|go\s+test|python(?:3)?\s+-m\s+unittest|vitest|jest|playwright|cypress)\b/i
50
+ .test(String(args.command ?? args.cmd ?? ''));
44
51
  }
45
52
 
46
53
  /**
@@ -163,11 +170,11 @@ const EXPLICIT_MEDIA_GENERATION_PATTERN =
163
170
 
164
171
  // Explicit web engineering intent
165
172
  const EXPLICIT_WEB_ENGINEERING_PATTERN =
166
- /\b(build|create|make|design|develop|implement|redesign|buat\w*)\b[\s\S]*\b(web|website|webpage|webapp|landing page|dashboard|ui|frontend|threejs|three\.js|3js)\b/i;
173
+ /\b(build|create|make|design|develop|implement|redesign|buat\w*)\b[\s\S]*\b(web|website|webpage|webapp|landing page|dashboard|ui|frontend|threejs|three\.js|thre\.?js|3js|webgl|canvas)\b/i;
167
174
 
168
175
  // Explicit game development intent
169
176
  const EXPLICIT_GAME_DEV_PATTERN =
170
- /\b(build.*game|create.*game|develop.*game|godot|unity|unreal|platformer 2d|rpg game|arcade game)\b/i;
177
+ /(?:\b(build.*(?:game|simulation|simulator)|create.*(?:game|simulation|simulator)|develop.*(?:game|simulation|simulator)|buat\w*.*(?:game|simulation|simulator)|bikin\w*.*(?:game|simulation|simulator)|game|gamedev|godot|unity|unreal|platformer|rpg|arcade|simulator|simulation|simulasi|interactive|3d\s*(?:game|app|simulator|scene|city|world|view))\b|[-_]3d\b|\b3d[-_]|\b(?:threejs|three\.js|webgl|canvas3d|babylonjs)\b)/i;
171
178
 
172
179
  /**
173
180
  * Select tools to preload based on prompt intent. This is never an allowlist:
@@ -261,6 +268,7 @@ export function determineToolScope(
261
268
  };
262
269
  }
263
270
 
271
+ // 5. Web engineering intent (websites, web applications, landing pages, Three.js web scenes)
264
272
  if (EXPLICIT_WEB_ENGINEERING_PATTERN.test(text)) {
265
273
  const tools = new Set([
266
274
  'fs_write',
@@ -282,7 +290,7 @@ export function determineToolScope(
282
290
  };
283
291
  }
284
292
 
285
- // 5. Media / 3D generation & creative audio intent
293
+ // 6. Media / 3D generation & creative audio intent
286
294
  if (EXPLICIT_MEDIA_GENERATION_PATTERN.test(text)) {
287
295
  const tools = new Set([
288
296
  'blender_act',
@@ -303,6 +311,28 @@ export function determineToolScope(
303
311
  };
304
312
  }
305
313
 
314
+ // 7. Game development and interactive simulation intent (simulators, 3D worlds, games)
315
+ if (EXPLICIT_GAME_DEV_PATTERN.test(text)) {
316
+ const tools = new Set([
317
+ 'fs_write',
318
+ 'fs_edit',
319
+ 'fs_read',
320
+ 'fs_list',
321
+ 'sysRun',
322
+ 'browser_act',
323
+ 'screenshot',
324
+ 'vision_inspect_ui',
325
+ 'update_plan',
326
+ 'tool_search'
327
+ ]);
328
+ return {
329
+ toolScope: tools,
330
+ archetype: 'game_development',
331
+ suppressedPacks: ['media', 'advanced', 'system'],
332
+ reason: 'Game development and simulation intent focuses on game code, assets, terminal execution, and browser/screen verification.'
333
+ };
334
+ }
335
+
306
336
  // Default: unconstrained (standard progressive disclosure and packs apply)
307
337
  return {
308
338
  toolScope: null,
@@ -350,15 +380,15 @@ export function resolveLazyPlaybooks(
350
380
  let tokenSavings = 0;
351
381
 
352
382
  // 1. Web Domain
353
- if (packs.has('web')) {
383
+ const webExplicitDemand = EXPLICIT_WEB_ENGINEERING_PATTERN.test(text)
384
+ || (isWebIntent(text) && WEB_CONSTRUCTION_EXCLUSION.test(text));
385
+ if (packs.has('web') || webExplicitDemand || tools.has('ui_forge') || tools.has('astryx_oracle')) {
354
386
  const webToolInvoked =
355
387
  tools.has('ui_forge') ||
356
388
  tools.has('browser_act') ||
357
389
  tools.has('vision_inspect_ui') ||
358
390
  tools.has('screenshot') ||
359
391
  tools.has('astryx_oracle');
360
- const webExplicitDemand = EXPLICIT_WEB_ENGINEERING_PATTERN.test(text)
361
- || (isWebIntent(text) && WEB_CONSTRUCTION_EXCLUSION.test(text));
362
392
 
363
393
  if ((webToolInvoked || webExplicitDemand) && PACK_PLAYBOOKS.web) {
364
394
  activePlaybooks.push(PACK_PLAYBOOKS.web);
@@ -414,3 +444,64 @@ export function resolveLazyPlaybooks(
414
444
  tokenSavingsEstimate: tokenSavings
415
445
  };
416
446
  }
447
+
448
+ // ---------------------------------------------------------------------------
449
+ // Pipeline stage 3: refine a decideTools decision before it is saved.
450
+ //
451
+ // user intent -> ToolsList -> decideTools -> SmartTools -> saveTools -> AgentLoop
452
+ // ---------------------------------------------------------------------------
453
+
454
+ /** What the loop must do before it may mutate: nothing, plan, or ask the user. */
455
+ export type ToolRoute = 'direct' | 'plan' | 'decision';
456
+
457
+ export interface SmartToolsContext {
458
+ /** True when the task is complex enough to require an implementation plan. */
459
+ readonly planRequired?: boolean | undefined;
460
+ /** True when the task crosses a durable choice the user must make. */
461
+ readonly decisionRequired?: boolean | undefined;
462
+ readonly admittedTools?: ReadonlySet<string> | undefined;
463
+ readonly admittedPacks?: ReadonlySet<string> | undefined;
464
+ }
465
+
466
+ export interface RefinedToolDecision {
467
+ readonly source: ToolDecision['source'];
468
+ readonly tools: string[];
469
+ readonly packs: string[];
470
+ /** Tools held back this step to protect the context window; the next decision sees them again. */
471
+ readonly deferred: string[];
472
+ readonly route: ToolRoute;
473
+ readonly reasons: string[];
474
+ }
475
+
476
+ /** A mid-task decision may load at most this many schemas at once. */
477
+ export const MAX_ADMIT_PER_STEP = 8;
478
+
479
+ /**
480
+ * The smart part: admit only the delta, bound what one step may load, and say
481
+ * what the loop owes before it changes anything. A task the user must decide
482
+ * or plan first keeps the tool for that step reachable, so the checkpoint can
483
+ * never be demanded of a model that was not given the means to meet it.
484
+ */
485
+ export function refineToolDecision(decision: ToolDecision, context: SmartToolsContext): RefinedToolDecision {
486
+ const admittedTools = context.admittedTools ?? new Set<string>();
487
+ const admittedPacks = context.admittedPacks ?? new Set<string>();
488
+ const fresh = decision.tools.filter((name) => !admittedTools.has(name));
489
+ const packs = decision.packs.filter((name) => !admittedPacks.has(name));
490
+ const reasons = [...decision.reasons];
491
+
492
+ let tools = fresh;
493
+ let deferred: string[] = [];
494
+ if (decision.source !== 'intent' && fresh.length > MAX_ADMIT_PER_STEP) {
495
+ tools = fresh.slice(0, MAX_ADMIT_PER_STEP);
496
+ deferred = fresh.slice(MAX_ADMIT_PER_STEP);
497
+ reasons.push(`deferred ${deferred.length} to protect context`);
498
+ }
499
+
500
+ const route: ToolRoute = context.decisionRequired ? 'decision' : context.planRequired ? 'plan' : 'direct';
501
+ if (decision.source === 'intent') {
502
+ const needed = route === 'decision' ? 'request_decision' : route === 'plan' ? 'update_plan' : '';
503
+ if (needed && !admittedTools.has(needed) && !tools.includes(needed)) tools = [...tools, needed];
504
+ }
505
+
506
+ return { source: decision.source, tools, packs, deferred, route, reasons };
507
+ }
package/src/taskShape.js CHANGED
@@ -1,7 +1,7 @@
1
1
  const PACK_SIGNALS = {
2
2
  game: {
3
- strong: ['game', 'gamedev', 'godot', 'unity', 'unreal', 'rpg', 'platformer', 'roguelike', 'arcade', 'voxel', 'minecraft', 'tilemap', 'spritesheet', 'boss fight', 'level design'],
4
- weak: ['sprite', 'player', 'enemy', 'quest', 'npc', 'gameplay', 'multiplayer', 'leaderboard']
3
+ strong: ['game', 'gamedev', 'godot', 'unity', 'unreal', 'rpg', 'platformer', 'roguelike', 'arcade', 'voxel', 'minecraft', 'tilemap', 'spritesheet', 'boss fight', 'level design', 'simulator', 'simulation', 'simulasi', 'tinder-3d', '3d'],
4
+ weak: ['sprite', 'player', 'enemy', 'quest', 'npc', 'gameplay', 'multiplayer', 'leaderboard', 'character']
5
5
  },
6
6
  web: {
7
7
  strong: ['web app', 'webapp', 'website', 'landing page', 'homepage', 'frontend', 'front-end', 'dashboard', 'portfolio', 'react', 'vue', 'svelte', 'angular', 'nextjs', 'next.js', 'nuxt', 'astro', 'tailwind', 'html', 'css'],
@@ -45,8 +45,8 @@ const ARCHETYPES = {
45
45
  build_app: {
46
46
  label: 'Build a new application from scratch',
47
47
  match: {
48
- strong: ['build me', 'create a', 'make me', 'develop a', 'new app', 'from scratch'],
49
- weak: ['app', 'project', 'tool', 'system']
48
+ strong: ['build me', 'create a', 'make me', 'develop a', 'new app', 'from scratch', 'buatkan', 'buat', 'bikin', 'bangun', 'ciptakan'],
49
+ weak: ['app', 'project', 'tool', 'system', 'game', 'simulator', 'aplikasi']
50
50
  },
51
51
  phases: [
52
52
  { name: 'Plan', tools: ['update_plan'], note: 'Create a visible atomic implementation plan before touching the filesystem.' },
@@ -58,8 +58,8 @@ const ARCHETYPES = {
58
58
  debug: {
59
59
  label: 'Diagnose and fix a defect in existing code',
60
60
  match: {
61
- strong: ['bug', 'error', 'crash', 'fix', 'broken', 'not working', 'failing', 'exception', 'stack trace', 'regression'],
62
- weak: ['issue', 'problem', 'wrong', 'debug']
61
+ strong: ['bug', 'error', 'crash', 'fix', 'broken', 'not working', 'failing', 'exception', 'stack trace', 'regression', 'perbaiki', 'betulkan', 'rusak'],
62
+ weak: ['issue', 'problem', 'wrong', 'debug', 'masalah']
63
63
  },
64
64
  phases: [
65
65
  { name: 'Reproduce', tools: ['sysRun', 'fs_read'], note: 'Reproduce the failure and capture the exact error before changing anything.' },
@@ -71,7 +71,7 @@ const ARCHETYPES = {
71
71
  research: {
72
72
  label: 'Investigate and report, without changing the system',
73
73
  match: {
74
- strong: ['explain', 'analyse', 'analyze', 'research', 'compare', 'what is', 'how does', 'review', 'audit'],
74
+ strong: ['explain', 'analyse', 'analyze', 'research', 'compare', 'what is', 'how does', 'review', 'audit', 'analisa', 'jelaskan', 'cek', 'periksa'],
75
75
  weak: ['understand', 'find out', 'summarize']
76
76
  },
77
77
  phases: [
package/src/taskShape.ts CHANGED
@@ -18,8 +18,8 @@ interface ArchetypeDefinition {
18
18
 
19
19
  const PACK_SIGNALS: Record<string, SignalSet> = {
20
20
  game: {
21
- strong: ['game', 'gamedev', 'godot', 'unity', 'unreal', 'rpg', 'platformer', 'roguelike', 'arcade', 'voxel', 'minecraft', 'tilemap', 'spritesheet', 'boss fight', 'level design'],
22
- weak: ['sprite', 'player', 'enemy', 'quest', 'npc', 'gameplay', 'multiplayer', 'leaderboard']
21
+ strong: ['game', 'gamedev', 'godot', 'unity', 'unreal', 'rpg', 'platformer', 'roguelike', 'arcade', 'voxel', 'minecraft', 'tilemap', 'spritesheet', 'boss fight', 'level design', 'simulator', 'simulation', 'simulasi', 'tinder-3d', '3d'],
22
+ weak: ['sprite', 'player', 'enemy', 'quest', 'npc', 'gameplay', 'multiplayer', 'leaderboard', 'character']
23
23
  },
24
24
  web: {
25
25
  strong: ['web app', 'webapp', 'website', 'landing page', 'homepage', 'frontend', 'front-end', 'dashboard', 'portfolio', 'react', 'vue', 'svelte', 'angular', 'nextjs', 'next.js', 'nuxt', 'astro', 'tailwind', 'html', 'css'],
@@ -66,8 +66,8 @@ const ARCHETYPES: Record<string, ArchetypeDefinition> = {
66
66
  build_app: {
67
67
  label: 'Build a new application from scratch',
68
68
  match: {
69
- strong: ['build me', 'create a', 'make me', 'develop a', 'new app', 'from scratch'],
70
- weak: ['app', 'project', 'tool', 'system']
69
+ strong: ['build me', 'create a', 'make me', 'develop a', 'new app', 'from scratch', 'buatkan', 'buat', 'bikin', 'bangun', 'ciptakan'],
70
+ weak: ['app', 'project', 'tool', 'system', 'game', 'simulator', 'aplikasi']
71
71
  },
72
72
  phases: [
73
73
  { name: 'Plan', tools: ['update_plan'], note: 'Create a visible atomic implementation plan before touching the filesystem.' },
@@ -79,8 +79,8 @@ const ARCHETYPES: Record<string, ArchetypeDefinition> = {
79
79
  debug: {
80
80
  label: 'Diagnose and fix a defect in existing code',
81
81
  match: {
82
- strong: ['bug', 'error', 'crash', 'fix', 'broken', 'not working', 'failing', 'exception', 'stack trace', 'regression'],
83
- weak: ['issue', 'problem', 'wrong', 'debug']
82
+ strong: ['bug', 'error', 'crash', 'fix', 'broken', 'not working', 'failing', 'exception', 'stack trace', 'regression', 'perbaiki', 'betulkan', 'rusak'],
83
+ weak: ['issue', 'problem', 'wrong', 'debug', 'masalah']
84
84
  },
85
85
  phases: [
86
86
  { name: 'Reproduce', tools: ['sysRun', 'fs_read'], note: 'Reproduce the failure and capture the exact error before changing anything.' },
@@ -92,7 +92,7 @@ const ARCHETYPES: Record<string, ArchetypeDefinition> = {
92
92
  research: {
93
93
  label: 'Investigate and report, without changing the system',
94
94
  match: {
95
- strong: ['explain', 'analyse', 'analyze', 'research', 'compare', 'what is', 'how does', 'review', 'audit'],
95
+ strong: ['explain', 'analyse', 'analyze', 'research', 'compare', 'what is', 'how does', 'review', 'audit', 'analisa', 'jelaskan', 'cek', 'periksa'],
96
96
  weak: ['understand', 'find out', 'summarize']
97
97
  },
98
98
  phases: [
@@ -2,11 +2,20 @@ import { createHash } from 'node:crypto';
2
2
  import { failureClass } from './planCache.js';
3
3
  import { isVerificationCommand } from './observer/evidence.js';
4
4
  export const TIME_MACHINE_MAX_ATTEMPTS = 6;
5
- export const TIME_MACHINE_REPLAN_AT = 3;
5
+ /**
6
+ * After this many failed attempts at the same issue the agent must stop and ask
7
+ * the user before trying again. Attempts beyond it are three more rounds of
8
+ * similar edits and checks, which cost real time and tokens, so they are the
9
+ * user's call and never the agent's.
10
+ */
11
+ export const TIME_MACHINE_CONSENT_AT = 3;
6
12
  export function recoveryUserMessage(decision, tool) {
7
13
  if (decision.kind === 'human') {
8
14
  return `${tool} needs approval or authentication. Review the last tool error, then provide the needed access or choose another route. No success is claimed.`;
9
15
  }
16
+ if (decision.attempt <= TIME_MACHINE_CONSENT_AT && decision.kind === 'stop') {
17
+ return `${tool} failed ${decision.attempt} times (${decision.failureClass}) and more attempts were not approved. The task stopped without verified success.`;
18
+ }
10
19
  return `${tool} still failed after ${decision.attempt} attempts (${decision.failureClass}). The task stopped without verified success.`;
11
20
  }
12
21
  function record(value) {
@@ -35,9 +44,12 @@ function operationFamily(args) {
35
44
  }
36
45
  return (words[0] || '').replace(/^.*[\\/]/, '').toLowerCase().slice(0, 32);
37
46
  }
38
- function issueKey(tool, args, classification) {
47
+ function issueKey(tool, args) {
39
48
  const family = operationFamily(args);
40
- return createHash('sha256').update(`${tool}\0${family}\0${classification}`).digest('hex');
49
+ const target = String(args.path ?? args.file_path ?? args.filePath ?? '');
50
+ // Changing error text/class does not buy another three attempts at the same
51
+ // operation. Targets are hashed and never included in recovery messages.
52
+ return createHash('sha256').update(`${tool}\0${family}\0${target}`).digest('hex');
41
53
  }
42
54
  function lastGoodTool(outcomes) {
43
55
  for (let index = outcomes.length - 1; index >= 0; index--) {
@@ -62,28 +74,39 @@ function nextDiagnostic(classification) {
62
74
  /** Per-task, deterministic recovery budget. Never replays actions or approvals. */
63
75
  export class TimeMachine {
64
76
  failures = new Map();
77
+ extended = new Set();
65
78
  reset() {
66
79
  this.failures.clear();
80
+ this.extended.clear();
81
+ }
82
+ /** The user approved attempts beyond the consent point for this issue, up to the hard maximum. */
83
+ grantExtension(issueKeyValue) {
84
+ const count = this.failures.get(issueKeyValue) ?? 0;
85
+ if (count >= TIME_MACHINE_CONSENT_AT && count < TIME_MACHINE_MAX_ATTEMPTS)
86
+ this.extended.add(issueKeyValue);
87
+ }
88
+ /** Whether the user already approved further attempts for this issue. */
89
+ isExtended(issueKeyValue) {
90
+ return this.extended.has(issueKeyValue);
67
91
  }
68
92
  observe(tool, args, result, outcomes = []) {
69
93
  const value = record(result);
70
94
  const failed = value.success === false || typeof value.error === 'string';
71
95
  const classification = failed ? failureClass(value) || 'failed' : '';
72
- const key = issueKey(tool, args, classification);
96
+ const key = issueKey(tool, args);
73
97
  const good = lastGoodTool(outcomes);
74
98
  if (!failed) {
75
99
  // A successful check only clears its own failure family. A successful
76
100
  // read/write cannot prove that a failing build or test was repaired.
77
- const possibleKeys = ['failed', 'exit_nonzero', 'syntax', 'invalid_args',
78
- 'not_found', 'timeout', 'network', 'rate_limited', 'permission'];
79
- const hadFailure = possibleKeys.some((item) => this.failures.has(issueKey(tool, args, item)));
101
+ const hadFailure = this.failures.has(key);
80
102
  if (hadFailure) {
81
- for (const item of possibleKeys)
82
- this.failures.delete(issueKey(tool, args, item));
103
+ this.failures.delete(key);
104
+ this.extended.delete(key);
83
105
  }
84
106
  return {
85
107
  kind: hadFailure ? 'resolved' : 'none', attempt: 0,
86
108
  maxAttempts: TIME_MACHINE_MAX_ATTEMPTS, failureClass: '',
109
+ issueKey: '',
87
110
  lastGoodTool: good,
88
111
  guidance: hadFailure
89
112
  ? isVerificationCommand(String(args.command || args.cmd || ''))
@@ -97,27 +120,39 @@ export class TimeMachine {
97
120
  const attempt = (this.failures.get(key) || 0) + 1;
98
121
  this.failures.set(key, attempt);
99
122
  const checkpoint = good ? ` Last successful tool: ${good}.` : '';
100
- if (value.failureKind === 'site_refusal' && attempt < TIME_MACHINE_MAX_ATTEMPTS) {
101
- return { kind: 'replan', attempt, maxAttempts: TIME_MACHINE_MAX_ATTEMPTS,
102
- failureClass: classification, lastGoodTool: good,
103
- guidance: `The site refused this fetch. Do not repeat the same URL or bypass the site's restriction. Search for another public source or use an already available browser capability.${checkpoint}` };
104
- }
105
123
  if (needsHuman) {
106
- return { kind: 'human', attempt, maxAttempts: TIME_MACHINE_MAX_ATTEMPTS,
124
+ return { kind: 'human', attempt, maxAttempts: TIME_MACHINE_MAX_ATTEMPTS, issueKey: key,
107
125
  failureClass: classification, lastGoodTool: good,
108
126
  guidance: `Permission or authentication is required. Stop retrying and explain the exact user action needed.${checkpoint}` };
109
127
  }
110
128
  if (attempt >= TIME_MACHINE_MAX_ATTEMPTS) {
111
- return { kind: 'stop', attempt, maxAttempts: TIME_MACHINE_MAX_ATTEMPTS,
129
+ return { kind: 'stop', attempt, maxAttempts: TIME_MACHINE_MAX_ATTEMPTS, issueKey: key,
112
130
  failureClass: classification, lastGoodTool: good,
113
131
  guidance: `The same failure class persisted through ${TIME_MACHINE_MAX_ATTEMPTS} attempts. Stop this task. Give a brief evidence-based report, state what remains unresolved, and ask for input only if needed. Put a detailed report in a Markdown file only if the user requests one.${checkpoint}` };
114
132
  }
115
- if (attempt >= TIME_MACHINE_REPLAN_AT) {
116
- return { kind: 'replan', attempt, maxAttempts: TIME_MACHINE_MAX_ATTEMPTS,
133
+ // The agent may spend three attempts alone. The fourth through sixth belong
134
+ // to the user: without an explicit grant the budget ends here.
135
+ if (attempt >= TIME_MACHINE_CONSENT_AT && !this.extended.has(key)) {
136
+ if (attempt === TIME_MACHINE_CONSENT_AT) {
137
+ return { kind: 'consent', attempt, maxAttempts: TIME_MACHINE_MAX_ATTEMPTS, issueKey: key,
138
+ failureClass: classification, lastGoodTool: good,
139
+ guidance: `Three attempts failed. Ask the user before trying again. If they allow it, change approach completely: review the last successful step and the failing evidence. ${nextDiagnostic(classification)}${checkpoint}` };
140
+ }
141
+ return { kind: 'stop', attempt, maxAttempts: TIME_MACHINE_MAX_ATTEMPTS, issueKey: key,
142
+ failureClass: classification, lastGoodTool: good,
143
+ guidance: `Further attempts were not approved. Stop this task. Give a brief evidence-based report and state what remains unresolved.${checkpoint}` };
144
+ }
145
+ if (value.failureKind === 'site_refusal' && attempt < TIME_MACHINE_MAX_ATTEMPTS) {
146
+ return { kind: 'replan', attempt, maxAttempts: TIME_MACHINE_MAX_ATTEMPTS, issueKey: key,
147
+ failureClass: classification, lastGoodTool: good,
148
+ guidance: `The site refused this fetch. Do not repeat the same URL or bypass the site's restriction. Search for another public source or use an already available browser capability.${checkpoint}` };
149
+ }
150
+ if (attempt >= TIME_MACHINE_CONSENT_AT) {
151
+ return { kind: 'replan', attempt, maxAttempts: TIME_MACHINE_MAX_ATTEMPTS, issueKey: key,
117
152
  failureClass: classification, lastGoodTool: good,
118
- guidance: `Review the last successful step and the failing evidence. ${nextDiagnostic(classification)} Change approach before another attempt; do not repeat the same command or claim a fix without a passing check.${checkpoint}` };
153
+ guidance: `Review the last successful step and the failing evidence. ${nextDiagnostic(classification)} Change approach before another attempt; do not repeat the same command or claim a fix without a passing check. ${TIME_MACHINE_MAX_ATTEMPTS - attempt} attempt(s) remain.${checkpoint}` };
119
154
  }
120
- return { kind: 'continue', attempt, maxAttempts: TIME_MACHINE_MAX_ATTEMPTS,
155
+ return { kind: 'continue', attempt, maxAttempts: TIME_MACHINE_MAX_ATTEMPTS, issueKey: key,
121
156
  failureClass: classification, lastGoodTool: good,
122
157
  guidance: `Inspect this failure before retrying. Attempt ${attempt}/${TIME_MACHINE_MAX_ATTEMPTS}.${checkpoint}` };
123
158
  }
@@ -3,21 +3,36 @@ import { failureClass } from './planCache.js';
3
3
  import { isVerificationCommand, type ToolOutcome } from './observer/evidence.js';
4
4
 
5
5
  export const TIME_MACHINE_MAX_ATTEMPTS = 6;
6
- export const TIME_MACHINE_REPLAN_AT = 3;
6
+ /**
7
+ * After this many failed attempts at the same issue the agent must stop and ask
8
+ * the user before trying again. Attempts beyond it are three more rounds of
9
+ * similar edits and checks, which cost real time and tokens, so they are the
10
+ * user's call and never the agent's.
11
+ */
12
+ export const TIME_MACHINE_CONSENT_AT = 3;
7
13
 
8
14
  export interface RecoveryDecision {
9
- kind: 'continue' | 'replan' | 'stop' | 'human' | 'resolved' | 'none';
15
+ /**
16
+ * `consent` means the attempt budget the agent may spend alone is used up:
17
+ * the caller must ask the user and call `grantExtension` only on approval.
18
+ */
19
+ kind: 'continue' | 'replan' | 'consent' | 'stop' | 'human' | 'resolved' | 'none';
10
20
  attempt: number;
11
21
  maxAttempts: number;
12
22
  failureClass: string;
13
23
  lastGoodTool: string | null;
14
24
  guidance: string;
25
+ /** Opaque identifier of the failing issue, for `grantExtension`. Empty when nothing failed. */
26
+ issueKey: string;
15
27
  }
16
28
 
17
29
  export function recoveryUserMessage(decision: RecoveryDecision, tool: string): string {
18
30
  if (decision.kind === 'human') {
19
31
  return `${tool} needs approval or authentication. Review the last tool error, then provide the needed access or choose another route. No success is claimed.`;
20
32
  }
33
+ if (decision.attempt <= TIME_MACHINE_CONSENT_AT && decision.kind === 'stop') {
34
+ return `${tool} failed ${decision.attempt} times (${decision.failureClass}) and more attempts were not approved. The task stopped without verified success.`;
35
+ }
21
36
  return `${tool} still failed after ${decision.attempt} attempts (${decision.failureClass}). The task stopped without verified success.`;
22
37
  }
23
38
 
@@ -44,9 +59,12 @@ function operationFamily(args: Record<string, unknown>): string {
44
59
  return (words[0] || '').replace(/^.*[\\/]/, '').toLowerCase().slice(0, 32);
45
60
  }
46
61
 
47
- function issueKey(tool: string, args: Record<string, unknown>, classification: string): string {
62
+ function issueKey(tool: string, args: Record<string, unknown>): string {
48
63
  const family = operationFamily(args);
49
- return createHash('sha256').update(`${tool}\0${family}\0${classification}`).digest('hex');
64
+ const target = String(args.path ?? args.file_path ?? args.filePath ?? '');
65
+ // Changing error text/class does not buy another three attempts at the same
66
+ // operation. Targets are hashed and never included in recovery messages.
67
+ return createHash('sha256').update(`${tool}\0${family}\0${target}`).digest('hex');
50
68
  }
51
69
 
52
70
  function lastGoodTool(outcomes: readonly ToolOutcome[]): string | null {
@@ -73,9 +91,22 @@ function nextDiagnostic(classification: string): string {
73
91
  /** Per-task, deterministic recovery budget. Never replays actions or approvals. */
74
92
  export class TimeMachine {
75
93
  private readonly failures = new Map<string, number>();
94
+ private readonly extended = new Set<string>();
76
95
 
77
96
  reset(): void {
78
97
  this.failures.clear();
98
+ this.extended.clear();
99
+ }
100
+
101
+ /** The user approved attempts beyond the consent point for this issue, up to the hard maximum. */
102
+ grantExtension(issueKeyValue: string): void {
103
+ const count = this.failures.get(issueKeyValue) ?? 0;
104
+ if (count >= TIME_MACHINE_CONSENT_AT && count < TIME_MACHINE_MAX_ATTEMPTS) this.extended.add(issueKeyValue);
105
+ }
106
+
107
+ /** Whether the user already approved further attempts for this issue. */
108
+ isExtended(issueKeyValue: string): boolean {
109
+ return this.extended.has(issueKeyValue);
79
110
  }
80
111
 
81
112
  observe(tool: string, args: Record<string, unknown>, result: unknown,
@@ -83,21 +114,21 @@ export class TimeMachine {
83
114
  const value = record(result);
84
115
  const failed = value.success === false || typeof value.error === 'string';
85
116
  const classification = failed ? failureClass(value) || 'failed' : '';
86
- const key = issueKey(tool, args, classification);
117
+ const key = issueKey(tool, args);
87
118
  const good = lastGoodTool(outcomes);
88
119
 
89
120
  if (!failed) {
90
121
  // A successful check only clears its own failure family. A successful
91
122
  // read/write cannot prove that a failing build or test was repaired.
92
- const possibleKeys = ['failed', 'exit_nonzero', 'syntax', 'invalid_args',
93
- 'not_found', 'timeout', 'network', 'rate_limited', 'permission'];
94
- const hadFailure = possibleKeys.some((item) => this.failures.has(issueKey(tool, args, item)));
123
+ const hadFailure = this.failures.has(key);
95
124
  if (hadFailure) {
96
- for (const item of possibleKeys) this.failures.delete(issueKey(tool, args, item));
125
+ this.failures.delete(key);
126
+ this.extended.delete(key);
97
127
  }
98
128
  return {
99
129
  kind: hadFailure ? 'resolved' : 'none', attempt: 0,
100
130
  maxAttempts: TIME_MACHINE_MAX_ATTEMPTS, failureClass: '',
131
+ issueKey: '',
101
132
  lastGoodTool: good,
102
133
  guidance: hadFailure
103
134
  ? isVerificationCommand(String(args.command || args.cmd || ''))
@@ -113,28 +144,41 @@ export class TimeMachine {
113
144
  this.failures.set(key, attempt);
114
145
  const checkpoint = good ? ` Last successful tool: ${good}.` : '';
115
146
 
116
- if (value.failureKind === 'site_refusal' && attempt < TIME_MACHINE_MAX_ATTEMPTS) {
117
- return { kind: 'replan', attempt, maxAttempts: TIME_MACHINE_MAX_ATTEMPTS,
118
- failureClass: classification, lastGoodTool: good,
119
- guidance: `The site refused this fetch. Do not repeat the same URL or bypass the site's restriction. Search for another public source or use an already available browser capability.${checkpoint}` };
120
- }
121
147
 
122
148
  if (needsHuman) {
123
- return { kind: 'human', attempt, maxAttempts: TIME_MACHINE_MAX_ATTEMPTS,
149
+ return { kind: 'human', attempt, maxAttempts: TIME_MACHINE_MAX_ATTEMPTS, issueKey: key,
124
150
  failureClass: classification, lastGoodTool: good,
125
151
  guidance: `Permission or authentication is required. Stop retrying and explain the exact user action needed.${checkpoint}` };
126
152
  }
127
153
  if (attempt >= TIME_MACHINE_MAX_ATTEMPTS) {
128
- return { kind: 'stop', attempt, maxAttempts: TIME_MACHINE_MAX_ATTEMPTS,
154
+ return { kind: 'stop', attempt, maxAttempts: TIME_MACHINE_MAX_ATTEMPTS, issueKey: key,
129
155
  failureClass: classification, lastGoodTool: good,
130
156
  guidance: `The same failure class persisted through ${TIME_MACHINE_MAX_ATTEMPTS} attempts. Stop this task. Give a brief evidence-based report, state what remains unresolved, and ask for input only if needed. Put a detailed report in a Markdown file only if the user requests one.${checkpoint}` };
131
157
  }
132
- if (attempt >= TIME_MACHINE_REPLAN_AT) {
133
- return { kind: 'replan', attempt, maxAttempts: TIME_MACHINE_MAX_ATTEMPTS,
158
+ // The agent may spend three attempts alone. The fourth through sixth belong
159
+ // to the user: without an explicit grant the budget ends here.
160
+ if (attempt >= TIME_MACHINE_CONSENT_AT && !this.extended.has(key)) {
161
+ if (attempt === TIME_MACHINE_CONSENT_AT) {
162
+ return { kind: 'consent', attempt, maxAttempts: TIME_MACHINE_MAX_ATTEMPTS, issueKey: key,
163
+ failureClass: classification, lastGoodTool: good,
164
+ guidance: `Three attempts failed. Ask the user before trying again. If they allow it, change approach completely: review the last successful step and the failing evidence. ${nextDiagnostic(classification)}${checkpoint}` };
165
+ }
166
+ return { kind: 'stop', attempt, maxAttempts: TIME_MACHINE_MAX_ATTEMPTS, issueKey: key,
167
+ failureClass: classification, lastGoodTool: good,
168
+ guidance: `Further attempts were not approved. Stop this task. Give a brief evidence-based report and state what remains unresolved.${checkpoint}` };
169
+ }
170
+ if (value.failureKind === 'site_refusal' && attempt < TIME_MACHINE_MAX_ATTEMPTS) {
171
+ return { kind: 'replan', attempt, maxAttempts: TIME_MACHINE_MAX_ATTEMPTS, issueKey: key,
172
+ failureClass: classification, lastGoodTool: good,
173
+ guidance: `The site refused this fetch. Do not repeat the same URL or bypass the site's restriction. Search for another public source or use an already available browser capability.${checkpoint}` };
174
+ }
175
+
176
+ if (attempt >= TIME_MACHINE_CONSENT_AT) {
177
+ return { kind: 'replan', attempt, maxAttempts: TIME_MACHINE_MAX_ATTEMPTS, issueKey: key,
134
178
  failureClass: classification, lastGoodTool: good,
135
- guidance: `Review the last successful step and the failing evidence. ${nextDiagnostic(classification)} Change approach before another attempt; do not repeat the same command or claim a fix without a passing check.${checkpoint}` };
179
+ guidance: `Review the last successful step and the failing evidence. ${nextDiagnostic(classification)} Change approach before another attempt; do not repeat the same command or claim a fix without a passing check. ${TIME_MACHINE_MAX_ATTEMPTS - attempt} attempt(s) remain.${checkpoint}` };
136
180
  }
137
- return { kind: 'continue', attempt, maxAttempts: TIME_MACHINE_MAX_ATTEMPTS,
181
+ return { kind: 'continue', attempt, maxAttempts: TIME_MACHINE_MAX_ATTEMPTS, issueKey: key,
138
182
  failureClass: classification, lastGoodTool: good,
139
183
  guidance: `Inspect this failure before retrying. Attempt ${attempt}/${TIME_MACHINE_MAX_ATTEMPTS}.${checkpoint}` };
140
184
  }