@causyne/agent 1.20.116 → 1.20.118

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 (59) hide show
  1. package/package.json +7 -2
  2. package/src/agentLoop.js +81 -31
  3. package/src/agentLoop.ts +82 -33
  4. package/src/browser/causyneBrowser.js +30 -7
  5. package/src/browser/causyneBrowser.ts +29 -7
  6. package/src/cliMode.js +24 -4
  7. package/src/commands.js +7 -1
  8. package/src/memory/scopedFacts.js +171 -0
  9. package/src/memory/scopedFacts.ts +214 -0
  10. package/src/memory.d.ts +13 -1
  11. package/src/memory.js +9 -12
  12. package/src/perception.js +124 -3
  13. package/src/perception.ts +128 -4
  14. package/src/planCache.js +17 -3
  15. package/src/planCache.ts +17 -3
  16. package/src/plugins/pluginManager.js +74 -0
  17. package/src/reporting.js +12 -4
  18. package/src/skillsManager.js +3 -2
  19. package/src/skillsManager.ts +3 -2
  20. package/src/smartToolsUse.js +4 -5
  21. package/src/smartToolsUse.ts +4 -6
  22. package/src/taskShape.js +49 -7
  23. package/src/taskShape.ts +55 -7
  24. package/src/toolPacks.js +27 -5
  25. package/src/toolPacks.ts +32 -5
  26. package/src/tools/memoryWrite.js +8 -10
  27. package/src/tools/memoryWrite.ts +13 -11
  28. package/src/tools/pluginManager.js +17 -2
  29. package/src/tui/chatRenderer.js +4 -1
  30. package/src/tui/codeProgress.js +3 -2
  31. package/src/tui/codeProgress.ts +3 -2
  32. package/src/tui/codeStreamRenderer.js +41 -15
  33. package/src/tui/codeStreamRenderer.ts +40 -15
  34. package/src/tui/composerControls.js +16 -3
  35. package/src/tui/composerControls.ts +14 -3
  36. package/src/tui/keys.js +3 -1
  37. package/src/tui/prompt.js +146 -16
  38. package/src/tui/scrollInteraction.js +2 -2
  39. package/src/tui/scrollInteraction.ts +2 -2
  40. package/src/tui/stageSurface.js +114 -4
  41. package/src/tui/turnRail.js +21 -14
  42. package/src/tui/turnRail.ts +19 -14
  43. package/src/tui/usageCard.js +164 -71
  44. package/src/tui/usageCard.ts +187 -96
  45. package/src/tui/workspaceSwitch.js +2 -0
  46. package/src/tui/workspaceSwitch.ts +1 -0
  47. package/src/types/contracts.ts +3 -0
  48. package/src/verification/boundedExplorer.js +119 -0
  49. package/src/verification/cliProbe.js +116 -0
  50. package/src/verification/featureMap.js +78 -0
  51. package/src/verification/interactivePty.js +188 -0
  52. package/src/verification/propertyProbe.js +121 -0
  53. package/src/verification/ptyProbe.js +125 -0
  54. package/src/verification/skillCatalog.d.ts +1 -0
  55. package/src/verification/skillCatalog.js +60 -0
  56. package/src/verification/statechart.js +143 -0
  57. package/src/verification/uiRuntime.js +57 -0
  58. package/src/verificationPlan.js +1 -1
  59. package/src/verificationPlan.ts +1 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@causyne/agent",
3
- "version": "1.20.116",
3
+ "version": "1.20.118",
4
4
  "description": "Agentic AI for software, tools, and computer workflows",
5
5
  "main": "bin/causyne.js",
6
6
  "type": "module",
@@ -32,7 +32,12 @@
32
32
  "typecheck": "tsc -p tsconfig.json",
33
33
  "typecheck:ts": "tsc -p tsconfig.strict.json",
34
34
  "typecheck:js-ratchet": "tsc -p tsconfig.js-ratchet.json",
35
- "typecheck:strict": "npm run typecheck:ts && npm run typecheck:js-ratchet"
35
+ "typecheck:strict": "npm run typecheck:ts && npm run typecheck:js-ratchet",
36
+ "verify:features": "node scripts/verify-features.mjs",
37
+ "verify:ui": "node scripts/verify-ui.mjs",
38
+ "verify:properties": "node --test --import ./tests/helpers/isolateState.js tests/boundedExplorer.test.ts tests/verificationPropertyProbe.test.ts",
39
+ "verify:statechart": "node scripts/verify-statechart.mjs",
40
+ "verify:tla": "node scripts/verify-tla.mjs"
36
41
  },
