@causyne/agent 1.20.20 → 1.20.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/agentLoop.js +57 -100
- package/src/agentLoop.ts +57 -101
- package/src/engines/reverseHarness.js +25 -3
- package/src/engines/reverseHarness.ts +30 -3
- package/src/providers/antigravity.js +43 -26
- package/src/providers/antigravity.ts +41 -24
- package/src/smartToolsUse.js +26 -3
- package/src/smartToolsUse.ts +29 -3
- package/src/tools/reverseEngineering.js +464 -24
- package/src/tools/reverseEngineering.ts +473 -25
- package/src/providers/budgetEnforcer.js +0 -136
- package/src/providers/budgetEnforcer.ts +0 -143
package/package.json
CHANGED
package/src/agentLoop.js
CHANGED
|
@@ -60,7 +60,17 @@ import { StallGuardController } from './stallGuard.js';
|
|
|
60
60
|
import { buildRecoverableDroppedSummary, pruneStaleToolObservations, shortenOversizedToolObservations, pruneExecutedToolArguments } from './historyPruner.js';
|
|
61
61
|
import { isOutputRecoveryRead } from './outputRecovery.js';
|
|
62
62
|
import { isPlanReviewHandoff, isPlanningOnlyRequest } from './taskContinuation.js';
|
|
63
|
-
|
|
63
|
+
export function noncachedTokens(usage) {
|
|
64
|
+
if (!usage)
|
|
65
|
+
return 0;
|
|
66
|
+
const finite = (value) => Number.isFinite(value) ? Math.max(0, value ?? 0) : 0;
|
|
67
|
+
const input = usage.uncachedPromptTokens !== undefined
|
|
68
|
+
? finite(usage.uncachedPromptTokens)
|
|
69
|
+
: finite(usage.cachedPromptTokens) > finite(usage.promptTokens)
|
|
70
|
+
? finite(usage.promptTokens)
|
|
71
|
+
: Math.max(0, finite(usage.promptTokens) - finite(usage.cachedPromptTokens));
|
|
72
|
+
return input + finite(usage.completionTokens);
|
|
73
|
+
}
|
|
64
74
|
export function isActionableTaskPrompt(text) {
|
|
65
75
|
const t = (text || '').trim();
|
|
66
76
|
if (!t)
|
|
@@ -982,7 +992,7 @@ export class AgentLoop {
|
|
|
982
992
|
return prefetched;
|
|
983
993
|
const eligible = [];
|
|
984
994
|
for (const toolCall of toolCalls) {
|
|
985
|
-
const capacity =
|
|
995
|
+
const capacity = this.smartToolsGovernor?.inspectionCapacity ?? 2;
|
|
986
996
|
if (eligible.length >= capacity)
|
|
987
997
|
break;
|
|
988
998
|
const functionName = canonicalToolName(toolCall.function.name);
|
|
@@ -1162,9 +1172,6 @@ export class AgentLoop {
|
|
|
1162
1172
|
throw new Error('The requested ACP file operation was not authorized');
|
|
1163
1173
|
if (tool === 'fs_write')
|
|
1164
1174
|
captureBeforeMutation(tool, args, { taskId: this.taskId, step: this.stepsCompleted });
|
|
1165
|
-
if (!this._inModelCall) {
|
|
1166
|
-
this.efficiencyBudget?.recordAction(`peer-file:${tool}:${target}`);
|
|
1167
|
-
}
|
|
1168
1175
|
let result;
|
|
1169
1176
|
if (tool === 'fs_read') {
|
|
1170
1177
|
// ACP expects the actual requested text, not the host tool's paging
|
|
@@ -1729,18 +1736,7 @@ export class AgentLoop {
|
|
|
1729
1736
|
if (!this.currentTaskPrompt && this.userPrompt) {
|
|
1730
1737
|
this.currentTaskPrompt = this.userPrompt;
|
|
1731
1738
|
}
|
|
1732
|
-
const
|
|
1733
|
-
const efficiency = this.config.efficiency || {};
|
|
1734
|
-
const taskTokenCeiling = Number.isInteger(this.taskTokenLimit) && this.taskTokenLimit > 0
|
|
1735
|
-
? this.taskTokenLimit
|
|
1736
|
-
: this.tokenTracker.budget?.enabled && Number.isFinite(this.tokenTracker.budget?.maxTokensPerTask) && this.tokenTracker.budget.maxTokensPerTask > 0
|
|
1737
|
-
? this.tokenTracker.budget.maxTokensPerTask
|
|
1738
|
-
: Number.isFinite(efficiency.maxTaskTokens) && efficiency.maxTaskTokens > 0
|
|
1739
|
-
? efficiency.maxTaskTokens
|
|
1740
|
-
: tokenLimitFor(turnArchetype);
|
|
1741
|
-
this.efficiencyBudget = new UnifiedBudgetEnforcer(Number.isFinite(efficiency.maxTurnTokens) && efficiency.maxTurnTokens > 0
|
|
1742
|
-
? efficiency.maxTurnTokens
|
|
1743
|
-
: turnTokenLimitFor(turnArchetype), Number.isSafeInteger(efficiency.maxTurnActions) && efficiency.maxTurnActions > 0 ? efficiency.maxTurnActions : actionLimitFor(turnArchetype), taskTokenCeiling);
|
|
1739
|
+
const isAutonomousMode = (this.config.autonomyMode || 'C') === 'C';
|
|
1744
1740
|
const recoveryPaths = new Set();
|
|
1745
1741
|
let modelCallIndex = 0;
|
|
1746
1742
|
let mediaExplorationRecoveries = 0;
|
|
@@ -1748,6 +1744,7 @@ export class AgentLoop {
|
|
|
1748
1744
|
let planHandoffRecoveries = 0;
|
|
1749
1745
|
let incompleteTurnContinuations = 0;
|
|
1750
1746
|
let toolRoutingRecoveries = 0;
|
|
1747
|
+
let emptyResponseRecoveries = 0;
|
|
1751
1748
|
// The core loop governed by Sovereign Human-in-the-Loop Checkpoints
|
|
1752
1749
|
while (!this.stopRequested) {
|
|
1753
1750
|
if (this.stopRequested) {
|
|
@@ -2107,7 +2104,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
2107
2104
|
const configuredRemainingBudget = hardBudget
|
|
2108
2105
|
? Math.min(taskLimit > 0 ? taskLimit - this.tokenTracker.taskTokens : Infinity, dailyLimit > 0 ? dailyLimit - dailyUsed : Infinity) : Infinity;
|
|
2109
2106
|
const remainingBudget = hardBudget
|
|
2110
|
-
?
|
|
2107
|
+
? configuredRemainingBudget
|
|
2111
2108
|
: Infinity;
|
|
2112
2109
|
if (hardBudget && remainingBudget <= 0) {
|
|
2113
2110
|
this.emitEvent({ type: 'budget_warning', message: 'Token budget reached before the next model call.' });
|
|
@@ -2142,9 +2139,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
2142
2139
|
pruneExecutedToolArguments(this.messages, { threshold: 1500, taskId: this.taskId });
|
|
2143
2140
|
const stepScale = Math.max(this.tokenTracker.largestStepTokens || 50_000, 100_000);
|
|
2144
2141
|
const extraTokens = Math.max(stepScale * 10, 1_000_000);
|
|
2145
|
-
const extraActions = Math.max(Math.ceil((this.efficiencyBudget?.getRemainingActions() ?? 50) + 100), 100);
|
|
2146
2142
|
this.tokenTracker.extendBudget(extraTokens);
|
|
2147
|
-
this.efficiencyBudget?.extendBudget?.(extraTokens, extraActions);
|
|
2148
2143
|
}
|
|
2149
2144
|
}
|
|
2150
2145
|
// 2. PLAN (Call LLM). dynamicTools was resolved above so the task brief
|
|
@@ -2185,7 +2180,6 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
2185
2180
|
this.emitEvent({ type: 'agent_activity', activity: 'Thinking…' });
|
|
2186
2181
|
const planStepStart = performance.now();
|
|
2187
2182
|
const nativeControl = new AbortController();
|
|
2188
|
-
let nativeCheckpoint = null;
|
|
2189
2183
|
const invocation = ++modelCallIndex;
|
|
2190
2184
|
this._inModelCall = true;
|
|
2191
2185
|
const response = await this.llm.chat(prunedMessages, {
|
|
@@ -2197,8 +2191,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
2197
2191
|
maxTokensThisCall: Number.isFinite(configuredRemainingBudget) && hardBudget ? configuredRemainingBudget : undefined,
|
|
2198
2192
|
tokenBudgetBasis: Number.isFinite(configuredRemainingBudget) ? 'total' : 'noncached',
|
|
2199
2193
|
tokenLimit: hardBudget && Number.isFinite(remainingBudget) && remainingBudget > 0
|
|
2200
|
-
?
|
|
2201
|
-
maxNativeActions: this.efficiencyBudget.getRemainingActions(),
|
|
2194
|
+
? remainingBudget : undefined,
|
|
2202
2195
|
workspaceRoot: this.workspaceRoot,
|
|
2203
2196
|
onPeerPermission: (request) => this.requestPeerPermission(request),
|
|
2204
2197
|
onPeerFileRead: (file, options) => this.executePeerFile('fs_read', file, undefined, options),
|
|
@@ -2292,19 +2285,6 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
2292
2285
|
auditLog.log({ event: 'native_action', taskId: this.taskId,
|
|
2293
2286
|
provider: this.config.provider || 'unknown', tool: action.name, status: action.status,
|
|
2294
2287
|
...(action.id ? { actionId: action.id } : {}) });
|
|
2295
|
-
if (action.status === 'running' && !isChecklistTool) {
|
|
2296
|
-
try {
|
|
2297
|
-
this.efficiencyBudget.recordAction(`${invocation}:${action.id || `${action.name}:${action.detail || ''}`}`);
|
|
2298
|
-
}
|
|
2299
|
-
catch (error) {
|
|
2300
|
-
if (error instanceof EfficiencyCheckpoint) {
|
|
2301
|
-
finalizeReasoningSegment();
|
|
2302
|
-
nativeCheckpoint = error;
|
|
2303
|
-
nativeControl.abort();
|
|
2304
|
-
}
|
|
2305
|
-
return;
|
|
2306
|
-
}
|
|
2307
|
-
}
|
|
2308
2288
|
if (action.status === 'completed' && action.id && !isChecklistTool) {
|
|
2309
2289
|
completedNativeActionIds.add(String(action.id));
|
|
2310
2290
|
}
|
|
@@ -2424,22 +2404,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
2424
2404
|
}
|
|
2425
2405
|
throw checkpoint;
|
|
2426
2406
|
}
|
|
2427
|
-
|
|
2428
|
-
if (completedNativeActionIds.size > 0) {
|
|
2429
|
-
this.stepsCompleted += completedNativeActionIds.size;
|
|
2430
|
-
}
|
|
2431
|
-
if (reasoningAccumulated) {
|
|
2432
|
-
this.messages.push({
|
|
2433
|
-
role: 'assistant',
|
|
2434
|
-
content: 'Turn paused at efficiency checkpoint.',
|
|
2435
|
-
reasoning_content: reasoningAccumulated
|
|
2436
|
-
});
|
|
2437
|
-
}
|
|
2438
|
-
if (error && typeof error === 'object' && 'partialUsage' in error) {
|
|
2439
|
-
Object.assign(nativeCheckpoint, { partialUsage: error.partialUsage });
|
|
2440
|
-
}
|
|
2441
|
-
}
|
|
2442
|
-
throw nativeCheckpoint || error;
|
|
2407
|
+
throw error;
|
|
2443
2408
|
})
|
|
2444
2409
|
.finally(() => {
|
|
2445
2410
|
finalizeReasoningSegment();
|
|
@@ -2486,10 +2451,6 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
2486
2451
|
? 'external_subscription_unavailable' : 'rate_card_estimate',
|
|
2487
2452
|
callEstimatedCostUsd: this.tokenTracker.calculateCost(response.usage.promptTokens, response.usage.completionTokens, response.usage)
|
|
2488
2453
|
});
|
|
2489
|
-
this.efficiencyBudget.recordUsage(response.usage);
|
|
2490
|
-
for (const action of response.externalActions || []) {
|
|
2491
|
-
this.efficiencyBudget.recordAction(`${invocation}:${action.id || `${action.name}:${action.detail || ''}`}`);
|
|
2492
|
-
}
|
|
2493
2454
|
const cachedTokens = response.usage.cachedPromptTokens || 0;
|
|
2494
2455
|
if (cachedTokens > 0) {
|
|
2495
2456
|
this.debugLog(`prompt cache hit: ${cachedTokens.toLocaleString()} of ${response.usage.promptTokens.toLocaleString()} input tokens served from cache`);
|
|
@@ -3581,7 +3542,6 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
3581
3542
|
// errors. It only rewinds reasoning; it never replays side effects.
|
|
3582
3543
|
let result;
|
|
3583
3544
|
let duration;
|
|
3584
|
-
this.efficiencyBudget.recordAction();
|
|
3585
3545
|
try {
|
|
3586
3546
|
const startTime = Date.now();
|
|
3587
3547
|
const actStart = performance.now();
|
|
@@ -4000,15 +3960,6 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
4000
3960
|
cachedPromptTokens: usage.cachedPromptTokens || 0,
|
|
4001
3961
|
measurement: 'provider_reported_partial', costBasis: 'external_subscription_unavailable'
|
|
4002
3962
|
});
|
|
4003
|
-
try {
|
|
4004
|
-
this.efficiencyBudget.recordUsage(usage);
|
|
4005
|
-
}
|
|
4006
|
-
catch (checkpoint) {
|
|
4007
|
-
if (checkpoint instanceof EfficiencyCheckpoint)
|
|
4008
|
-
e = checkpoint;
|
|
4009
|
-
else
|
|
4010
|
-
throw checkpoint;
|
|
4011
|
-
}
|
|
4012
3963
|
}
|
|
4013
3964
|
}
|
|
4014
3965
|
if (e instanceof RetryConsentCheckpoint && this._pendingConsent) {
|
|
@@ -4023,40 +3974,26 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
4023
3974
|
this.memoryManager.saveHistory(this.messages);
|
|
4024
3975
|
continue;
|
|
4025
3976
|
}
|
|
4026
|
-
|
|
4027
|
-
const isHardBudget = (Number.isInteger(this.taskTokenLimit) && this.taskTokenLimit > 0)
|
|
4028
|
-
|| (this.tokenTracker.budget?.enabled === true && this.tokenTracker.budget?.hardStop === true);
|
|
4029
|
-
const isDesktopLimit = e?.code === 'AGY_DESKTOP_TASK_LIMIT';
|
|
4030
|
-
if (isTokenCheckpoint && !isHardBudget && !isDesktopLimit && incompleteTurnContinuations < 5) {
|
|
4031
|
-
incompleteTurnContinuations++;
|
|
4032
|
-
this.emitEvent({ type: 'budget_warning', message: e.message });
|
|
4033
|
-
auditLog.log({
|
|
4034
|
-
event: 'efficiency_checkpoint',
|
|
4035
|
-
taskId: this.taskId,
|
|
4036
|
-
reason: e?.reason || e?.code || 'budget',
|
|
4037
|
-
...this.efficiencyBudget.snapshot()
|
|
4038
|
-
});
|
|
4039
|
-
const stepScale = Math.max(this.tokenTracker.largestStepTokens || 50_000, 100_000);
|
|
4040
|
-
const extraTokens = Math.max(stepScale * 10, 1_000_000);
|
|
4041
|
-
const extraActions = Math.max(Math.ceil((this.efficiencyBudget?.getRemainingActions() ?? 50) + 100), 100);
|
|
4042
|
-
this.tokenTracker.extendBudget(extraTokens);
|
|
4043
|
-
this.efficiencyBudget.extendBudget?.(extraTokens, extraActions);
|
|
4044
|
-
compactSessionMessages(this.messages, {
|
|
4045
|
-
keepRecentTurns: 4,
|
|
4046
|
-
taskId: this.taskId,
|
|
4047
|
-
originalPrompt: this.currentTaskPrompt || this.userPrompt
|
|
4048
|
-
});
|
|
4049
|
-
this.emitEvent({ type: 'status', message: `Continuing task execution from efficiency checkpoint (runway extended +${extraActions} actions)…` });
|
|
4050
|
-
this.emitEvent({ type: 'agent_activity', activity: 'Continuing task from efficiency checkpoint…' });
|
|
4051
|
-
this.messages.push({
|
|
4052
|
-
role: 'system',
|
|
4053
|
-
content: `[EFFICIENCY CONTINUATION: Previous turn paused at checkpoint (${e.message}). Autonomous runway extended (+${extraActions} actions). Session history and disk modifications are preserved. Do NOT replay prior actions. Continue executing the task directly.]`
|
|
4054
|
-
});
|
|
4055
|
-
this.memoryManager.saveHistory(this.messages);
|
|
4056
|
-
continue;
|
|
4057
|
-
}
|
|
4058
|
-
if (e instanceof EfficiencyCheckpoint || e?.code === 'TASK_TOKEN_BUDGET' || e?.code === 'PROVIDER_TOKEN_BUDGET'
|
|
3977
|
+
if (e?.code === 'TASK_TOKEN_BUDGET' || e?.code === 'PROVIDER_TOKEN_BUDGET'
|
|
4059
3978
|
|| e?.code === 'AGY_DESKTOP_TASK_LIMIT' || e?.code === 'AGY_TOKEN_BUDGET' || e?.code === 'AGY_NATIVE_ACTION_BUDGET') {
|
|
3979
|
+
const isExplicitHardBudget = (Number.isInteger(this.taskTokenLimit) && this.taskTokenLimit > 0)
|
|
3980
|
+
|| (this.tokenTracker.budget?.enabled === true && this.tokenTracker.budget?.hardStop === true);
|
|
3981
|
+
if (this.config.autonomyMode === 'C' && !isExplicitHardBudget) {
|
|
3982
|
+
this.emitEvent({ type: 'budget_warning', message: e.message });
|
|
3983
|
+
pruneStaleToolObservations(this.messages, { keepRecent: 3, minChars: 300, taskId: this.taskId });
|
|
3984
|
+
shortenOversizedToolObservations(this.messages, { threshold: 1500, taskId: this.taskId });
|
|
3985
|
+
pruneExecutedToolArguments(this.messages, { threshold: 1500, taskId: this.taskId });
|
|
3986
|
+
const stepScale = Math.max(this.tokenTracker.largestStepTokens || 50_000, 100_000);
|
|
3987
|
+
const extraTokens = Math.max(stepScale * 10, 1_000_000);
|
|
3988
|
+
this.tokenTracker.extendBudget(extraTokens);
|
|
3989
|
+
this.emitEvent({ type: 'status', message: 'Continuing autonomous task execution without artificial interruption…' });
|
|
3990
|
+
this.messages.push({
|
|
3991
|
+
role: 'system',
|
|
3992
|
+
content: '[Autonomous task continuation: Do not repeat prior actions. Proceed with executing next concrete steps.]'
|
|
3993
|
+
});
|
|
3994
|
+
this.memoryManager.saveHistory(this.messages);
|
|
3995
|
+
continue;
|
|
3996
|
+
}
|
|
4060
3997
|
this.messages.push({ role: 'system', content: `[Unfinished task checkpoint] ${e.message}` });
|
|
4061
3998
|
this.memoryManager.saveHistory(this.messages);
|
|
4062
3999
|
this.emitEvent({ type: 'budget_warning', message: e.message });
|
|
@@ -4064,7 +4001,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
4064
4001
|
event: 'efficiency_checkpoint',
|
|
4065
4002
|
taskId: this.taskId,
|
|
4066
4003
|
reason: e?.reason || e?.code,
|
|
4067
|
-
|
|
4004
|
+
tokenUsage: this.tokenTracker.taskTokens
|
|
4068
4005
|
});
|
|
4069
4006
|
break;
|
|
4070
4007
|
}
|
|
@@ -4097,6 +4034,26 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
4097
4034
|
this.emitEvent({ type: 'error', message: 'The provider continued read-only inspection after a corrective checkpoint. The task remains unfinished; no edit was verified.' });
|
|
4098
4035
|
break;
|
|
4099
4036
|
}
|
|
4037
|
+
if (e?.code === 'PROVIDER_EMPTY_RESPONSE'
|
|
4038
|
+
|| (typeof e?.message === 'string' && e.message.includes('returned no response'))) {
|
|
4039
|
+
if (emptyResponseRecoveries++ < 5) {
|
|
4040
|
+
this.emitEvent({
|
|
4041
|
+
type: 'notice',
|
|
4042
|
+
message: `Peer connection was interrupted or returned no response (${emptyResponseRecoveries}/5). Auto-reconnecting session and resuming task…`
|
|
4043
|
+
});
|
|
4044
|
+
auditLog.log({ event: 'peer_empty_response_recovery', taskId: this.taskId, attempt: emptyResponseRecoveries, error: e.message });
|
|
4045
|
+
const planNotice = this._implementationPlan?.length > 0
|
|
4046
|
+
? ` Active plan has ${this._implementationPlan.filter((s) => s.status === 'completed' || s.completed).length}/${this._implementationPlan.length} steps completed.`
|
|
4047
|
+
: '';
|
|
4048
|
+
this.messages.push({
|
|
4049
|
+
role: 'system',
|
|
4050
|
+
content: `[RECONNECTION RECOVERY: The previous peer turn disconnected or returned no response.${planNotice} Disk files and modifications are preserved. Do NOT repeat completed work. Continue executing the next unfinished step of the task directly.]`
|
|
4051
|
+
});
|
|
4052
|
+
this.memoryManager.saveHistory(this.messages);
|
|
4053
|
+
await this.backoff(emptyResponseRecoveries);
|
|
4054
|
+
continue;
|
|
4055
|
+
}
|
|
4056
|
+
}
|
|
4100
4057
|
if (this.stopRequested || this.abortController?.signal?.aborted || e?.name === 'AbortError') {
|
|
4101
4058
|
this.debugLog(`agent loop interrupted: ${e?.message || 'aborted'}`);
|
|
4102
4059
|
auditLog.log({ event: 'task_interrupted', taskId: this.taskId });
|
package/src/agentLoop.ts
CHANGED
|
@@ -101,7 +101,16 @@ import { StallGuardController, type StallGuardDecision, type IdenticalCallObserv
|
|
|
101
101
|
import { buildRecoverableDroppedSummary, pruneStaleToolObservations, shortenOversizedToolObservations, pruneExecutedToolArguments } from './historyPruner.js';
|
|
102
102
|
import { isOutputRecoveryRead } from './outputRecovery.js';
|
|
103
103
|
import { isPlanReviewHandoff, isPlanningOnlyRequest } from './taskContinuation.js';
|
|
104
|
-
|
|
104
|
+
export function noncachedTokens(usage: any): number {
|
|
105
|
+
if (!usage) return 0;
|
|
106
|
+
const finite = (value: number | undefined): number => Number.isFinite(value) ? Math.max(0, value ?? 0) : 0;
|
|
107
|
+
const input = usage.uncachedPromptTokens !== undefined
|
|
108
|
+
? finite(usage.uncachedPromptTokens)
|
|
109
|
+
: finite(usage.cachedPromptTokens) > finite(usage.promptTokens)
|
|
110
|
+
? finite(usage.promptTokens)
|
|
111
|
+
: Math.max(0, finite(usage.promptTokens) - finite(usage.cachedPromptTokens));
|
|
112
|
+
return input + finite(usage.completionTokens);
|
|
113
|
+
}
|
|
105
114
|
|
|
106
115
|
export interface AgentLoopEvent {
|
|
107
116
|
type: string;
|
|
@@ -1096,8 +1105,7 @@ export class AgentLoop {
|
|
|
1096
1105
|
|
|
1097
1106
|
const eligible: any[] = [];
|
|
1098
1107
|
for (const toolCall of toolCalls) {
|
|
1099
|
-
const capacity =
|
|
1100
|
-
this.efficiencyBudget?.getRemainingActions() ?? 35);
|
|
1108
|
+
const capacity = this.smartToolsGovernor?.inspectionCapacity ?? 2;
|
|
1101
1109
|
if (eligible.length >= capacity) break;
|
|
1102
1110
|
const functionName = canonicalToolName(toolCall.function.name);
|
|
1103
1111
|
// A later read may verify an earlier write. Never prefetch it across
|
|
@@ -1251,9 +1259,6 @@ export class AgentLoop {
|
|
|
1251
1259
|
const id = `peer-file:${randomUUID()}:${tool}`;
|
|
1252
1260
|
if (!await this.authorizePeerOperation(tool, args, id)) throw new Error('The requested ACP file operation was not authorized');
|
|
1253
1261
|
if (tool === 'fs_write') captureBeforeMutation(tool, args, { taskId: this.taskId, step: this.stepsCompleted });
|
|
1254
|
-
if (!this._inModelCall) {
|
|
1255
|
-
this.efficiencyBudget?.recordAction(`peer-file:${tool}:${target}`);
|
|
1256
|
-
}
|
|
1257
1262
|
let result: { success: boolean; error?: string; output?: string };
|
|
1258
1263
|
if (tool === 'fs_read') {
|
|
1259
1264
|
// ACP expects the actual requested text, not the host tool's paging
|
|
@@ -1828,22 +1833,7 @@ export class AgentLoop {
|
|
|
1828
1833
|
if (!this.currentTaskPrompt && this.userPrompt) {
|
|
1829
1834
|
this.currentTaskPrompt = this.userPrompt;
|
|
1830
1835
|
}
|
|
1831
|
-
const
|
|
1832
|
-
const efficiency = this.config.efficiency || {};
|
|
1833
|
-
const taskTokenCeiling = Number.isInteger(this.taskTokenLimit) && (this.taskTokenLimit as number) > 0
|
|
1834
|
-
? (this.taskTokenLimit as number)
|
|
1835
|
-
: this.tokenTracker.budget?.enabled && Number.isFinite(this.tokenTracker.budget?.maxTokensPerTask) && (this.tokenTracker.budget.maxTokensPerTask as number) > 0
|
|
1836
|
-
? (this.tokenTracker.budget.maxTokensPerTask as number)
|
|
1837
|
-
: Number.isFinite(efficiency.maxTaskTokens) && (efficiency.maxTaskTokens as number) > 0
|
|
1838
|
-
? (efficiency.maxTaskTokens as number)
|
|
1839
|
-
: tokenLimitFor(turnArchetype);
|
|
1840
|
-
this.efficiencyBudget = new UnifiedBudgetEnforcer(
|
|
1841
|
-
Number.isFinite(efficiency.maxTurnTokens) && efficiency.maxTurnTokens > 0
|
|
1842
|
-
? efficiency.maxTurnTokens
|
|
1843
|
-
: turnTokenLimitFor(turnArchetype),
|
|
1844
|
-
Number.isSafeInteger(efficiency.maxTurnActions) && efficiency.maxTurnActions > 0 ? efficiency.maxTurnActions : actionLimitFor(turnArchetype),
|
|
1845
|
-
taskTokenCeiling
|
|
1846
|
-
);
|
|
1836
|
+
const isAutonomousMode = (this.config.autonomyMode || 'C') === 'C';
|
|
1847
1837
|
const recoveryPaths = new Set<string>();
|
|
1848
1838
|
let modelCallIndex = 0;
|
|
1849
1839
|
let mediaExplorationRecoveries = 0;
|
|
@@ -1851,6 +1841,7 @@ export class AgentLoop {
|
|
|
1851
1841
|
let planHandoffRecoveries = 0;
|
|
1852
1842
|
let incompleteTurnContinuations = 0;
|
|
1853
1843
|
let toolRoutingRecoveries = 0;
|
|
1844
|
+
let emptyResponseRecoveries = 0;
|
|
1854
1845
|
|
|
1855
1846
|
// The core loop governed by Sovereign Human-in-the-Loop Checkpoints
|
|
1856
1847
|
while (!this.stopRequested) {
|
|
@@ -2240,7 +2231,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
2240
2231
|
dailyLimit > 0 ? dailyLimit - dailyUsed : Infinity
|
|
2241
2232
|
) : Infinity;
|
|
2242
2233
|
const remainingBudget = hardBudget
|
|
2243
|
-
?
|
|
2234
|
+
? configuredRemainingBudget
|
|
2244
2235
|
: Infinity;
|
|
2245
2236
|
if (hardBudget && remainingBudget <= 0) {
|
|
2246
2237
|
this.emitEvent({ type: 'budget_warning', message: 'Token budget reached before the next model call.' });
|
|
@@ -2271,9 +2262,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
2271
2262
|
pruneExecutedToolArguments(this.messages, { threshold: 1500, taskId: this.taskId });
|
|
2272
2263
|
const stepScale = Math.max(this.tokenTracker.largestStepTokens || 50_000, 100_000);
|
|
2273
2264
|
const extraTokens = Math.max(stepScale * 10, 1_000_000);
|
|
2274
|
-
const extraActions = Math.max(Math.ceil((this.efficiencyBudget?.getRemainingActions() ?? 50) + 100), 100);
|
|
2275
2265
|
this.tokenTracker.extendBudget(extraTokens);
|
|
2276
|
-
this.efficiencyBudget?.extendBudget?.(extraTokens, extraActions);
|
|
2277
2266
|
}
|
|
2278
2267
|
}
|
|
2279
2268
|
|
|
@@ -2316,7 +2305,6 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
2316
2305
|
|
|
2317
2306
|
const planStepStart = performance.now();
|
|
2318
2307
|
const nativeControl = new AbortController();
|
|
2319
|
-
let nativeCheckpoint: EfficiencyCheckpoint | null = null;
|
|
2320
2308
|
const invocation = ++modelCallIndex;
|
|
2321
2309
|
this._inModelCall = true;
|
|
2322
2310
|
const response = await this.llm.chat(prunedMessages, {
|
|
@@ -2328,8 +2316,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
2328
2316
|
maxTokensThisCall: Number.isFinite(configuredRemainingBudget) && hardBudget ? configuredRemainingBudget : undefined,
|
|
2329
2317
|
tokenBudgetBasis: Number.isFinite(configuredRemainingBudget) ? 'total' : 'noncached',
|
|
2330
2318
|
tokenLimit: hardBudget && Number.isFinite(remainingBudget) && remainingBudget > 0
|
|
2331
|
-
?
|
|
2332
|
-
maxNativeActions: this.efficiencyBudget.getRemainingActions(),
|
|
2319
|
+
? remainingBudget : undefined,
|
|
2333
2320
|
workspaceRoot: this.workspaceRoot,
|
|
2334
2321
|
onPeerPermission: (request: RequestPermissionRequest) => this.requestPeerPermission(request),
|
|
2335
2322
|
onPeerFileRead: (file: string, options?: { line?: number; limit?: number }) => this.executePeerFile('fs_read', file, undefined, options),
|
|
@@ -2415,18 +2402,6 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
2415
2402
|
auditLog.log({ event: 'native_action', taskId: this.taskId,
|
|
2416
2403
|
provider: this.config.provider || 'unknown', tool: action.name, status: action.status,
|
|
2417
2404
|
...(action.id ? { actionId: action.id } : {}) });
|
|
2418
|
-
if (action.status === 'running' && !isChecklistTool) {
|
|
2419
|
-
try {
|
|
2420
|
-
this.efficiencyBudget.recordAction(`${invocation}:${action.id || `${action.name}:${action.detail || ''}`}`);
|
|
2421
|
-
} catch (error: unknown) {
|
|
2422
|
-
if (error instanceof EfficiencyCheckpoint) {
|
|
2423
|
-
finalizeReasoningSegment();
|
|
2424
|
-
nativeCheckpoint = error;
|
|
2425
|
-
nativeControl.abort();
|
|
2426
|
-
}
|
|
2427
|
-
return;
|
|
2428
|
-
}
|
|
2429
|
-
}
|
|
2430
2405
|
if (action.status === 'completed' && action.id && !isChecklistTool) {
|
|
2431
2406
|
completedNativeActionIds.add(String(action.id));
|
|
2432
2407
|
}
|
|
@@ -2543,22 +2518,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
2543
2518
|
}
|
|
2544
2519
|
throw checkpoint;
|
|
2545
2520
|
}
|
|
2546
|
-
|
|
2547
|
-
if (completedNativeActionIds.size > 0) {
|
|
2548
|
-
this.stepsCompleted += completedNativeActionIds.size;
|
|
2549
|
-
}
|
|
2550
|
-
if (reasoningAccumulated) {
|
|
2551
|
-
this.messages.push({
|
|
2552
|
-
role: 'assistant',
|
|
2553
|
-
content: 'Turn paused at efficiency checkpoint.',
|
|
2554
|
-
reasoning_content: reasoningAccumulated
|
|
2555
|
-
});
|
|
2556
|
-
}
|
|
2557
|
-
if (error && typeof error === 'object' && 'partialUsage' in error) {
|
|
2558
|
-
Object.assign(nativeCheckpoint, { partialUsage: error.partialUsage });
|
|
2559
|
-
}
|
|
2560
|
-
}
|
|
2561
|
-
throw nativeCheckpoint || error;
|
|
2521
|
+
throw error;
|
|
2562
2522
|
})
|
|
2563
2523
|
.finally(() => {
|
|
2564
2524
|
finalizeReasoningSegment();
|
|
@@ -2617,10 +2577,6 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
2617
2577
|
response.usage.promptTokens, response.usage.completionTokens, response.usage
|
|
2618
2578
|
)
|
|
2619
2579
|
});
|
|
2620
|
-
this.efficiencyBudget.recordUsage(response.usage);
|
|
2621
|
-
for (const action of response.externalActions || []) {
|
|
2622
|
-
this.efficiencyBudget.recordAction(`${invocation}:${action.id || `${action.name}:${action.detail || ''}`}`);
|
|
2623
|
-
}
|
|
2624
2580
|
|
|
2625
2581
|
const cachedTokens = response.usage.cachedPromptTokens || 0;
|
|
2626
2582
|
if (cachedTokens > 0) {
|
|
@@ -3795,7 +3751,6 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
3795
3751
|
// errors. It only rewinds reasoning; it never replays side effects.
|
|
3796
3752
|
let result;
|
|
3797
3753
|
let duration;
|
|
3798
|
-
this.efficiencyBudget.recordAction();
|
|
3799
3754
|
|
|
3800
3755
|
try {
|
|
3801
3756
|
const startTime = Date.now();
|
|
@@ -4251,11 +4206,6 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
4251
4206
|
cachedPromptTokens: usage.cachedPromptTokens || 0,
|
|
4252
4207
|
measurement: 'provider_reported_partial', costBasis: 'external_subscription_unavailable'
|
|
4253
4208
|
});
|
|
4254
|
-
try { this.efficiencyBudget.recordUsage(usage); }
|
|
4255
|
-
catch (checkpoint: unknown) {
|
|
4256
|
-
if (checkpoint instanceof EfficiencyCheckpoint) e = checkpoint;
|
|
4257
|
-
else throw checkpoint;
|
|
4258
|
-
}
|
|
4259
4209
|
}
|
|
4260
4210
|
}
|
|
4261
4211
|
if (e instanceof RetryConsentCheckpoint && this._pendingConsent) {
|
|
@@ -4270,41 +4220,26 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
4270
4220
|
this.memoryManager.saveHistory(this.messages);
|
|
4271
4221
|
continue;
|
|
4272
4222
|
}
|
|
4273
|
-
|
|
4274
|
-
const isHardBudget = (Number.isInteger(this.taskTokenLimit) && (this.taskTokenLimit as number) > 0)
|
|
4275
|
-
|| (this.tokenTracker.budget?.enabled === true && this.tokenTracker.budget?.hardStop === true);
|
|
4276
|
-
const isDesktopLimit = e?.code === 'AGY_DESKTOP_TASK_LIMIT';
|
|
4277
|
-
|
|
4278
|
-
if (isTokenCheckpoint && !isHardBudget && !isDesktopLimit && incompleteTurnContinuations < 5) {
|
|
4279
|
-
incompleteTurnContinuations++;
|
|
4280
|
-
this.emitEvent({ type: 'budget_warning', message: e.message });
|
|
4281
|
-
auditLog.log({
|
|
4282
|
-
event: 'efficiency_checkpoint',
|
|
4283
|
-
taskId: this.taskId,
|
|
4284
|
-
reason: (e as any)?.reason || (e as any)?.code || 'budget',
|
|
4285
|
-
...this.efficiencyBudget.snapshot()
|
|
4286
|
-
});
|
|
4287
|
-
const stepScale = Math.max(this.tokenTracker.largestStepTokens || 50_000, 100_000);
|
|
4288
|
-
const extraTokens = Math.max(stepScale * 10, 1_000_000);
|
|
4289
|
-
const extraActions = Math.max(Math.ceil((this.efficiencyBudget?.getRemainingActions() ?? 50) + 100), 100);
|
|
4290
|
-
this.tokenTracker.extendBudget(extraTokens);
|
|
4291
|
-
this.efficiencyBudget.extendBudget?.(extraTokens, extraActions);
|
|
4292
|
-
compactSessionMessages(this.messages, {
|
|
4293
|
-
keepRecentTurns: 4,
|
|
4294
|
-
taskId: this.taskId,
|
|
4295
|
-
originalPrompt: this.currentTaskPrompt || this.userPrompt
|
|
4296
|
-
});
|
|
4297
|
-
this.emitEvent({ type: 'status', message: `Continuing task execution from efficiency checkpoint (runway extended +${extraActions} actions)…` });
|
|
4298
|
-
this.emitEvent({ type: 'agent_activity', activity: 'Continuing task from efficiency checkpoint…' });
|
|
4299
|
-
this.messages.push({
|
|
4300
|
-
role: 'system',
|
|
4301
|
-
content: `[EFFICIENCY CONTINUATION: Previous turn paused at checkpoint (${e.message}). Autonomous runway extended (+${extraActions} actions). Session history and disk modifications are preserved. Do NOT replay prior actions. Continue executing the task directly.]`
|
|
4302
|
-
});
|
|
4303
|
-
this.memoryManager.saveHistory(this.messages);
|
|
4304
|
-
continue;
|
|
4305
|
-
}
|
|
4306
|
-
if (e instanceof EfficiencyCheckpoint || e?.code === 'TASK_TOKEN_BUDGET' || e?.code === 'PROVIDER_TOKEN_BUDGET'
|
|
4223
|
+
if (e?.code === 'TASK_TOKEN_BUDGET' || e?.code === 'PROVIDER_TOKEN_BUDGET'
|
|
4307
4224
|
|| e?.code === 'AGY_DESKTOP_TASK_LIMIT' || e?.code === 'AGY_TOKEN_BUDGET' || e?.code === 'AGY_NATIVE_ACTION_BUDGET') {
|
|
4225
|
+
const isExplicitHardBudget = (Number.isInteger(this.taskTokenLimit) && (this.taskTokenLimit as number) > 0)
|
|
4226
|
+
|| (this.tokenTracker.budget?.enabled === true && this.tokenTracker.budget?.hardStop === true);
|
|
4227
|
+
if (this.config.autonomyMode === 'C' && !isExplicitHardBudget) {
|
|
4228
|
+
this.emitEvent({ type: 'budget_warning', message: e.message });
|
|
4229
|
+
pruneStaleToolObservations(this.messages, { keepRecent: 3, minChars: 300, taskId: this.taskId });
|
|
4230
|
+
shortenOversizedToolObservations(this.messages, { threshold: 1500, taskId: this.taskId });
|
|
4231
|
+
pruneExecutedToolArguments(this.messages, { threshold: 1500, taskId: this.taskId });
|
|
4232
|
+
const stepScale = Math.max(this.tokenTracker.largestStepTokens || 50_000, 100_000);
|
|
4233
|
+
const extraTokens = Math.max(stepScale * 10, 1_000_000);
|
|
4234
|
+
this.tokenTracker.extendBudget(extraTokens);
|
|
4235
|
+
this.emitEvent({ type: 'status', message: 'Continuing autonomous task execution without artificial interruption…' });
|
|
4236
|
+
this.messages.push({
|
|
4237
|
+
role: 'system',
|
|
4238
|
+
content: '[Autonomous task continuation: Do not repeat prior actions. Proceed with executing next concrete steps.]'
|
|
4239
|
+
});
|
|
4240
|
+
this.memoryManager.saveHistory(this.messages);
|
|
4241
|
+
continue;
|
|
4242
|
+
}
|
|
4308
4243
|
this.messages.push({ role: 'system', content: `[Unfinished task checkpoint] ${e.message}` });
|
|
4309
4244
|
this.memoryManager.saveHistory(this.messages);
|
|
4310
4245
|
this.emitEvent({ type: 'budget_warning', message: e.message });
|
|
@@ -4312,7 +4247,7 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
4312
4247
|
event: 'efficiency_checkpoint',
|
|
4313
4248
|
taskId: this.taskId,
|
|
4314
4249
|
reason: (e as any)?.reason || (e as any)?.code,
|
|
4315
|
-
|
|
4250
|
+
tokenUsage: this.tokenTracker.taskTokens
|
|
4316
4251
|
});
|
|
4317
4252
|
break;
|
|
4318
4253
|
}
|
|
@@ -4348,6 +4283,27 @@ You are operating in a text-and-code modality without direct image pixel renderi
|
|
|
4348
4283
|
'The provider continued read-only inspection after a corrective checkpoint. The task remains unfinished; no edit was verified.' });
|
|
4349
4284
|
break;
|
|
4350
4285
|
}
|
|
4286
|
+
if (e?.code === 'PROVIDER_EMPTY_RESPONSE'
|
|
4287
|
+
|| (typeof e?.message === 'string' && e.message.includes('returned no response'))) {
|
|
4288
|
+
if (emptyResponseRecoveries++ < 5) {
|
|
4289
|
+
this.emitEvent({
|
|
4290
|
+
type: 'notice',
|
|
4291
|
+
message: `Peer connection was interrupted or returned no response (${emptyResponseRecoveries}/5). Auto-reconnecting session and resuming task…`
|
|
4292
|
+
});
|
|
4293
|
+
auditLog.log({ event: 'peer_empty_response_recovery', taskId: this.taskId, attempt: emptyResponseRecoveries, error: e.message });
|
|
4294
|
+
|
|
4295
|
+
const planNotice = this._implementationPlan?.length > 0
|
|
4296
|
+
? ` Active plan has ${this._implementationPlan.filter((s: any) => s.status === 'completed' || s.completed).length}/${this._implementationPlan.length} steps completed.`
|
|
4297
|
+
: '';
|
|
4298
|
+
this.messages.push({
|
|
4299
|
+
role: 'system',
|
|
4300
|
+
content: `[RECONNECTION RECOVERY: The previous peer turn disconnected or returned no response.${planNotice} Disk files and modifications are preserved. Do NOT repeat completed work. Continue executing the next unfinished step of the task directly.]`
|
|
4301
|
+
});
|
|
4302
|
+
this.memoryManager.saveHistory(this.messages);
|
|
4303
|
+
await this.backoff(emptyResponseRecoveries);
|
|
4304
|
+
continue;
|
|
4305
|
+
}
|
|
4306
|
+
}
|
|
4351
4307
|
if (this.stopRequested || this.abortController?.signal?.aborted || e?.name === 'AbortError') {
|
|
4352
4308
|
this.debugLog(`agent loop interrupted: ${e?.message || 'aborted'}`);
|
|
4353
4309
|
auditLog.log({ event: 'task_interrupted', taskId: this.taskId });
|
|
@@ -63,10 +63,24 @@ export class SovereignReverseHarness {
|
|
|
63
63
|
break;
|
|
64
64
|
}
|
|
65
65
|
}
|
|
66
|
+
const nodeDir = path.dirname(process.execPath);
|
|
67
|
+
const homeDir = process.env.HOME || '';
|
|
68
|
+
const buildToolsDirs = [
|
|
69
|
+
path.join(homeDir, 'Library/Android/sdk/build-tools/36.1.0'),
|
|
70
|
+
path.join(homeDir, 'Library/Android/sdk/build-tools/35.0.0'),
|
|
71
|
+
path.join(homeDir, 'Library/Android/sdk/platform-tools'),
|
|
72
|
+
'/opt/homebrew/bin',
|
|
73
|
+
'/usr/local/bin'
|
|
74
|
+
].filter(d => fs.existsSync(d));
|
|
75
|
+
const augmentedPath = [nodeDir, ...buildToolsDirs, process.env.PATH || ''].join(':');
|
|
66
76
|
const mcpClient = new McpClient({
|
|
67
77
|
name: 'causyne_reverse_engineering',
|
|
68
78
|
command,
|
|
69
79
|
args,
|
|
80
|
+
env: {
|
|
81
|
+
...process.env,
|
|
82
|
+
PATH: augmentedPath
|
|
83
|
+
},
|
|
70
84
|
timeoutMs: 60_000
|
|
71
85
|
});
|
|
72
86
|
await mcpClient.connect();
|
|
@@ -163,15 +177,23 @@ export class SovereignReverseHarness {
|
|
|
163
177
|
const ext = path.extname(resolved).toLowerCase();
|
|
164
178
|
if (ext === '.apk' || ext === '.aab') {
|
|
165
179
|
const pkg = await this.callEngineTool('inspect_android_package', { path: resolved }, signal);
|
|
166
|
-
if (pkg.success)
|
|
180
|
+
if (pkg.success && pkg.output && !pkg.output.includes('capability_unavailable') && !pkg.output.includes('REA_JADX_MCP_JAR')) {
|
|
167
181
|
return pkg;
|
|
182
|
+
}
|
|
168
183
|
const dec = await this.callEngineTool('decode_android_resources', { path: resolved }, signal);
|
|
169
|
-
if (dec.success)
|
|
184
|
+
if (dec.success && dec.output && !dec.output.includes('capability_unavailable') && !dec.output.includes('apktool launcher was not found')) {
|
|
170
185
|
return dec;
|
|
186
|
+
}
|
|
187
|
+
return {
|
|
188
|
+
success: false,
|
|
189
|
+
toolName: 'inspect_android_package',
|
|
190
|
+
error: 'Engine APK tools unavailable; delegating to sovereign native inspector.',
|
|
191
|
+
source: 'fallback'
|
|
192
|
+
};
|
|
171
193
|
}
|
|
172
194
|
// Try primary session / overview tools
|
|
173
195
|
const open = await this.callEngineTool('open_binary', { path: resolved }, signal);
|
|
174
|
-
if (open.success)
|
|
196
|
+
if (open.success && open.output && !open.output.includes('"architecture":null'))
|
|
175
197
|
return open;
|
|
176
198
|
const layout = await this.callEngineTool('inspect_binary_layout', { path: resolved }, signal);
|
|
177
199
|
if (layout.success)
|