37
42
  "engines": {
38
43
  "node": ">=24.0.0"
package/src/agentLoop.js CHANGED
@@ -50,7 +50,7 @@ import { assessVerification } from './verificationPlan.js';
50
50
  import { SmartTools } from './SmartTools.js';
51
51
  import { decideTools, isDirectGameTask as isDirectGameTaskDecision } from './decideTools.js';
52
52
  import { SavedTools, readSavedTools, writeSavedTools } from './saveTools.js';
53
- import { resolveCharPool, measureMessages, resultCapFor, decayToolResults, buildWindow, compactInPlace, describeDroppedMessages, sanitizeSequences, applyProgressiveCompaction, snipOversizedToolOutputs } from './contextManager.js';
53
+ import { CHARS_PER_TOKEN, resolveCharPool, measureMessages, resultCapFor, decayToolResults, buildWindow, compactInPlace, describeDroppedMessages, sanitizeSequences, applyProgressiveCompaction, snipOversizedToolOutputs } from './contextManager.js';
54
54
  // Provider imports
55
55
  import { detectWorkspaceDomains, ensureSkillRepo, getSkillDomainHeader } from './skillsManager.js';
56
56
  import { spillToolResult, buildDecayPointer, pruneOutputStore } from './outputStore.js';
@@ -313,10 +313,10 @@ ${AGENT_USER_POLICY}
313
313
  # Project Conventions
314
314
  Follow the selected project's existing style and architecture. Check dependencies and tool schemas before use. Preserve unrelated behavior.
315
315
 
316
- # Greenfield Application Scaffolding vs. Legacy Codebase Exploration
317
- - When the user asks to CREATE or BUILD a new application, web page, 3D model, game, or tool from scratch (e.g., "buatkan", "create", "build", "make", "generate"), focus DIRECTLY on authoring the project in its designated project directory.
318
- - DO NOT perform exploratory directory listings of the root repository or inspect unrelated legacy projects in the workspace.
319
- - Immediately initialize the target directory and author the required implementation files (e.g. index.html, style.css, app.js).
316
+ # Repository Structure, Project Docs & Existing Codebases First
317
+ - When working inside an existing repository or project (indicated by Workspace Context key files, docs, build scripts, or subprojects), ALWAYS inspect the relevant project documentation (docs/, README.md), build scripts (scripts/, Makefile, package.json), and actual directory structure BEFORE modifying files or choosing a build/release command.
318
+ - Do NOT blindly initialize template web files (index.html, style.css, app.js) or assume a task is a greenfield web app unless the user explicitly requested a new web project from scratch AND the target directory has no matching existing build/architecture.
319
+ - Only skip root exploration when creating an explicitly requested brand-new greenfield project inside a dedicated new/empty directory.
320
320
 
321
321
  # Operational Guidelines & Communication
322
322
  - **Strict Mandatory English Only Directive**: Operate, reason, plan, and communicate STRICTLY and EXCLUSIVELY in the English language across all thoughts, plan steps, and responses, regardless of the language used in the user's prompt. The use of non-English languages (including Indonesian) is strictly and permanently forbidden anywhere in agent responses, plans, or thoughts.
@@ -704,6 +704,8 @@ export class AgentLoop {
704
704
  this.webVerificationScheduled = false;
705
705
  // P6: rendered surfaces this task wrote, for the anti-slop gate to read back.
706
706
  this.webArtifacts = new Set();
707
+ // Web files only read/grepped during exploration — never treated as written surfaces.
708
+ this.inspectedWebFiles = new Set();
707
709
  this.claimedLocalUrls = new Set();
708
710
  this.slopReviewAttempts = 0;
709
711
  this.slopLastAuditHash = '';
@@ -919,7 +921,7 @@ export class AgentLoop {
919
921
  const resolved = path.resolve(this.workspaceRoot, expanded);
920
922
  try {
921
923
  if (fsSync.existsSync(resolved) && fsSync.statSync(resolved).isFile()) {
922
- this.webArtifacts.add(resolved);
924
+ this.inspectedWebFiles.add(resolved);
923
925
  this.webVerificationState.htmlInspected = true;
924
926
  }
925
927
  }
@@ -1421,6 +1423,10 @@ export class AgentLoop {
1421
1423
  }
1422
1424
  }
1423
1425
  updateImplementationPlan(update, options = {}) {
1426
+ // A malformed provider plan is not permission to replace a valid plan or
1427
+ // crash an active run. Empty arrays remain valid and can clear the plan.
1428
+ if (!update || !Array.isArray(update.plan))
1429
+ return;
1424
1430
  const nextPlan = update.plan.map((item) => ({ ...item }));
1425
1431
  const prevText = this._implementationPlan.map((item) => item.step).join('\n');
1426
1432
  const prevKey = JSON.stringify(this._implementationPlan.map((item) => ({ id: item.id, step: item.step, status: item.status })));
@@ -1857,6 +1863,7 @@ export class AgentLoop {
1857
1863
  this._verificationPlanFired = false;
1858
1864
  this.webVerificationState = { screenshotTaken: false, browserActUsed: false, htmlInspected: false };
1859
1865
  this.webArtifacts = new Set();
1866
+ this.inspectedWebFiles = new Set();
1860
1867
  this.claimedLocalUrls = new Set();
1861
1868
  this.slopReviewAttempts = 0;
1862
1869
  this.slopLastAuditHash = '';
@@ -1940,7 +1947,11 @@ export class AgentLoop {
1940
1947
  this.seedTaskPhasePlanIfEmpty();
1941
1948
  if (!this.isInitialized) {
1942
1949
  const activeTier = this.activeTier;
1943
- const charPoolLimit = resolveCharPool(activeTier, this.config.maxCharPool);
1950
+ const charPoolLimit = resolveCharPool(activeTier, this.config.maxCharPool, {
1951
+ provider: this.config.provider,
1952
+ model: this.config.model,
1953
+ overrideTokens: this.config.contextTokens || this.config.maxContextTokens
1954
+ });
1944
1955
  const devTag = isDevEmulator(this.config) ? ' (dev emulator)' : '';
1945
1956
  // Was a console.log carrying a hardcoded \x1b[1m\x1b[36m, which ignored
1946
1957
  // NO_COLOR outright. The renderer paints this through the theme.
@@ -2170,7 +2181,11 @@ export class AgentLoop {
2170
2181
  // tool payloads decay into stubs, and anything amputated is physically
2171
2182
  // replaced by a summary, so memory, disk and CPU all stay bounded.
2172
2183
  const activeTier = isDevEmulator(this.config) ? 'super_max' : (this.config.tier || 'premium');
2173
- const MAX_CHAR_POOL = resolveCharPool(activeTier, this.config.maxCharPool);
2184
+ const MAX_CHAR_POOL = resolveCharPool(activeTier, this.config.maxCharPool, {
2185
+ provider: this.config.provider,
2186
+ model: this.config.model,
2187
+ overrideTokens: this.config.contextTokens || this.config.maxContextTokens
2188
+ });
2174
2189
  // 5-Stage Progressive Compaction (Claude Code Architecture / Research Section E):
2175
2190
  // Stage 0 (HLCE Ephemeral Decay) + Stage 2 (Snip >15K tokens / 60K chars) +
2176
2191
  // Stage 1 (Budget Reduction >70%) + Stage 3 (Microcompact) + Stage 4 (Context Collapse >85%)
@@ -2300,7 +2315,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
2300
2315
  4. Perform thorough code inspection of generated math, physics, and canvas render loops to ensure zero defects.
2301
2316
  - For non-visual tasks (backend, CLI, algorithms): Verify using standard test suites and execution logs.`;
2302
2317
  const providerPrompt = `${baseProviderPrompt}${sensoryAwareness}`;
2303
- const memoryContext = getMemoryContextString();
2318
+ const memoryContext = getMemoryContextString({ workspaceRoot: this.workspaceRoot });
2304
2319
  // --- PER-TASK STATIC CONTEXT (computed once, not once per step) ---
2305
2320
  // Cortex retrieval, design detection, creative-pattern lookup and the
2306
2321
  // workspace domain scan are all constant for the duration of a task, but
@@ -2328,11 +2343,15 @@ You are operating in a text-and-code modality without direct image pixel renderi
2328
2343
  ctx.packageManager && `Package manager: ${ctx.packageManager}`,
2329
2344
  ctx.gitBranch && `Git branch: ${ctx.gitBranch}`,
2330
2345
  ctx.gitStatus && `Git status: ${ctx.gitStatus}`,
2346
+ Array.isArray(ctx.topEntries) && ctx.topEntries.length > 0 && `Top-level layout: ${ctx.topEntries.slice(0, 20).join(', ')}`,
2347
+ Array.isArray(ctx.subprojectStacks) && ctx.subprojectStacks.length > 0 && `Detected stacks: ${ctx.subprojectStacks.join(', ')}`,
2331
2348
  Array.isArray(ctx.subprojects) && ctx.subprojects.length > 0 && `Subprojects in workspace: ${ctx.subprojects.join(', ')}`,
2349
+ Array.isArray(ctx.docFiles) && ctx.docFiles.length > 0 && `Project docs (read relevant docs before guessing conventions): ${ctx.docFiles.slice(0, 15).join(', ')}`,
2350
+ Array.isArray(ctx.buildFiles) && ctx.buildFiles.length > 0 && `Build & config files: ${ctx.buildFiles.slice(0, 15).join(', ')}`,
2332
2351
  Array.isArray(ctx.keyFiles) && ctx.keyFiles.length > 0 && `Key files: ${ctx.keyFiles.slice(0, 25).join(', ')}`
2333
2352
  ].filter(Boolean);
2334
2353
  if (facts.length > 0) {
2335
- workspaceSummary = `\n\n◆ WORKSPACE CONTEXT (already scanned for you — do NOT waste steps rediscovering this):\n${facts.join('\n')}`;
2354
+ workspaceSummary = `\n\n◆ WORKSPACE CONTEXT (scanned on disk — verify docs/build scripts directly and treat repository files as authoritative):\n${facts.join('\n')}`;
2336
2355
  }
2337
2356
  }
2338
2357
  // --- PROMPT ASSEMBLY, ORDERED STABLE → VOLATILE ---
@@ -2438,7 +2457,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
2438
2457
  // here never invalidates the cached prefix in [1]-[3].
2439
2458
  {
2440
2459
  role: 'system',
2441
- content: `${uncertaintyDirective ? uncertaintyDirective + '\n\n' : ''}${describeSession(this.taskId)}CURRENT AUTONOMY MODE: ${autonomyMode}\nALLOWED WORKSPACE PATHS: ${allowedPaths}\n(You MUST NOT write files outside these paths!)\n\n◆ PERSISTENT MEMORY (FACTS LEARNED ABOUT THE USER):\n${memoryContext}`
2460
+ content: `${uncertaintyDirective ? uncertaintyDirective + '\n\n' : ''}${describeSession(this.taskId)}CURRENT AUTONOMY MODE: ${autonomyMode}\nALLOWED WORKSPACE PATHS: ${allowedPaths}\n(You MUST NOT write files outside these paths!)${memoryContext ? `\n\n◆ PERSISTENT MEMORY (workspace-relevant notes — actual repository files and docs on disk always override memory if anything conflicts):\n${memoryContext}` : ''}`
2442
2461
  }
2443
2462
  ];
2444
2463
  // Dev-only visibility into what fills each step's prompt. Set
@@ -2545,6 +2564,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
2545
2564
  let nativeMutationCount = 0;
2546
2565
  let nativeExplorationCount = 0;
2547
2566
  const completedNativeActionIds = new Set();
2567
+ const seenNativePlanActionIds = new Set();
2548
2568
  const observedNativeTerminalIds = new Set();
2549
2569
  const finalizeReasoningSegment = () => {
2550
2570
  if (!segmentReasoning)
@@ -2677,6 +2697,9 @@ You are operating in a text-and-code modality without direct image pixel renderi
2677
2697
  const actionPlan = normalizePeerPlanEntries(action.parameters);
2678
2698
  if (actionPlan) {
2679
2699
  hasStructuredToolPlan = true;
2700
+ if (action.id)
2701
+ seenNativePlanActionIds.add(String(action.id));
2702
+ seenNativePlanActionIds.add(JSON.stringify(actionPlan));
2680
2703
  this.updateImplementationPlan(actionPlan);
2681
2704
  }
2682
2705
  const isChecklistTool = Boolean(actionPlan) || ['todowrite', 'todo_write', 'update_plan'].includes(action.name.toLowerCase());
@@ -2753,7 +2776,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
2753
2776
  const lowerName = action.name.toLowerCase();
2754
2777
  const rawDetail = String(action.detail || '');
2755
2778
  const lowerDetail = rawDetail.toLowerCase();
2756
- if (['fs_write', 'fs_edit', 'write_file', 'edit_file', 'write', 'edit', 'replace_file_content'].includes(lowerName)
2779
+ if (['fs_write', 'fs_edit', 'write_file', 'edit_file', 'write', 'edit', 'multiedit', 'multi_edit', 'write_to_file', 'replace_file_content', 'multi_replace_file_content'].includes(lowerName)
2757
2780
  || isNativeMutation(action.name, actionArgs)) {
2758
2781
  nativeMutationCount++;
2759
2782
  taskMutationCount++;
@@ -2851,15 +2874,18 @@ You are operating in a text-and-code modality without direct image pixel renderi
2851
2874
  if (this._pendingConsent) {
2852
2875
  throw Object.assign(new RetryConsentCheckpoint(), { partialUsage: response.usage });
2853
2876
  }
2854
- // The call came back. Whatever went wrong before is no longer
2855
- // consecutive — without this reset, one failure at step 2 and another
2856
- // at step 200 would count toward the same ceiling and stop a task that
2857
- // was working perfectly well.
2858
- this.consecutiveFailures = 0;
2859
- this.lastFailureType = null;
2860
2877
  // Track tokens. usage carries cachedPromptTokens / cacheWriteTokens so
2861
2878
  // the cost estimate reflects the real cache-discounted bill.
2862
- const tracking = await this.tokenTracker.trackUsage(response.usage.promptTokens, response.usage.completionTokens, (msg) => this.emitEvent({ type: 'budget_warning', message: msg }), response.usage);
2879
+ const rawUsage = response?.usage && typeof response.usage === 'object' ? response.usage : undefined;
2880
+ const normalizedUsage = rawUsage
2881
+ ? {
2882
+ ...rawUsage,
2883
+ promptTokens: Number.isFinite(Number(rawUsage.promptTokens)) ? Math.max(0, Number(rawUsage.promptTokens)) : 0,
2884
+ completionTokens: Number.isFinite(Number(rawUsage.completionTokens)) ? Math.max(0, Number(rawUsage.completionTokens)) : 0,
2885
+ cachedPromptTokens: Number.isFinite(Number(rawUsage.cachedPromptTokens)) ? Math.max(0, Number(rawUsage.cachedPromptTokens)) : 0
2886
+ }
2887
+ : { promptTokens: 0, completionTokens: 0, cachedPromptTokens: 0 };
2888
+ const tracking = await this.tokenTracker.trackUsage(normalizedUsage.promptTokens, normalizedUsage.completionTokens, (msg) => this.emitEvent({ type: 'budget_warning', message: msg }), normalizedUsage);
2863
2889
  // Private numeric telemetry only. The daily ledger aggregates calls,
2864
2890
  // so it cannot attribute usage to a task or distinguish provider data
2865
2891
  // from the character-count fallback used by some ACP peers.
@@ -2867,17 +2893,17 @@ You are operating in a text-and-code modality without direct image pixel renderi
2867
2893
  event: 'model_usage', scope: 'agent_loop_primary',
2868
2894
  taskId: this.taskId, step: this.stepsCompleted,
2869
2895
  provider: this.config.provider || 'unknown',
2870
- promptTokens: response.usage.promptTokens,
2871
- completionTokens: response.usage.completionTokens,
2872
- cachedPromptTokens: response.usage.cachedPromptTokens || 0,
2873
- uncachedPromptTokens: response.usage.uncachedPromptTokens,
2874
- noncachedTokens: noncachedTokens(response.usage),
2875
- measurement: response.usage.measurement || 'unspecified',
2876
- measurementScope: response.usage.measurementScope || 'unspecified',
2877
- cacheMeasurement: response.usage.cacheMeasurement || 'unspecified',
2896
+ promptTokens: normalizedUsage.promptTokens,
2897
+ completionTokens: normalizedUsage.completionTokens,
2898
+ cachedPromptTokens: normalizedUsage.cachedPromptTokens,
2899
+ uncachedPromptTokens: rawUsage?.uncachedPromptTokens,
2900
+ noncachedTokens: noncachedTokens(normalizedUsage),
2901
+ measurement: rawUsage?.measurement || 'unspecified',
2902
+ measurementScope: rawUsage?.measurementScope || 'unspecified',
2903
+ cacheMeasurement: rawUsage?.cacheMeasurement || 'unspecified',
2878
2904
  costBasis: /^(acp(?:\/|$)|antigravity$|agy$)/i.test(String(this.config.provider || ''))
2879
2905
  ? 'external_subscription_unavailable' : 'rate_card_estimate',
2880
- callEstimatedCostUsd: this.tokenTracker.calculateCost(response.usage.promptTokens, response.usage.completionTokens, response.usage)
2906
+ callEstimatedCostUsd: this.tokenTracker.calculateCost(normalizedUsage.promptTokens, normalizedUsage.completionTokens, normalizedUsage)
2881
2907
  });
2882
2908
  // Soft advisory only; repeated status frames must not consume tokens or stop work.
2883
2909
  if (isAntigravityPeer(this.config.provider) && !hardBudget && !softUsageNoticeIssued
@@ -2886,10 +2912,14 @@ You are operating in a text-and-code modality without direct image pixel renderi
2886
2912
  this.emitEvent({ type: 'notice', message: `Task usage passed ${DEFAULT_AGY_TASK_TOKENS.toLocaleString()} fresh tokens. This is an advisory, not a stop. Use /stop or set a user hard budget to limit further calls.` });
2887
2913
  auditLog.log({ event: 'task_usage_advisory', taskId: this.taskId, freshTokens: this.tokenTracker.taskTokens });
2888
2914
  }
2889
- const cachedTokens = response.usage.cachedPromptTokens || 0;
2915
+ const cachedTokens = normalizedUsage.cachedPromptTokens;
2890
2916
  if (cachedTokens > 0) {
2891
- this.debugLog(`prompt cache hit: ${cachedTokens.toLocaleString()} of ${response.usage.promptTokens.toLocaleString()} input tokens served from cache`);
2917
+ this.debugLog(`prompt cache hit: ${cachedTokens.toLocaleString()} of ${normalizedUsage.promptTokens.toLocaleString()} input tokens served from cache`);
2892
2918
  }
2919
+ // Reset retry state only after response metadata and token accounting succeed
2920
+ // so an internal post-response exception cannot spin infinitely on retry 1 of 3.
2921
+ this.consecutiveFailures = 0;
2922
+ this.lastFailureType = null;
2893
2923
  //
2894
2924
  // ALWAYS read (AgentViewModel: `optInt("dailyTokens", optInt("usedTokens",
2895
2925
  // — which this frame set to the TASK total. The card therefore drew task
@@ -2900,6 +2930,16 @@ You are operating in a text-and-code modality without direct image pixel renderi
2900
2930
  // the window is actually budgeted in. The renderer converts once, using
2901
2931
  // the project's own CHAR_POOLS convention, instead of comparing a token
2902
2932
  // count to a character limit.
2933
+ const reportedPromptTokens = Number(response.usage?.promptTokens || 0);
2934
+ if (response.usage?.measurement === 'provider_reported'
2935
+ && response.usage?.measurementScope !== 'cumulative'
2936
+ && Number.isFinite(reportedPromptTokens)
2937
+ && reportedPromptTokens > 0) {
2938
+ const reportedContextChars = Math.round(reportedPromptTokens * CHARS_PER_TOKEN);
2939
+ if (reportedContextChars > (this._contextChars || 0)) {
2940
+ this._contextChars = reportedContextChars;
2941
+ }
2942
+ }
2903
2943
  this.emitEvent({
2904
2944
  type: 'usage_update',
2905
2945
  usedTokens: tracking.dailyTokens || 0,
@@ -3124,7 +3164,14 @@ You are operating in a text-and-code modality without direct image pixel renderi
3124
3164
  const extPlan = normalizePeerPlanEntries(extAction.parameters);
3125
3165
  if (extPlan) {
3126
3166
  hasStructuredToolPlan = true;
3127
- this.updateImplementationPlan(extPlan);
3167
+ const extActionId = extAction.id ? String(extAction.id) : '';
3168
+ const extPlanKey = JSON.stringify(extPlan);
3169
+ if (!(extActionId && seenNativePlanActionIds.has(extActionId)) && !seenNativePlanActionIds.has(extPlanKey)) {
3170
+ seenNativePlanActionIds.add(extPlanKey);
3171
+ if (extActionId)
3172
+ seenNativePlanActionIds.add(extActionId);
3173
+ this.updateImplementationPlan(extPlan);
3174
+ }
3128
3175
  }
3129
3176
  const actionName = String(extAction.name || '').toLowerCase();
3130
3177
  const detailPath = typeof extAction.detail === 'string' ? extAction.detail.trim() : '';
@@ -5006,6 +5053,9 @@ You are operating in a text-and-code modality without direct image pixel renderi
5006
5053
  if (msg.includes('kill') || msg.includes('abort') || msg.includes('signal') || msg.includes('fatal')) {
5007
5054
  return 'fatal';
5008
5055
  }
5056
+ if (error instanceof TypeError || error instanceof ReferenceError || error instanceof RangeError) {
5057
+ return 'fatal';
5058
+ }
5009
5059
  return 'unknown_error';
5010
5060
  }
5011
5061
  // V5: Provide actionable retry hints per error type
package/src/agentLoop.ts CHANGED
@@ -80,6 +80,7 @@ import type { DecideToolsInput } from './decideTools.js';
80
80
  import { SavedTools, readSavedTools, writeSavedTools } from './saveTools.js';
81
81
  import type { AdmissionResult } from './saveTools.js';
82
82
  import {
83
+ CHARS_PER_TOKEN,
83
84
  resolveCharPool,
84
85
  measureMessages,
85
86
  resultCapFor,
@@ -394,10 +395,10 @@ ${AGENT_USER_POLICY}
394
395
  # Project Conventions
395
396
  Follow the selected project's existing style and architecture. Check dependencies and tool schemas before use. Preserve unrelated behavior.
396
397
 
397
- # Greenfield Application Scaffolding vs. Legacy Codebase Exploration
398
- - When the user asks to CREATE or BUILD a new application, web page, 3D model, game, or tool from scratch (e.g., "buatkan", "create", "build", "make", "generate"), focus DIRECTLY on authoring the project in its designated project directory.
399
- - DO NOT perform exploratory directory listings of the root repository or inspect unrelated legacy projects in the workspace.
400
- - Immediately initialize the target directory and author the required implementation files (e.g. index.html, style.css, app.js).
398
+ # Repository Structure, Project Docs & Existing Codebases First
399
+ - When working inside an existing repository or project (indicated by Workspace Context key files, docs, build scripts, or subprojects), ALWAYS inspect the relevant project documentation (docs/, README.md), build scripts (scripts/, Makefile, package.json), and actual directory structure BEFORE modifying files or choosing a build/release command.
400
+ - Do NOT blindly initialize template web files (index.html, style.css, app.js) or assume a task is a greenfield web app unless the user explicitly requested a new web project from scratch AND the target directory has no matching existing build/architecture.
401
+ - Only skip root exploration when creating an explicitly requested brand-new greenfield project inside a dedicated new/empty directory.
401
402
 
402
403
  # Operational Guidelines & Communication
403
404
  - **Strict Mandatory English Only Directive**: Operate, reason, plan, and communicate STRICTLY and EXCLUSIVELY in the English language across all thoughts, plan steps, and responses, regardless of the language used in the user's prompt. The use of non-English languages (including Indonesian) is strictly and permanently forbidden anywhere in agent responses, plans, or thoughts.
@@ -805,6 +806,8 @@ export class AgentLoop {
805
806
  this.webVerificationScheduled = false;
806
807
  // P6: rendered surfaces this task wrote, for the anti-slop gate to read back.
807
808
  this.webArtifacts = new Set();
809
+ // Web files only read/grepped during exploration — never treated as written surfaces.
810
+ this.inspectedWebFiles = new Set();
808
811
  this.claimedLocalUrls = new Set();
809
812
  this.slopReviewAttempts = 0;
810
813
  this.slopLastAuditHash = '';
@@ -1030,7 +1033,7 @@ export class AgentLoop {
1030
1033
  const resolved = path.resolve(this.workspaceRoot, expanded);
1031
1034
  try {
1032
1035
  if (fsSync.existsSync(resolved) && fsSync.statSync(resolved).isFile()) {
1033
- this.webArtifacts.add(resolved);
1036
+ this.inspectedWebFiles.add(resolved);
1034
1037
  this.webVerificationState.htmlInspected = true;
1035
1038
  }
1036
1039
  } catch {
@@ -1506,6 +1509,9 @@ export class AgentLoop {
1506
1509
  }
1507
1510
 
1508
1511
  updateImplementationPlan(update: any, options: { seeded?: boolean } = {}) {
1512
+ // A malformed provider plan is not permission to replace a valid plan or
1513
+ // crash an active run. Empty arrays remain valid and can clear the plan.
1514
+ if (!update || !Array.isArray(update.plan)) return;
1509
1515
  const nextPlan = update.plan.map((item: any) => ({ ...item }));
1510
1516
  const prevText = this._implementationPlan.map((item: any) => item.step).join('\n');
1511
1517
  const prevKey = JSON.stringify(this._implementationPlan.map((item: any) => ({ id: item.id, step: item.step, status: item.status })));
@@ -1915,6 +1921,7 @@ export class AgentLoop {
1915
1921
  this._verificationPlanFired = false;
1916
1922
  this.webVerificationState = { screenshotTaken: false, browserActUsed: false, htmlInspected: false };
1917
1923
  this.webArtifacts = new Set();
1924
+ this.inspectedWebFiles = new Set();
1918
1925
  this.claimedLocalUrls = new Set();
1919
1926
  this.slopReviewAttempts = 0;
1920
1927
  this.slopLastAuditHash = '';
@@ -2006,7 +2013,11 @@ export class AgentLoop {
2006
2013
 
2007
2014
  if (!this.isInitialized) {
2008
2015
  const activeTier = this.activeTier;
2009
- const charPoolLimit = resolveCharPool(activeTier, this.config.maxCharPool);
2016
+ const charPoolLimit = resolveCharPool(activeTier, this.config.maxCharPool, {
2017
+ provider: this.config.provider,
2018
+ model: this.config.model,
2019
+ overrideTokens: this.config.contextTokens || this.config.maxContextTokens
2020
+ });
2010
2021
  const devTag = isDevEmulator(this.config) ? ' (dev emulator)' : '';
2011
2022
  // Was a console.log carrying a hardcoded \x1b[1m\x1b[36m, which ignored
2012
2023
  // NO_COLOR outright. The renderer paints this through the theme.
@@ -2246,7 +2257,11 @@ export class AgentLoop {
2246
2257
  // replaced by a summary, so memory, disk and CPU all stay bounded.
2247
2258
 
2248
2259
  const activeTier = isDevEmulator(this.config) ? 'super_max' : (this.config.tier || 'premium');
2249
- const MAX_CHAR_POOL = resolveCharPool(activeTier, this.config.maxCharPool);
2260
+ const MAX_CHAR_POOL = resolveCharPool(activeTier, this.config.maxCharPool, {
2261
+ provider: this.config.provider,
2262
+ model: this.config.model,
2263
+ overrideTokens: this.config.contextTokens || this.config.maxContextTokens
2264
+ });
2250
2265
 
2251
2266
  // 5-Stage Progressive Compaction (Claude Code Architecture / Research Section E):
2252
2267
  // Stage 0 (HLCE Ephemeral Decay) + Stage 2 (Snip >15K tokens / 60K chars) +
@@ -2383,7 +2398,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
2383
2398
  4. Perform thorough code inspection of generated math, physics, and canvas render loops to ensure zero defects.
2384
2399
  - For non-visual tasks (backend, CLI, algorithms): Verify using standard test suites and execution logs.`;
2385
2400
  const providerPrompt = `${baseProviderPrompt}${sensoryAwareness}`;
2386
- const memoryContext = getMemoryContextString();
2401
+ const memoryContext = getMemoryContextString({ workspaceRoot: this.workspaceRoot });
2387
2402
 
2388
2403
  // --- PER-TASK STATIC CONTEXT (computed once, not once per step) ---
2389
2404
  // Cortex retrieval, design detection, creative-pattern lookup and the
@@ -2413,11 +2428,15 @@ You are operating in a text-and-code modality without direct image pixel renderi
2413
2428
  ctx.packageManager && `Package manager: ${ctx.packageManager}`,
2414
2429
  ctx.gitBranch && `Git branch: ${ctx.gitBranch}`,
2415
2430
  ctx.gitStatus && `Git status: ${ctx.gitStatus}`,
2431
+ Array.isArray(ctx.topEntries) && ctx.topEntries.length > 0 && `Top-level layout: ${ctx.topEntries.slice(0, 20).join(', ')}`,
2432
+ Array.isArray(ctx.subprojectStacks) && ctx.subprojectStacks.length > 0 && `Detected stacks: ${ctx.subprojectStacks.join(', ')}`,
2416
2433
  Array.isArray(ctx.subprojects) && ctx.subprojects.length > 0 && `Subprojects in workspace: ${ctx.subprojects.join(', ')}`,
2434
+ Array.isArray(ctx.docFiles) && ctx.docFiles.length > 0 && `Project docs (read relevant docs before guessing conventions): ${ctx.docFiles.slice(0, 15).join(', ')}`,
2435
+ Array.isArray(ctx.buildFiles) && ctx.buildFiles.length > 0 && `Build & config files: ${ctx.buildFiles.slice(0, 15).join(', ')}`,
2417
2436
  Array.isArray(ctx.keyFiles) && ctx.keyFiles.length > 0 && `Key files: ${ctx.keyFiles.slice(0, 25).join(', ')}`
2418
2437
  ].filter(Boolean);
2419
2438
  if (facts.length > 0) {
2420
- workspaceSummary = `\n\n◆ WORKSPACE CONTEXT (already scanned for you — do NOT waste steps rediscovering this):\n${facts.join('\n')}`;
2439
+ workspaceSummary = `\n\n◆ WORKSPACE CONTEXT (scanned on disk — verify docs/build scripts directly and treat repository files as authoritative):\n${facts.join('\n')}`;
2421
2440
  }
2422
2441
  }
2423
2442
 
@@ -2531,7 +2550,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
2531
2550
  // here never invalidates the cached prefix in [1]-[3].
2532
2551
  {
2533
2552
  role: 'system',
2534
- content: `${uncertaintyDirective ? uncertaintyDirective + '\n\n' : ''}${describeSession(this.taskId)}CURRENT AUTONOMY MODE: ${autonomyMode}\nALLOWED WORKSPACE PATHS: ${allowedPaths}\n(You MUST NOT write files outside these paths!)\n\n◆ PERSISTENT MEMORY (FACTS LEARNED ABOUT THE USER):\n${memoryContext}`
2553
+ content: `${uncertaintyDirective ? uncertaintyDirective + '\n\n' : ''}${describeSession(this.taskId)}CURRENT AUTONOMY MODE: ${autonomyMode}\nALLOWED WORKSPACE PATHS: ${allowedPaths}\n(You MUST NOT write files outside these paths!)${memoryContext ? `\n\n◆ PERSISTENT MEMORY (workspace-relevant notes — actual repository files and docs on disk always override memory if anything conflicts):\n${memoryContext}` : ''}`
2535
2554
  }
2536
2555
  ];
2537
2556
 
@@ -2646,6 +2665,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
2646
2665
  let nativeMutationCount = 0;
2647
2666
  let nativeExplorationCount = 0;
2648
2667
  const completedNativeActionIds = new Set<string>();
2668
+ const seenNativePlanActionIds = new Set<string>();
2649
2669
  const observedNativeTerminalIds = new Set<string>();
2650
2670
  const finalizeReasoningSegment = (): void => {
2651
2671
  if (!segmentReasoning) return;
@@ -2772,6 +2792,8 @@ You are operating in a text-and-code modality without direct image pixel renderi
2772
2792
  const actionPlan = normalizePeerPlanEntries(action.parameters);
2773
2793
  if (actionPlan) {
2774
2794
  hasStructuredToolPlan = true;
2795
+ if (action.id) seenNativePlanActionIds.add(String(action.id));
2796
+ seenNativePlanActionIds.add(JSON.stringify(actionPlan));
2775
2797
  this.updateImplementationPlan(actionPlan);
2776
2798
  }
2777
2799
  const isChecklistTool = Boolean(actionPlan) || ['todowrite', 'todo_write', 'update_plan'].includes(action.name.toLowerCase());
@@ -2843,7 +2865,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
2843
2865
  const lowerName = action.name.toLowerCase();
2844
2866
  const rawDetail = String(action.detail || '');
2845
2867
  const lowerDetail = rawDetail.toLowerCase();
2846
- if (['fs_write', 'fs_edit', 'write_file', 'edit_file', 'write', 'edit', 'replace_file_content'].includes(lowerName)
2868
+ if (['fs_write', 'fs_edit', 'write_file', 'edit_file', 'write', 'edit', 'multiedit', 'multi_edit', 'write_to_file', 'replace_file_content', 'multi_replace_file_content'].includes(lowerName)
2847
2869
  || isNativeMutation(action.name, actionArgs)) {
2848
2870
  nativeMutationCount++;
2849
2871
  taskMutationCount++;
@@ -2944,20 +2966,23 @@ You are operating in a text-and-code modality without direct image pixel renderi
2944
2966
  throw Object.assign(new RetryConsentCheckpoint(), { partialUsage: response.usage });
2945
2967
  }
2946
2968
 
2947
- // The call came back. Whatever went wrong before is no longer
2948
- // consecutive — without this reset, one failure at step 2 and another
2949
- // at step 200 would count toward the same ceiling and stop a task that
2950
- // was working perfectly well.
2951
- this.consecutiveFailures = 0;
2952
- this.lastFailureType = null;
2953
-
2954
2969
  // Track tokens. usage carries cachedPromptTokens / cacheWriteTokens so
2955
2970
  // the cost estimate reflects the real cache-discounted bill.
2971
+ const rawUsage = response?.usage && typeof response.usage === 'object' ? response.usage : undefined;
2972
+ const normalizedUsage = rawUsage
2973
+ ? {
2974
+ ...rawUsage,
2975
+ promptTokens: Number.isFinite(Number(rawUsage.promptTokens)) ? Math.max(0, Number(rawUsage.promptTokens)) : 0,
2976
+ completionTokens: Number.isFinite(Number(rawUsage.completionTokens)) ? Math.max(0, Number(rawUsage.completionTokens)) : 0,
2977
+ cachedPromptTokens: Number.isFinite(Number(rawUsage.cachedPromptTokens)) ? Math.max(0, Number(rawUsage.cachedPromptTokens)) : 0
2978
+ }
2979
+ : { promptTokens: 0, completionTokens: 0, cachedPromptTokens: 0 };
2980
+
2956
2981
  const tracking = await this.tokenTracker.trackUsage(
2957
- response.usage.promptTokens,
2958
- response.usage.completionTokens,
2982
+ normalizedUsage.promptTokens,
2983
+ normalizedUsage.completionTokens,
2959
2984
  (msg: string) => this.emitEvent({ type: 'budget_warning', message: msg }),
2960
- response.usage
2985
+ normalizedUsage
2961
2986
  );
2962
2987
 
2963
2988
  // Private numeric telemetry only. The daily ledger aggregates calls,
@@ -2967,18 +2992,18 @@ You are operating in a text-and-code modality without direct image pixel renderi
2967
2992
  event: 'model_usage', scope: 'agent_loop_primary',
2968
2993
  taskId: this.taskId, step: this.stepsCompleted,
2969
2994
  provider: this.config.provider || 'unknown',
2970
- promptTokens: response.usage.promptTokens,
2971
- completionTokens: response.usage.completionTokens,
2972
- cachedPromptTokens: response.usage.cachedPromptTokens || 0,
2973
- uncachedPromptTokens: response.usage.uncachedPromptTokens,
2974
- noncachedTokens: noncachedTokens(response.usage),
2975
- measurement: response.usage.measurement || 'unspecified',
2976
- measurementScope: response.usage.measurementScope || 'unspecified',
2977
- cacheMeasurement: response.usage.cacheMeasurement || 'unspecified',
2995
+ promptTokens: normalizedUsage.promptTokens,
2996
+ completionTokens: normalizedUsage.completionTokens,
2997
+ cachedPromptTokens: normalizedUsage.cachedPromptTokens,
2998
+ uncachedPromptTokens: rawUsage?.uncachedPromptTokens,
2999
+ noncachedTokens: noncachedTokens(normalizedUsage),
3000
+ measurement: rawUsage?.measurement || 'unspecified',
3001
+ measurementScope: rawUsage?.measurementScope || 'unspecified',
3002
+ cacheMeasurement: rawUsage?.cacheMeasurement || 'unspecified',
2978
3003
  costBasis: /^(acp(?:\/|$)|antigravity$|agy$)/i.test(String(this.config.provider || ''))
2979
3004
  ? 'external_subscription_unavailable' : 'rate_card_estimate',
2980
3005
  callEstimatedCostUsd: this.tokenTracker.calculateCost(
2981
- response.usage.promptTokens, response.usage.completionTokens, response.usage
3006
+ normalizedUsage.promptTokens, normalizedUsage.completionTokens, normalizedUsage
2982
3007
  )
2983
3008
  });
2984
3009
 
@@ -2991,11 +3016,16 @@ You are operating in a text-and-code modality without direct image pixel renderi
2991
3016
  auditLog.log({ event: 'task_usage_advisory', taskId: this.taskId, freshTokens: this.tokenTracker.taskTokens });
2992
3017
  }
2993
3018
 
2994
- const cachedTokens = response.usage.cachedPromptTokens || 0;
3019
+ const cachedTokens = normalizedUsage.cachedPromptTokens;
2995
3020
  if (cachedTokens > 0) {
2996
- this.debugLog(`prompt cache hit: ${cachedTokens.toLocaleString()} of ${response.usage.promptTokens.toLocaleString()} input tokens served from cache`);
3021
+ this.debugLog(`prompt cache hit: ${cachedTokens.toLocaleString()} of ${normalizedUsage.promptTokens.toLocaleString()} input tokens served from cache`);
2997
3022
  }
2998
3023
 
3024
+ // Reset retry state only after response metadata and token accounting succeed
3025
+ // so an internal post-response exception cannot spin infinitely on retry 1 of 3.
3026
+ this.consecutiveFailures = 0;
3027
+ this.lastFailureType = null;
3028
+
2999
3029
 
3000
3030
  //
3001
3031
 
@@ -3010,6 +3040,16 @@ You are operating in a text-and-code modality without direct image pixel renderi
3010
3040
  // the window is actually budgeted in. The renderer converts once, using
3011
3041
  // the project's own CHAR_POOLS convention, instead of comparing a token
3012
3042
  // count to a character limit.
3043
+ const reportedPromptTokens = Number(response.usage?.promptTokens || 0);
3044
+ if (response.usage?.measurement === 'provider_reported'
3045
+ && response.usage?.measurementScope !== 'cumulative'
3046
+ && Number.isFinite(reportedPromptTokens)
3047
+ && reportedPromptTokens > 0) {
3048
+ const reportedContextChars = Math.round(reportedPromptTokens * CHARS_PER_TOKEN);
3049
+ if (reportedContextChars > (this._contextChars || 0)) {
3050
+ this._contextChars = reportedContextChars;
3051
+ }
3052
+ }
3013
3053
  this.emitEvent({
3014
3054
  type: 'usage_update',
3015
3055
  usedTokens: tracking.dailyTokens || 0,
@@ -3245,7 +3285,13 @@ You are operating in a text-and-code modality without direct image pixel renderi
3245
3285
  const extPlan = normalizePeerPlanEntries(extAction.parameters);
3246
3286
  if (extPlan) {
3247
3287
  hasStructuredToolPlan = true;
3248
- this.updateImplementationPlan(extPlan);
3288
+ const extActionId = extAction.id ? String(extAction.id) : '';
3289
+ const extPlanKey = JSON.stringify(extPlan);
3290
+ if (!(extActionId && seenNativePlanActionIds.has(extActionId)) && !seenNativePlanActionIds.has(extPlanKey)) {
3291
+ seenNativePlanActionIds.add(extPlanKey);
3292
+ if (extActionId) seenNativePlanActionIds.add(extActionId);
3293
+ this.updateImplementationPlan(extPlan);
3294
+ }
3249
3295
  }
3250
3296
  const actionName = String(extAction.name || '').toLowerCase();
3251
3297
  const detailPath = typeof extAction.detail === 'string' ? extAction.detail.trim() : '';
@@ -5258,6 +5304,9 @@ You are operating in a text-and-code modality without direct image pixel renderi
5258
5304
  if (msg.includes('kill') || msg.includes('abort') || msg.includes('signal') || msg.includes('fatal')) {
5259
5305
  return 'fatal';
5260
5306
  }
5307
+ if (error instanceof TypeError || error instanceof ReferenceError || error instanceof RangeError) {
5308
+ return 'fatal';
5309
+ }
5261
5310
 
5262
5311
  return 'unknown_error';
5263
5312
  }