@balchemyai/agent-sdk 0.8.1 → 0.9.0
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/CHANGELOG.md +16 -1
- package/README.md +20 -284
- package/dist/agent-loop/llm-adapters/openai.js +1 -1
- package/dist/agent-loop/llm-adapters/openai.js.map +1 -1
- package/dist/agent-loop/types.d.ts +1 -138
- package/dist/agent-loop/types.d.ts.map +1 -1
- package/dist/index.d.ts +1 -33
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -72
- package/dist/index.js.map +1 -1
- package/docs/error-retry-strategy.md +4 -4
- package/docs/release-policy.md +1 -1
- package/package.json +2 -6
- package/dist/agent-loop/agent-loop.d.ts +0 -77
- package/dist/agent-loop/agent-loop.d.ts.map +0 -1
- package/dist/agent-loop/agent-loop.js +0 -1270
- package/dist/agent-loop/agent-loop.js.map +0 -1
- package/dist/agent-loop/decision-handler.d.ts +0 -38
- package/dist/agent-loop/decision-handler.d.ts.map +0 -1
- package/dist/agent-loop/decision-handler.js +0 -231
- package/dist/agent-loop/decision-handler.js.map +0 -1
- package/dist/agent-loop/llm-cost-tracker.d.ts +0 -27
- package/dist/agent-loop/llm-cost-tracker.d.ts.map +0 -1
- package/dist/agent-loop/llm-cost-tracker.js +0 -102
- package/dist/agent-loop/llm-cost-tracker.js.map +0 -1
- package/dist/agent-loop/model-router.d.ts +0 -35
- package/dist/agent-loop/model-router.d.ts.map +0 -1
- package/dist/agent-loop/model-router.js +0 -55
- package/dist/agent-loop/model-router.js.map +0 -1
- package/dist/agent-loop/rule-checker.d.ts +0 -26
- package/dist/agent-loop/rule-checker.d.ts.map +0 -1
- package/dist/agent-loop/rule-checker.js +0 -70
- package/dist/agent-loop/rule-checker.js.map +0 -1
- package/dist/agent-loop/telemetry-reporter.d.ts +0 -70
- package/dist/agent-loop/telemetry-reporter.d.ts.map +0 -1
- package/dist/agent-loop/telemetry-reporter.js +0 -221
- package/dist/agent-loop/telemetry-reporter.js.map +0 -1
- package/dist/agent-loop/webhook-receiver.d.ts +0 -41
- package/dist/agent-loop/webhook-receiver.d.ts.map +0 -1
- package/dist/agent-loop/webhook-receiver.js +0 -308
- package/dist/agent-loop/webhook-receiver.js.map +0 -1
- package/dist/auth/onboarding.d.ts +0 -12
- package/dist/auth/onboarding.d.ts.map +0 -1
- package/dist/auth/onboarding.js +0 -70
- package/dist/auth/onboarding.js.map +0 -1
- package/dist/auth/token-store.d.ts +0 -44
- package/dist/auth/token-store.d.ts.map +0 -1
- package/dist/auth/token-store.js +0 -67
- package/dist/auth/token-store.js.map +0 -1
- package/dist/mcp/mcp-client.d.ts +0 -174
- package/dist/mcp/mcp-client.d.ts.map +0 -1
- package/dist/mcp/mcp-client.js +0 -845
- package/dist/mcp/mcp-client.js.map +0 -1
- package/dist/streaming/sse-event-stream.d.ts +0 -72
- package/dist/streaming/sse-event-stream.d.ts.map +0 -1
- package/dist/streaming/sse-event-stream.js +0 -403
- package/dist/streaming/sse-event-stream.js.map +0 -1
- package/dist/types.d.ts +0 -162
- package/dist/types.d.ts.map +0 -1
- package/dist/types.js +0 -3
- package/dist/types.js.map +0 -1
- package/dist/utils/package-version.d.ts +0 -2
- package/dist/utils/package-version.d.ts.map +0 -1
- package/dist/utils/package-version.js +0 -54
- package/dist/utils/package-version.js.map +0 -1
- package/docs/BEHAVIOR_RULES.md +0 -184
- package/docs/DEPLOYMENT.md +0 -197
- package/docs/QUICKSTART.md +0 -139
- package/docs/examples/custom-strategy.yaml +0 -73
- package/docs/examples/dca-accumulator.yaml +0 -41
- package/docs/examples/memecoin-sniper.yaml +0 -47
- package/docs/examples/swing-trader.yaml +0 -50
- package/docs/partner-integration-checklist.md +0 -47
- package/docs/python-parity-backlog.md +0 -20
|
@@ -1,1270 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.AgentLoop = void 0;
|
|
4
|
-
const sse_event_stream_1 = require("../streaming/sse-event-stream");
|
|
5
|
-
const node_crypto_1 = require("node:crypto");
|
|
6
|
-
const mcp_client_1 = require("../mcp/mcp-client");
|
|
7
|
-
const llm_cost_tracker_1 = require("./llm-cost-tracker");
|
|
8
|
-
const decision_handler_1 = require("./decision-handler");
|
|
9
|
-
const webhook_receiver_1 = require("./webhook-receiver");
|
|
10
|
-
const openai_1 = require("./llm-adapters/openai");
|
|
11
|
-
const anthropic_1 = require("./llm-adapters/anthropic");
|
|
12
|
-
const model_router_1 = require("./model-router");
|
|
13
|
-
const telemetry_reporter_1 = require("./telemetry-reporter");
|
|
14
|
-
const rule_checker_1 = require("./rule-checker");
|
|
15
|
-
const redaction_1 = require("../utils/redaction");
|
|
16
|
-
const PORTFOLIO_TTL_MS = 30_000; // 30 seconds
|
|
17
|
-
const RULES_TTL_MS = 5 * 60_000; // 5 minutes
|
|
18
|
-
const RULES_FAILURE_TTL_MS = 30_000; // 30 seconds
|
|
19
|
-
const DEFAULT_MAX_PENDING_EVENTS = 100;
|
|
20
|
-
const DEFAULT_MAX_EVENT_AGE_MS = 5 * 60_000;
|
|
21
|
-
const DEFAULT_MAX_EVIDENCE_AGE_MS = 90_000;
|
|
22
|
-
const MAX_FUTURE_SKEW_MS = 5_000;
|
|
23
|
-
const STOP_DRAIN_TIMEOUT_MS = 5_000;
|
|
24
|
-
const REVISION_ID_RE = /^brr_[a-f0-9]{64}$/;
|
|
25
|
-
const SHA256_DIGEST_RE = /^sha256:[a-f0-9]{64}$/;
|
|
26
|
-
function asRecord(value) {
|
|
27
|
-
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
28
|
-
? value
|
|
29
|
-
: null;
|
|
30
|
-
}
|
|
31
|
-
function stablePolicyValue(value) {
|
|
32
|
-
if (Array.isArray(value)) {
|
|
33
|
-
return `[${value.map(stablePolicyValue).join(',')}]`;
|
|
34
|
-
}
|
|
35
|
-
const record = asRecord(value);
|
|
36
|
-
if (record) {
|
|
37
|
-
return `{${Object.keys(record).sort().map((key) => `${JSON.stringify(key)}:${stablePolicyValue(record[key])}`).join(',')}}`;
|
|
38
|
-
}
|
|
39
|
-
return JSON.stringify(value) ?? 'null';
|
|
40
|
-
}
|
|
41
|
-
function isFinitePositiveOrNull(value) {
|
|
42
|
-
return value === null || (typeof value === 'number' && Number.isFinite(value) && value > 0);
|
|
43
|
-
}
|
|
44
|
-
function parseBehaviorRuleBinding(value) {
|
|
45
|
-
const resource = asRecord(value);
|
|
46
|
-
const revision = asRecord(resource?.revision) ?? resource;
|
|
47
|
-
const compiled = asRecord(revision?.compiled);
|
|
48
|
-
const executionPolicy = asRecord(resource?.executionPolicy);
|
|
49
|
-
if (!revision || !compiled || !executionPolicy)
|
|
50
|
-
return null;
|
|
51
|
-
const revisionId = revision.revisionId;
|
|
52
|
-
const schemaVersion = revision.schemaVersion;
|
|
53
|
-
const revisionNumber = revision.revision;
|
|
54
|
-
const chain = revision.chain;
|
|
55
|
-
const compilerVersion = revision.compilerVersion;
|
|
56
|
-
const source = asRecord(revision.source);
|
|
57
|
-
const sourceDigest = source?.sourceDigest;
|
|
58
|
-
const rulesDigest = revision.rulesDigest;
|
|
59
|
-
const compiledDigest = revision.compiledDigest;
|
|
60
|
-
const compilationStatus = revision.compilationStatus;
|
|
61
|
-
const diagnostics = revision.diagnostics;
|
|
62
|
-
const compressedRules = compiled.compressedRules;
|
|
63
|
-
const policyRevisionRecord = asRecord(executionPolicy.revision);
|
|
64
|
-
const policyRevision = parseBehaviorRuleIdentityPin({ ruleRevision: executionPolicy.revision });
|
|
65
|
-
const sizing = asRecord(executionPolicy.sizing);
|
|
66
|
-
const entry = asRecord(executionPolicy.entry);
|
|
67
|
-
const exit = asRecord(executionPolicy.exit);
|
|
68
|
-
const approval = asRecord(executionPolicy.approval);
|
|
69
|
-
const policyDigest = executionPolicy.policyDigest;
|
|
70
|
-
const policyWithoutDigest = Object.fromEntries(Object.entries(executionPolicy).filter(([key]) => key !== 'policyDigest'));
|
|
71
|
-
const computedPolicyDigest = `sha256:${(0, node_crypto_1.createHash)('sha256')
|
|
72
|
-
.update(stablePolicyValue(policyWithoutDigest), 'utf8')
|
|
73
|
-
.digest('hex')}`;
|
|
74
|
-
if (resource?.status !== 'active'
|
|
75
|
-
|| resource?.executionPolicyStatus !== 'executable'
|
|
76
|
-
|| schemaVersion !== 'balchemy.behavior-rule-revision.v1'
|
|
77
|
-
|| typeof revisionId !== 'string'
|
|
78
|
-
|| !REVISION_ID_RE.test(revisionId)
|
|
79
|
-
|| typeof revisionNumber !== 'number'
|
|
80
|
-
|| !Number.isSafeInteger(revisionNumber)
|
|
81
|
-
|| revisionNumber < 1
|
|
82
|
-
|| (chain !== null && chain !== 'solana' && chain !== 'base')
|
|
83
|
-
|| typeof compilerVersion !== 'string'
|
|
84
|
-
|| compilerVersion.trim().length === 0
|
|
85
|
-
|| typeof sourceDigest !== 'string'
|
|
86
|
-
|| !SHA256_DIGEST_RE.test(sourceDigest)
|
|
87
|
-
|| typeof rulesDigest !== 'string'
|
|
88
|
-
|| !SHA256_DIGEST_RE.test(rulesDigest)
|
|
89
|
-
|| typeof compiledDigest !== 'string'
|
|
90
|
-
|| !SHA256_DIGEST_RE.test(compiledDigest)
|
|
91
|
-
|| compilationStatus !== 'compiled'
|
|
92
|
-
|| !Array.isArray(diagnostics)
|
|
93
|
-
|| diagnostics.length > 0
|
|
94
|
-
|| typeof compressedRules !== 'string'
|
|
95
|
-
|| compressedRules.trim().length === 0
|
|
96
|
-
|| compressedRules.length > 64 * 1024
|
|
97
|
-
|| executionPolicy.schemaVersion !== 'balchemy.behavior-rule-execution-policy.v1'
|
|
98
|
-
|| !policyRevision
|
|
99
|
-
|| !policyRevisionRecord
|
|
100
|
-
|| !Array.isArray(policyRevisionRecord.diagnostics)
|
|
101
|
-
|| policyRevisionRecord.diagnostics.length !== 0
|
|
102
|
-
|| policyRevision.revisionId !== revisionId
|
|
103
|
-
|| policyRevision.revision !== revisionNumber
|
|
104
|
-
|| policyRevision.chain !== chain
|
|
105
|
-
|| policyRevision.compilerVersion !== compilerVersion
|
|
106
|
-
|| policyRevision.sourceDigest !== sourceDigest
|
|
107
|
-
|| policyRevision.rulesDigest !== rulesDigest
|
|
108
|
-
|| policyRevision.compiledDigest !== compiledDigest
|
|
109
|
-
|| !sizing
|
|
110
|
-
|| sizing.mode !== 'outer_decision_bounded_by_revision'
|
|
111
|
-
|| (sizing.nativeAmountUnit !== null && sizing.nativeAmountUnit !== 'SOL' && sizing.nativeAmountUnit !== 'ETH')
|
|
112
|
-
|| !isFinitePositiveOrNull(sizing.maxTradeNative)
|
|
113
|
-
|| !isFinitePositiveOrNull(sizing.maxTradesPerHour)
|
|
114
|
-
|| !entry
|
|
115
|
-
|| !exit
|
|
116
|
-
|| typeof exit.stopLossPct !== 'number'
|
|
117
|
-
|| !Number.isFinite(exit.stopLossPct)
|
|
118
|
-
|| !approval
|
|
119
|
-
|| typeof approval.confirmBeforeTrade !== 'boolean'
|
|
120
|
-
|| !isFinitePositiveOrNull(approval.requireApprovalAboveUsd)
|
|
121
|
-
|| typeof approval.requireApprovalForNewTokens !== 'boolean'
|
|
122
|
-
|| typeof executionPolicy.shadowMode !== 'boolean'
|
|
123
|
-
|| typeof policyDigest !== 'string'
|
|
124
|
-
|| !SHA256_DIGEST_RE.test(policyDigest)
|
|
125
|
-
|| computedPolicyDigest !== policyDigest) {
|
|
126
|
-
return null;
|
|
127
|
-
}
|
|
128
|
-
return {
|
|
129
|
-
schemaVersion,
|
|
130
|
-
revisionId,
|
|
131
|
-
revision: revisionNumber,
|
|
132
|
-
chain,
|
|
133
|
-
compilerVersion,
|
|
134
|
-
sourceDigest,
|
|
135
|
-
rulesDigest,
|
|
136
|
-
compiledDigest,
|
|
137
|
-
compilationStatus,
|
|
138
|
-
diagnostics: [],
|
|
139
|
-
compressedRules,
|
|
140
|
-
executionPolicy: {
|
|
141
|
-
policyDigest,
|
|
142
|
-
sizing: {
|
|
143
|
-
nativeAmountUnit: sizing.nativeAmountUnit,
|
|
144
|
-
maxTradeNative: sizing.maxTradeNative,
|
|
145
|
-
maxTradesPerHour: sizing.maxTradesPerHour,
|
|
146
|
-
},
|
|
147
|
-
exit,
|
|
148
|
-
},
|
|
149
|
-
};
|
|
150
|
-
}
|
|
151
|
-
function behaviorRuleBindingsMatch(expected, actual) {
|
|
152
|
-
return expected.revisionId === actual.revisionId
|
|
153
|
-
&& expected.schemaVersion === actual.schemaVersion
|
|
154
|
-
&& expected.revision === actual.revision
|
|
155
|
-
&& expected.chain === actual.chain
|
|
156
|
-
&& expected.compilerVersion === actual.compilerVersion
|
|
157
|
-
&& expected.sourceDigest === actual.sourceDigest
|
|
158
|
-
&& expected.rulesDigest === actual.rulesDigest
|
|
159
|
-
&& expected.compiledDigest === actual.compiledDigest
|
|
160
|
-
&& expected.executionPolicy.policyDigest === actual.executionPolicy.policyDigest;
|
|
161
|
-
}
|
|
162
|
-
function parseBehaviorRuleIdentityPin(value) {
|
|
163
|
-
const record = asRecord(value);
|
|
164
|
-
if (!record)
|
|
165
|
-
return null;
|
|
166
|
-
const candidate = asRecord(record.rule_revision) ?? asRecord(record.ruleRevision);
|
|
167
|
-
if (candidate) {
|
|
168
|
-
const revisionId = candidate.revisionId;
|
|
169
|
-
const revision = candidate.revision;
|
|
170
|
-
const chain = candidate.chain;
|
|
171
|
-
const compilerVersion = candidate.compilerVersion;
|
|
172
|
-
const sourceDigest = candidate.sourceDigest;
|
|
173
|
-
const rulesDigest = candidate.rulesDigest;
|
|
174
|
-
const compiledDigest = candidate.compiledDigest;
|
|
175
|
-
if (candidate.schemaVersion === 'balchemy.behavior-rule-revision.v1'
|
|
176
|
-
&& typeof revisionId === 'string'
|
|
177
|
-
&& REVISION_ID_RE.test(revisionId)
|
|
178
|
-
&& typeof revision === 'number'
|
|
179
|
-
&& Number.isSafeInteger(revision)
|
|
180
|
-
&& revision > 0
|
|
181
|
-
&& (chain === null || chain === 'solana' || chain === 'base')
|
|
182
|
-
&& typeof compilerVersion === 'string'
|
|
183
|
-
&& compilerVersion.trim().length > 0
|
|
184
|
-
&& candidate.compilationStatus === 'compiled'
|
|
185
|
-
&& typeof sourceDigest === 'string'
|
|
186
|
-
&& SHA256_DIGEST_RE.test(sourceDigest)
|
|
187
|
-
&& typeof rulesDigest === 'string'
|
|
188
|
-
&& SHA256_DIGEST_RE.test(rulesDigest)
|
|
189
|
-
&& typeof compiledDigest === 'string'
|
|
190
|
-
&& SHA256_DIGEST_RE.test(compiledDigest)) {
|
|
191
|
-
return {
|
|
192
|
-
schemaVersion: 'balchemy.behavior-rule-revision.v1',
|
|
193
|
-
revisionId,
|
|
194
|
-
revision,
|
|
195
|
-
chain,
|
|
196
|
-
compilerVersion,
|
|
197
|
-
sourceDigest,
|
|
198
|
-
rulesDigest,
|
|
199
|
-
compiledDigest,
|
|
200
|
-
compilationStatus: 'compiled',
|
|
201
|
-
};
|
|
202
|
-
}
|
|
203
|
-
return null;
|
|
204
|
-
}
|
|
205
|
-
for (const key of ['event', 'data', 'delta', 'payload']) {
|
|
206
|
-
const nested = parseBehaviorRuleIdentityPin(record[key]);
|
|
207
|
-
if (nested)
|
|
208
|
-
return nested;
|
|
209
|
-
}
|
|
210
|
-
return null;
|
|
211
|
-
}
|
|
212
|
-
function behaviorRuleBindingMatchesPin(binding, pin) {
|
|
213
|
-
return binding.schemaVersion === pin.schemaVersion
|
|
214
|
-
&& binding.revisionId === pin.revisionId
|
|
215
|
-
&& binding.revision === pin.revision
|
|
216
|
-
&& binding.chain === pin.chain
|
|
217
|
-
&& binding.compilerVersion === pin.compilerVersion
|
|
218
|
-
&& binding.compilationStatus === pin.compilationStatus
|
|
219
|
-
&& binding.sourceDigest === pin.sourceDigest
|
|
220
|
-
&& binding.rulesDigest === pin.rulesDigest
|
|
221
|
-
&& binding.compiledDigest === pin.compiledDigest;
|
|
222
|
-
}
|
|
223
|
-
function buildRuntimeStatusSnapshot(parsed) {
|
|
224
|
-
const structured = asRecord(parsed.structured) ?? parsed;
|
|
225
|
-
const reply = typeof parsed.reply === 'string' && parsed.reply.trim()
|
|
226
|
-
? parsed.reply
|
|
227
|
-
: undefined;
|
|
228
|
-
return {
|
|
229
|
-
...(reply ? { summary: reply } : {}),
|
|
230
|
-
runtimeStatus: structured,
|
|
231
|
-
};
|
|
232
|
-
}
|
|
233
|
-
function getAutonomousRuntimeState(snapshot) {
|
|
234
|
-
const runtimeStatus = asRecord(snapshot.runtimeStatus);
|
|
235
|
-
return asRecord(runtimeStatus?.autonomous_runtime)
|
|
236
|
-
?? asRecord(runtimeStatus?.autonomousRuntime)
|
|
237
|
-
?? asRecord(snapshot.autonomous_runtime)
|
|
238
|
-
?? asRecord(snapshot.autonomousRuntime);
|
|
239
|
-
}
|
|
240
|
-
function isRuntimeLiveArmed(snapshot) {
|
|
241
|
-
const runtime = getAutonomousRuntimeState(snapshot);
|
|
242
|
-
if (!runtime) {
|
|
243
|
-
return false;
|
|
244
|
-
}
|
|
245
|
-
return runtime.mode === 'live_armed'
|
|
246
|
-
&& runtime.armed === true
|
|
247
|
-
&& runtime.paused !== true;
|
|
248
|
-
}
|
|
249
|
-
function isRuntimePaused(snapshot) {
|
|
250
|
-
const runtime = getAutonomousRuntimeState(snapshot);
|
|
251
|
-
return runtime?.paused === true || runtime?.mode === 'paused';
|
|
252
|
-
}
|
|
253
|
-
function hasRuntimeStatusSnapshot(snapshot) {
|
|
254
|
-
const runtimeStatus = asRecord(snapshot.runtimeStatus);
|
|
255
|
-
return Boolean(runtimeStatus && Object.keys(runtimeStatus).length > 0);
|
|
256
|
-
}
|
|
257
|
-
const VALID_AMOUNT_SOURCES = new Set(['rules', 'config', 'explicit_user']);
|
|
258
|
-
const GOOD_SOURCE_HEALTH_VALUES = new Set([
|
|
259
|
-
'available',
|
|
260
|
-
'fresh',
|
|
261
|
-
'healthy',
|
|
262
|
-
'ok',
|
|
263
|
-
]);
|
|
264
|
-
const BAD_SOURCE_HEALTH_VALUES = new Set([
|
|
265
|
-
'blocked',
|
|
266
|
-
'degraded',
|
|
267
|
-
'error',
|
|
268
|
-
'failed',
|
|
269
|
-
'failing',
|
|
270
|
-
'no_data',
|
|
271
|
-
'quota_blocked',
|
|
272
|
-
'rate_limited',
|
|
273
|
-
'stale',
|
|
274
|
-
'unavailable',
|
|
275
|
-
'unknown',
|
|
276
|
-
]);
|
|
277
|
-
function normalizeTradeChain(chain) {
|
|
278
|
-
const normalized = chain?.trim().toLowerCase();
|
|
279
|
-
if (normalized === 'solana' || normalized === 'sol')
|
|
280
|
-
return 'solana';
|
|
281
|
-
if (normalized === 'base')
|
|
282
|
-
return 'base';
|
|
283
|
-
return null;
|
|
284
|
-
}
|
|
285
|
-
function getEventRuleChain(event) {
|
|
286
|
-
const visit = (value, depth) => {
|
|
287
|
-
if (depth > 3)
|
|
288
|
-
return null;
|
|
289
|
-
const record = asRecord(value);
|
|
290
|
-
if (!record)
|
|
291
|
-
return null;
|
|
292
|
-
const direct = typeof record.chain === 'string'
|
|
293
|
-
? normalizeTradeChain(record.chain)
|
|
294
|
-
: null;
|
|
295
|
-
if (direct)
|
|
296
|
-
return direct;
|
|
297
|
-
for (const key of ['event', 'data', 'delta', 'payload']) {
|
|
298
|
-
const nested = visit(record[key], depth + 1);
|
|
299
|
-
if (nested)
|
|
300
|
-
return nested;
|
|
301
|
-
}
|
|
302
|
-
if (Array.isArray(record.events)) {
|
|
303
|
-
for (const item of record.events) {
|
|
304
|
-
const nested = visit(item, depth + 1);
|
|
305
|
-
if (nested)
|
|
306
|
-
return nested;
|
|
307
|
-
}
|
|
308
|
-
}
|
|
309
|
-
return null;
|
|
310
|
-
};
|
|
311
|
-
return visit(event.data, 0);
|
|
312
|
-
}
|
|
313
|
-
function isNonEmptyString(value) {
|
|
314
|
-
return typeof value === 'string' && value.trim().length > 0;
|
|
315
|
-
}
|
|
316
|
-
function isNonEmptyObject(value) {
|
|
317
|
-
const record = asRecord(value);
|
|
318
|
-
return Boolean(record && Object.keys(record).length > 0);
|
|
319
|
-
}
|
|
320
|
-
function isStringArray(value) {
|
|
321
|
-
return Array.isArray(value) && value.every((item) => typeof item === 'string');
|
|
322
|
-
}
|
|
323
|
-
function hasExitPolicy(value) {
|
|
324
|
-
return isNonEmptyString(value) || isNonEmptyObject(value);
|
|
325
|
-
}
|
|
326
|
-
function parseEvidenceTimestamp(value) {
|
|
327
|
-
if (typeof value === 'number') {
|
|
328
|
-
return Number.isSafeInteger(value) && value > 0 ? value : null;
|
|
329
|
-
}
|
|
330
|
-
if (typeof value !== 'string' || value.length === 0 || value.length > 64)
|
|
331
|
-
return null;
|
|
332
|
-
const parsed = Date.parse(value);
|
|
333
|
-
return Number.isFinite(parsed) && parsed > 0 ? parsed : null;
|
|
334
|
-
}
|
|
335
|
-
function sourceHealthIsUsable(value, maxAgeMs, now = Date.now()) {
|
|
336
|
-
const initialRecords = Array.isArray(value)
|
|
337
|
-
? value.map(asRecord).filter((item) => item !== null)
|
|
338
|
-
: [asRecord(value)].filter((item) => item !== null);
|
|
339
|
-
if (initialRecords.length === 0 || initialRecords.some((record) => Object.keys(record).length === 0)) {
|
|
340
|
-
return false;
|
|
341
|
-
}
|
|
342
|
-
let sawPositiveHealthSignal = false;
|
|
343
|
-
let sawFreshHealthSignal = false;
|
|
344
|
-
const stack = [...initialRecords];
|
|
345
|
-
while (stack.length > 0) {
|
|
346
|
-
const current = stack.pop();
|
|
347
|
-
if (!current) {
|
|
348
|
-
continue;
|
|
349
|
-
}
|
|
350
|
-
if (current.ok === false || current.degraded === true || current.unavailable === true) {
|
|
351
|
-
return false;
|
|
352
|
-
}
|
|
353
|
-
let currentHasHealthSignal = false;
|
|
354
|
-
if (current.ok === true) {
|
|
355
|
-
sawPositiveHealthSignal = true;
|
|
356
|
-
currentHasHealthSignal = true;
|
|
357
|
-
}
|
|
358
|
-
for (const key of ['status', 'state', 'health', 'sourceStatus']) {
|
|
359
|
-
const raw = current[key];
|
|
360
|
-
if (typeof raw !== 'string') {
|
|
361
|
-
continue;
|
|
362
|
-
}
|
|
363
|
-
const normalized = raw.trim().toLowerCase();
|
|
364
|
-
if (BAD_SOURCE_HEALTH_VALUES.has(normalized)) {
|
|
365
|
-
return false;
|
|
366
|
-
}
|
|
367
|
-
if (GOOD_SOURCE_HEALTH_VALUES.has(normalized)) {
|
|
368
|
-
sawPositiveHealthSignal = true;
|
|
369
|
-
currentHasHealthSignal = true;
|
|
370
|
-
}
|
|
371
|
-
}
|
|
372
|
-
if (currentHasHealthSignal) {
|
|
373
|
-
const timestamp = parseEvidenceTimestamp(current.fetchedAt
|
|
374
|
-
?? current.observedAt
|
|
375
|
-
?? current.observed_at_ms
|
|
376
|
-
?? current.observed_at
|
|
377
|
-
?? current.timestamp
|
|
378
|
-
?? current.ts);
|
|
379
|
-
if (timestamp === null
|
|
380
|
-
|| timestamp > now + MAX_FUTURE_SKEW_MS
|
|
381
|
-
|| now - timestamp > maxAgeMs) {
|
|
382
|
-
return false;
|
|
383
|
-
}
|
|
384
|
-
sawFreshHealthSignal = true;
|
|
385
|
-
}
|
|
386
|
-
for (const key of ['sources', 'sourceHealth', 'source_health', 'providers', 'sourceStatuses']) {
|
|
387
|
-
const nested = current[key];
|
|
388
|
-
if (Array.isArray(nested)) {
|
|
389
|
-
stack.push(...nested.map(asRecord).filter((item) => item !== null));
|
|
390
|
-
continue;
|
|
391
|
-
}
|
|
392
|
-
const nestedRecord = asRecord(nested);
|
|
393
|
-
if (nestedRecord) {
|
|
394
|
-
stack.push(nestedRecord);
|
|
395
|
-
stack.push(...Object.values(nestedRecord).map(asRecord).filter((item) => item !== null));
|
|
396
|
-
}
|
|
397
|
-
}
|
|
398
|
-
}
|
|
399
|
-
return sawPositiveHealthSignal && sawFreshHealthSignal;
|
|
400
|
-
}
|
|
401
|
-
function validateExecutableTradeDecision(decision, maxEvidenceAgeMs) {
|
|
402
|
-
if (!isNonEmptyString(decision.token)) {
|
|
403
|
-
return { allowed: false, action: 'blocked', reason: 'decision is missing exact token' };
|
|
404
|
-
}
|
|
405
|
-
if (!isNonEmptyString(decision.amount)) {
|
|
406
|
-
return { allowed: false, action: 'blocked', reason: 'decision is missing exact amount' };
|
|
407
|
-
}
|
|
408
|
-
if (!/^\d+(?:\.\d+)?$/.test(decision.amount.trim())) {
|
|
409
|
-
return { allowed: false, action: 'blocked', reason: 'decision amount must be numeric without a unit suffix' };
|
|
410
|
-
}
|
|
411
|
-
if (!Number.isFinite(Number.parseFloat(decision.amount)) || Number.parseFloat(decision.amount) <= 0) {
|
|
412
|
-
return { allowed: false, action: 'blocked', reason: 'decision amount is not a positive number' };
|
|
413
|
-
}
|
|
414
|
-
if (!isNonEmptyString(decision.amountUnit)) {
|
|
415
|
-
return { allowed: false, action: 'blocked', reason: 'decision is missing amount unit' };
|
|
416
|
-
}
|
|
417
|
-
const chain = normalizeTradeChain(decision.chain);
|
|
418
|
-
if (!chain) {
|
|
419
|
-
return { allowed: false, action: 'blocked', reason: 'decision is missing an explicit supported chain' };
|
|
420
|
-
}
|
|
421
|
-
if (!isNonEmptyString(decision.amountSource) || !VALID_AMOUNT_SOURCES.has(decision.amountSource.trim())) {
|
|
422
|
-
return { allowed: false, action: 'blocked', reason: 'decision amount source is missing or unsupported' };
|
|
423
|
-
}
|
|
424
|
-
if (!isNonEmptyString(decision.evidenceId)) {
|
|
425
|
-
return { allowed: false, action: 'blocked', reason: 'decision is missing evidence id' };
|
|
426
|
-
}
|
|
427
|
-
if (!sourceHealthIsUsable(decision.sourceHealth, maxEvidenceAgeMs)) {
|
|
428
|
-
return { allowed: false, action: 'degraded', reason: 'source health is missing, stale, future-dated, or degraded' };
|
|
429
|
-
}
|
|
430
|
-
if (!isStringArray(decision.missingFacts)) {
|
|
431
|
-
return { allowed: false, action: 'blocked', reason: 'missingFacts must be an explicit array' };
|
|
432
|
-
}
|
|
433
|
-
if (decision.missingFacts.length > 0) {
|
|
434
|
-
return { allowed: false, action: 'blocked', reason: `decision has missing facts: ${decision.missingFacts.join(', ')}` };
|
|
435
|
-
}
|
|
436
|
-
if (Array.isArray(decision.requiredApprovals) && decision.requiredApprovals.length > 0) {
|
|
437
|
-
return { allowed: false, action: 'approval_required', reason: `required approvals: ${decision.requiredApprovals.join(', ')}` };
|
|
438
|
-
}
|
|
439
|
-
if (!hasExitPolicy(decision.exitPolicy)) {
|
|
440
|
-
return { allowed: false, action: 'blocked', reason: 'decision is missing exit policy' };
|
|
441
|
-
}
|
|
442
|
-
if (decision.action === 'buy' && decision.token.trim().toLowerCase() === decision.amountUnit.trim().toLowerCase()) {
|
|
443
|
-
return { allowed: false, action: 'blocked', reason: 'buy target token matches spend unit' };
|
|
444
|
-
}
|
|
445
|
-
return { allowed: true, chain, amountUnit: decision.amountUnit.trim() };
|
|
446
|
-
}
|
|
447
|
-
function buildTradeCommandMessage(decision, chain, amountUnit) {
|
|
448
|
-
return `${decision.action} ${decision.amount} ${amountUnit} ${decision.token} on ${chain}`.trim();
|
|
449
|
-
}
|
|
450
|
-
function getToolResponseText(response) {
|
|
451
|
-
return response.content?.find((content) => content.type === 'text')?.text ?? '';
|
|
452
|
-
}
|
|
453
|
-
function getStringFromRecord(record, key) {
|
|
454
|
-
const value = record?.[key];
|
|
455
|
-
return typeof value === 'string' && value.trim().length > 0 ? value.trim() : undefined;
|
|
456
|
-
}
|
|
457
|
-
function getPlainResponseStatusText(responseText) {
|
|
458
|
-
const trimmed = responseText.trim();
|
|
459
|
-
if (!trimmed || trimmed.startsWith('{') || trimmed.startsWith('[')) {
|
|
460
|
-
return undefined;
|
|
461
|
-
}
|
|
462
|
-
return trimmed;
|
|
463
|
-
}
|
|
464
|
-
function hasAnyKey(record, keys) {
|
|
465
|
-
if (!record) {
|
|
466
|
-
return false;
|
|
467
|
-
}
|
|
468
|
-
return keys.some((key) => record[key] !== undefined && record[key] !== null);
|
|
469
|
-
}
|
|
470
|
-
function hasBroadcastReference(record, depth = 0) {
|
|
471
|
-
if (!record || depth > 3) {
|
|
472
|
-
return false;
|
|
473
|
-
}
|
|
474
|
-
if (hasAnyKey(record, [
|
|
475
|
-
'transactionHash',
|
|
476
|
-
'transaction_hash',
|
|
477
|
-
'txHash',
|
|
478
|
-
'tx_hash',
|
|
479
|
-
'signature',
|
|
480
|
-
])) {
|
|
481
|
-
return true;
|
|
482
|
-
}
|
|
483
|
-
for (const key of ['order', 'data', 'result', 'execution', 'transaction']) {
|
|
484
|
-
const nested = asRecord(record[key]);
|
|
485
|
-
if (nested && hasBroadcastReference(nested, depth + 1)) {
|
|
486
|
-
return true;
|
|
487
|
-
}
|
|
488
|
-
}
|
|
489
|
-
return false;
|
|
490
|
-
}
|
|
491
|
-
function collectTradeStatusText(record, depth = 0) {
|
|
492
|
-
if (!record || depth > 3) {
|
|
493
|
-
return [];
|
|
494
|
-
}
|
|
495
|
-
const values = [
|
|
496
|
-
getStringFromRecord(record, 'status'),
|
|
497
|
-
getStringFromRecord(record, 'state'),
|
|
498
|
-
getStringFromRecord(record, 'orderStatus'),
|
|
499
|
-
getStringFromRecord(record, 'message'),
|
|
500
|
-
].filter((value) => Boolean(value));
|
|
501
|
-
const requiresAction = asRecord(record.requiresAction);
|
|
502
|
-
if (requiresAction) {
|
|
503
|
-
values.push(...[
|
|
504
|
-
getStringFromRecord(requiresAction, 'type'),
|
|
505
|
-
getStringFromRecord(requiresAction, 'reason'),
|
|
506
|
-
getStringFromRecord(requiresAction, 'message'),
|
|
507
|
-
].filter((value) => Boolean(value)));
|
|
508
|
-
}
|
|
509
|
-
for (const key of ['order', 'data', 'result', 'execution', 'transaction']) {
|
|
510
|
-
values.push(...collectTradeStatusText(asRecord(record[key]), depth + 1));
|
|
511
|
-
}
|
|
512
|
-
return values;
|
|
513
|
-
}
|
|
514
|
-
function getTradeCommandResult(response) {
|
|
515
|
-
const parsed = (0, mcp_client_1.parseToolJson)(response);
|
|
516
|
-
const structured = asRecord(parsed?.structured);
|
|
517
|
-
return asRecord(structured?.result) ?? asRecord(parsed?.result);
|
|
518
|
-
}
|
|
519
|
-
function classifyTradeCommandOutcome(response, decision) {
|
|
520
|
-
const responseText = getToolResponseText(response);
|
|
521
|
-
const result = getTradeCommandResult(response);
|
|
522
|
-
const statusText = [
|
|
523
|
-
...collectTradeStatusText(result),
|
|
524
|
-
getPlainResponseStatusText(responseText),
|
|
525
|
-
].filter((value) => Boolean(value)).join(' ').toLowerCase();
|
|
526
|
-
if (/\b(?:not|never|no)\s+(?:accepted|broadcast|confirmed|executed|filled|submitted)\b/.test(statusText)
|
|
527
|
-
|| /\bdid\s+not\s+(?:accept|broadcast|confirm|execute|fill|submit)\b/.test(statusText)
|
|
528
|
-
|| /\bnot\s+confirmed\b/.test(statusText)) {
|
|
529
|
-
return { submitted: false, action: 'blocked', responseText };
|
|
530
|
-
}
|
|
531
|
-
if (/\b(approval|approve|confirm|confirmation|pending_approval)\b/.test(statusText)) {
|
|
532
|
-
return { submitted: false, action: 'approval_required', responseText };
|
|
533
|
-
}
|
|
534
|
-
if (result?.requiresAction === true || asRecord(result?.requiresAction) !== null) {
|
|
535
|
-
return { submitted: false, action: 'approval_required', responseText };
|
|
536
|
-
}
|
|
537
|
-
if (/\b(degraded|unavailable|rate[_ -]?limited|quota)\b/.test(statusText)) {
|
|
538
|
-
return { submitted: false, action: 'degraded', responseText };
|
|
539
|
-
}
|
|
540
|
-
if (response.isError === true || result?.success === false || /\b(blocked|denied|disabled|failed|failure|rejected|error)\b/.test(statusText)) {
|
|
541
|
-
return { submitted: false, action: 'blocked', responseText };
|
|
542
|
-
}
|
|
543
|
-
const accepted = hasBroadcastReference(result)
|
|
544
|
-
|| /\b(accepted|executed|submitted|broadcast|filled|confirmed)\b/.test(statusText);
|
|
545
|
-
if (accepted && decision.action !== 'hold') {
|
|
546
|
-
return { submitted: true, responseText };
|
|
547
|
-
}
|
|
548
|
-
const fallbackText = responseText || 'trade_command did not confirm a submitted or executed order.';
|
|
549
|
-
return {
|
|
550
|
-
submitted: false,
|
|
551
|
-
action: 'blocked',
|
|
552
|
-
responseText: fallbackText,
|
|
553
|
-
};
|
|
554
|
-
}
|
|
555
|
-
class AgentLoop {
|
|
556
|
-
config;
|
|
557
|
-
sseEndpoint;
|
|
558
|
-
costTracker;
|
|
559
|
-
llm;
|
|
560
|
-
decisionHandler;
|
|
561
|
-
mcp;
|
|
562
|
-
modelRouter;
|
|
563
|
-
telemetry;
|
|
564
|
-
webhookReceiver = null;
|
|
565
|
-
sseStream = null;
|
|
566
|
-
unsubscribeSse = null;
|
|
567
|
-
status = 'stopped';
|
|
568
|
-
startedAt = 0;
|
|
569
|
-
eventsReceived = 0;
|
|
570
|
-
eventsDropped = 0;
|
|
571
|
-
decisionsExecuted = 0;
|
|
572
|
-
tradesExecuted = 0;
|
|
573
|
-
lastEventAt;
|
|
574
|
-
lastTradeAt;
|
|
575
|
-
seenTraceIds = new Map();
|
|
576
|
-
pendingEvents = [];
|
|
577
|
-
drainPromise = null;
|
|
578
|
-
processingHalted = false;
|
|
579
|
-
lifecycleGeneration = 0;
|
|
580
|
-
portfolioCache = null;
|
|
581
|
-
rulesCache = null;
|
|
582
|
-
/** Client-side behavior rule limits for pre-check enforcement. */
|
|
583
|
-
/** Trades executed in the current clock-hour (reset each hour). */
|
|
584
|
-
tradesThisHour = 0;
|
|
585
|
-
/** Timestamp (ms) of the hour boundary when tradesThisHour was last reset. */
|
|
586
|
-
currentHourStart = 0;
|
|
587
|
-
/** publicId extracted from the MCP endpoint path (last path segment). */
|
|
588
|
-
publicId;
|
|
589
|
-
sessionId;
|
|
590
|
-
userMessageIdempotencyNamespace = (0, node_crypto_1.randomUUID)();
|
|
591
|
-
userMessageSequence = 0;
|
|
592
|
-
maxPendingEvents;
|
|
593
|
-
maxEventAgeMs;
|
|
594
|
-
maxEvidenceAgeMs;
|
|
595
|
-
constructor(config) {
|
|
596
|
-
this.config = config;
|
|
597
|
-
const mcpUrl = new URL(config.mcpEndpoint);
|
|
598
|
-
if ((mcpUrl.protocol !== 'https:' && mcpUrl.protocol !== 'http:')
|
|
599
|
-
|| mcpUrl.username
|
|
600
|
-
|| mcpUrl.password
|
|
601
|
-
|| mcpUrl.search
|
|
602
|
-
|| mcpUrl.hash) {
|
|
603
|
-
throw new Error('AgentLoop MCP endpoint is invalid');
|
|
604
|
-
}
|
|
605
|
-
const endpointSegments = mcpUrl.pathname.split('/').filter(Boolean);
|
|
606
|
-
const mcpSegment = endpointSegments.lastIndexOf('mcp');
|
|
607
|
-
if (mcpSegment < 0 || mcpSegment !== endpointSegments.length - 2) {
|
|
608
|
-
throw new Error('AgentLoop MCP endpoint must end with /mcp/{publicId}');
|
|
609
|
-
}
|
|
610
|
-
this.sseEndpoint = config.sseEndpoint ??
|
|
611
|
-
`${config.mcpEndpoint.replace(/\/+$/, '')}/events/sse`;
|
|
612
|
-
this.publicId = endpointSegments[endpointSegments.length - 1] ?? '';
|
|
613
|
-
this.sessionId = config.sessionId ?? `sdk-${this.publicId || (0, node_crypto_1.randomUUID)()}`;
|
|
614
|
-
if (!/^[A-Za-z0-9._:-]{1,160}$/.test(this.publicId)) {
|
|
615
|
-
throw new Error('AgentLoop MCP publicId is invalid');
|
|
616
|
-
}
|
|
617
|
-
if (!/^[A-Za-z0-9._:-]{1,160}$/.test(this.sessionId)) {
|
|
618
|
-
throw new Error('AgentLoop sessionId is invalid');
|
|
619
|
-
}
|
|
620
|
-
this.maxPendingEvents = config.maxPendingEvents ?? DEFAULT_MAX_PENDING_EVENTS;
|
|
621
|
-
this.maxEventAgeMs = config.maxEventAgeMs ?? DEFAULT_MAX_EVENT_AGE_MS;
|
|
622
|
-
this.maxEvidenceAgeMs = config.maxEvidenceAgeMs ?? DEFAULT_MAX_EVIDENCE_AGE_MS;
|
|
623
|
-
for (const [name, value] of Object.entries({
|
|
624
|
-
maxPendingEvents: this.maxPendingEvents,
|
|
625
|
-
maxEventAgeMs: this.maxEventAgeMs,
|
|
626
|
-
maxEvidenceAgeMs: this.maxEvidenceAgeMs,
|
|
627
|
-
})) {
|
|
628
|
-
if (!Number.isSafeInteger(value) || value <= 0) {
|
|
629
|
-
throw new Error(`${name} must be a positive safe integer`);
|
|
630
|
-
}
|
|
631
|
-
}
|
|
632
|
-
this.costTracker = new llm_cost_tracker_1.LlmCostTracker({
|
|
633
|
-
maxDailyUsd: config.maxDailyLlmCost ?? 5,
|
|
634
|
-
pricingUsdPerMillion: config.llmPricingUsdPerMillion,
|
|
635
|
-
});
|
|
636
|
-
this.llm = this.createLlmAdapter();
|
|
637
|
-
this.decisionHandler = new decision_handler_1.DecisionHandler(this.llm, this.costTracker, {
|
|
638
|
-
maxConsecutiveFailures: config.maxConsecutiveFailures ?? 3,
|
|
639
|
-
});
|
|
640
|
-
this.mcp = (0, mcp_client_1.connectMcp)({
|
|
641
|
-
endpoint: config.mcpEndpoint,
|
|
642
|
-
apiKey: config.apiKey,
|
|
643
|
-
fetchFn: config.mcpFetchFn,
|
|
644
|
-
});
|
|
645
|
-
// ModelRouter activates only when both cheapModel and fullModel are configured.
|
|
646
|
-
if (config.cheapModel && config.fullModel) {
|
|
647
|
-
this.modelRouter = new model_router_1.ModelRouter({
|
|
648
|
-
cheapModel: config.cheapModel,
|
|
649
|
-
fullModel: config.fullModel,
|
|
650
|
-
});
|
|
651
|
-
}
|
|
652
|
-
else {
|
|
653
|
-
this.modelRouter = null;
|
|
654
|
-
}
|
|
655
|
-
// Derive the telemetry endpoint from the MCP endpoint:
|
|
656
|
-
// https://api.balchemy.ai/mcp/abc123 → https://api.balchemy.ai/api/agent-telemetry/abc123
|
|
657
|
-
const telemetryUrl = new URL(mcpUrl.toString());
|
|
658
|
-
telemetryUrl.pathname = `${endpointSegments.slice(0, mcpSegment).length > 0 ? `/${endpointSegments.slice(0, mcpSegment).join('/')}` : ''}/api/agent-telemetry/${this.publicId}`;
|
|
659
|
-
const telemetryEndpoint = telemetryUrl.toString();
|
|
660
|
-
this.telemetry = new telemetry_reporter_1.TelemetryReporter(telemetryEndpoint, config.apiKey, 30_000, undefined, { sdkVersion: config.sdkVersion, cliVersion: config.cliVersion });
|
|
661
|
-
}
|
|
662
|
-
async start() {
|
|
663
|
-
if (this.status !== 'stopped') {
|
|
664
|
-
throw new Error(`AgentLoop cannot start from status ${this.status}`);
|
|
665
|
-
}
|
|
666
|
-
this.status = 'starting';
|
|
667
|
-
this.startedAt = Date.now();
|
|
668
|
-
this.processingHalted = false;
|
|
669
|
-
this.lifecycleGeneration++;
|
|
670
|
-
this.telemetry.start();
|
|
671
|
-
try {
|
|
672
|
-
if (this.config.webhookPort && this.config.webhookSecret) {
|
|
673
|
-
this.webhookReceiver = new webhook_receiver_1.WebhookReceiver({
|
|
674
|
-
secret: this.config.webhookSecret,
|
|
675
|
-
port: this.config.webhookPort,
|
|
676
|
-
maxEventAgeMs: this.maxEventAgeMs,
|
|
677
|
-
});
|
|
678
|
-
await this.webhookReceiver.start((event) => this.handleEvent(event));
|
|
679
|
-
}
|
|
680
|
-
this.sseStream = new sse_event_stream_1.SseEventStream(this.sseEndpoint, this.config.apiKey, {
|
|
681
|
-
maxReconnects: 0,
|
|
682
|
-
reconnectDelayMs: 2000,
|
|
683
|
-
maxReconnectDelayMs: 30_000,
|
|
684
|
-
jitterFactor: 0.25,
|
|
685
|
-
maxBufferedEvents: this.maxPendingEvents,
|
|
686
|
-
});
|
|
687
|
-
this.unsubscribeSse = this.sseStream.subscribe((sseEvent) => {
|
|
688
|
-
const envelope = asRecord(sseEvent.data);
|
|
689
|
-
const timestamp = parseEvidenceTimestamp(envelope?.ts ?? envelope?.timestamp) ?? Number.NaN;
|
|
690
|
-
const traceId = typeof envelope?.trace_id === 'string'
|
|
691
|
-
? envelope.trace_id
|
|
692
|
-
: sseEvent.id;
|
|
693
|
-
const eventType = typeof envelope?.event_type === 'string'
|
|
694
|
-
? envelope.event_type
|
|
695
|
-
: sseEvent.event;
|
|
696
|
-
const event = {
|
|
697
|
-
id: traceId,
|
|
698
|
-
type: eventType,
|
|
699
|
-
data: sseEvent.data,
|
|
700
|
-
timestamp,
|
|
701
|
-
source: 'sse',
|
|
702
|
-
};
|
|
703
|
-
this.handleEvent(event);
|
|
704
|
-
}, (err) => {
|
|
705
|
-
this.processingHalted = true;
|
|
706
|
-
this.status = 'error';
|
|
707
|
-
this.notifyError(err instanceof Error ? err : new Error(String(err)));
|
|
708
|
-
this.notifyStatus();
|
|
709
|
-
});
|
|
710
|
-
this.status = 'running';
|
|
711
|
-
this.notifyStatus();
|
|
712
|
-
}
|
|
713
|
-
catch (error) {
|
|
714
|
-
this.processingHalted = true;
|
|
715
|
-
this.status = 'error';
|
|
716
|
-
this.unsubscribeSse?.();
|
|
717
|
-
this.sseStream?.close();
|
|
718
|
-
await this.webhookReceiver?.stop();
|
|
719
|
-
await this.telemetry.stop();
|
|
720
|
-
this.notifyStatus();
|
|
721
|
-
throw error;
|
|
722
|
-
}
|
|
723
|
-
}
|
|
724
|
-
async stop() {
|
|
725
|
-
this.status = 'stopped';
|
|
726
|
-
this.processingHalted = true;
|
|
727
|
-
this.lifecycleGeneration++;
|
|
728
|
-
this.eventsDropped += this.pendingEvents.length;
|
|
729
|
-
this.pendingEvents.length = 0;
|
|
730
|
-
this.unsubscribeSse?.();
|
|
731
|
-
this.sseStream?.close();
|
|
732
|
-
await this.webhookReceiver?.stop();
|
|
733
|
-
await this.awaitCurrentDrain();
|
|
734
|
-
await this.telemetry.stop();
|
|
735
|
-
this.unsubscribeSse = null;
|
|
736
|
-
this.sseStream = null;
|
|
737
|
-
this.webhookReceiver = null;
|
|
738
|
-
this.notifyStatus();
|
|
739
|
-
}
|
|
740
|
-
getStatus() {
|
|
741
|
-
return {
|
|
742
|
-
status: this.status,
|
|
743
|
-
uptime: this.startedAt > 0 ? Date.now() - this.startedAt : 0,
|
|
744
|
-
eventsReceived: this.eventsReceived,
|
|
745
|
-
eventsDropped: this.eventsDropped,
|
|
746
|
-
pendingEvents: this.pendingEvents.length,
|
|
747
|
-
decisionsExecuted: this.decisionsExecuted,
|
|
748
|
-
tradesExecuted: this.tradesExecuted,
|
|
749
|
-
llmCallsToday: this.costTracker.getCallCount(),
|
|
750
|
-
llmCostToday: this.costTracker.getTodaySpend(),
|
|
751
|
-
maxDailyLlmCost: this.config.maxDailyLlmCost ?? 5,
|
|
752
|
-
consecutiveLlmFailures: this.decisionHandler.getConsecutiveFailures(),
|
|
753
|
-
lastEventAt: this.lastEventAt,
|
|
754
|
-
lastTradeAt: this.lastTradeAt,
|
|
755
|
-
sseConnected: this.sseStream?.isConnected() ?? false,
|
|
756
|
-
webhookActive: this.webhookReceiver !== null,
|
|
757
|
-
};
|
|
758
|
-
}
|
|
759
|
-
/**
|
|
760
|
-
* Send a user message to the bot via the ask_bot MCP tool.
|
|
761
|
-
* Parses the JSON envelope returned by the server and extracts the `reply`
|
|
762
|
-
* field if present; otherwise returns the raw text.
|
|
763
|
-
* On network / tool error, calls `config.onError` and returns an error string.
|
|
764
|
-
*/
|
|
765
|
-
async sendMessage(message) {
|
|
766
|
-
if (typeof message !== 'string' || message.trim().length === 0 || message.length > 16_384) {
|
|
767
|
-
throw new Error('AgentLoop message must contain 1 to 16384 characters');
|
|
768
|
-
}
|
|
769
|
-
this.userMessageSequence += 1;
|
|
770
|
-
if (!Number.isSafeInteger(this.userMessageSequence)) {
|
|
771
|
-
throw new Error('AgentLoop user message sequence exhausted');
|
|
772
|
-
}
|
|
773
|
-
const idempotencyKey = `sdk-ask-${(0, node_crypto_1.createHash)('sha256')
|
|
774
|
-
.update(`${this.userMessageIdempotencyNamespace}:${this.userMessageSequence}`, 'utf8')
|
|
775
|
-
.digest('hex')}`;
|
|
776
|
-
try {
|
|
777
|
-
const response = await this.mcp.callTool('ask_bot', {
|
|
778
|
-
message,
|
|
779
|
-
chat_id: this.sessionId,
|
|
780
|
-
idempotency_key: idempotencyKey,
|
|
781
|
-
});
|
|
782
|
-
const text = response.content?.find((c) => c.type === 'text')?.text ?? '';
|
|
783
|
-
try {
|
|
784
|
-
const parsed = JSON.parse(text);
|
|
785
|
-
const reply = parsed['reply'] ?? parsed['text'];
|
|
786
|
-
return typeof reply === 'string' ? reply : text;
|
|
787
|
-
}
|
|
788
|
-
catch (_error) {
|
|
789
|
-
return text;
|
|
790
|
-
}
|
|
791
|
-
}
|
|
792
|
-
catch {
|
|
793
|
-
this.notifyError(new Error('ask_bot failed'));
|
|
794
|
-
return 'Error: ask_bot failed';
|
|
795
|
-
}
|
|
796
|
-
}
|
|
797
|
-
handleEvent(event) {
|
|
798
|
-
const now = Date.now();
|
|
799
|
-
if (this.processingHalted
|
|
800
|
-
|| (this.status !== 'starting' && this.status !== 'running')) {
|
|
801
|
-
this.eventsDropped++;
|
|
802
|
-
return;
|
|
803
|
-
}
|
|
804
|
-
if (typeof event.type !== 'string'
|
|
805
|
-
|| event.type.length === 0
|
|
806
|
-
|| event.type.length > 128
|
|
807
|
-
|| !Number.isSafeInteger(event.timestamp)
|
|
808
|
-
|| event.timestamp > now + MAX_FUTURE_SKEW_MS
|
|
809
|
-
|| now - event.timestamp > this.maxEventAgeMs) {
|
|
810
|
-
this.eventsDropped++;
|
|
811
|
-
this.notifyError(new Error('Agent event rejected because its type or timestamp is invalid'));
|
|
812
|
-
return;
|
|
813
|
-
}
|
|
814
|
-
if (!event.id || !/^[A-Za-z0-9._:-]{1,256}$/.test(event.id)) {
|
|
815
|
-
this.eventsDropped++;
|
|
816
|
-
this.notifyError(new Error('Agent event rejected because its id is missing or invalid'));
|
|
817
|
-
return;
|
|
818
|
-
}
|
|
819
|
-
for (const [traceId, seenAt] of this.seenTraceIds) {
|
|
820
|
-
if (now - seenAt > this.maxEventAgeMs)
|
|
821
|
-
this.seenTraceIds.delete(traceId);
|
|
822
|
-
}
|
|
823
|
-
if (this.seenTraceIds.has(event.id))
|
|
824
|
-
return;
|
|
825
|
-
if (this.seenTraceIds.size >= 10_000) {
|
|
826
|
-
this.eventsDropped++;
|
|
827
|
-
this.processingHalted = true;
|
|
828
|
-
this.status = 'error';
|
|
829
|
-
this.sseStream?.close();
|
|
830
|
-
this.notifyError(new Error('AgentLoop replay ledger capacity exceeded; processing halted'));
|
|
831
|
-
this.notifyStatus();
|
|
832
|
-
return;
|
|
833
|
-
}
|
|
834
|
-
this.seenTraceIds.set(event.id, now);
|
|
835
|
-
this.eventsReceived++;
|
|
836
|
-
this.lastEventAt = Date.now();
|
|
837
|
-
try {
|
|
838
|
-
this.config.onEvent?.(event);
|
|
839
|
-
}
|
|
840
|
-
catch (error) {
|
|
841
|
-
this.notifyError(error instanceof Error ? error : new Error('AgentLoop onEvent callback failed'));
|
|
842
|
-
}
|
|
843
|
-
// Check budget
|
|
844
|
-
if (!this.costTracker.canCallLlm()) {
|
|
845
|
-
this.status = 'budget_exhausted';
|
|
846
|
-
this.notifyStatus();
|
|
847
|
-
return;
|
|
848
|
-
}
|
|
849
|
-
// Check if decision handler is paused (too many failures)
|
|
850
|
-
if (this.decisionHandler.isPaused()) {
|
|
851
|
-
this.status = 'llm_failing';
|
|
852
|
-
this.notifyStatus();
|
|
853
|
-
return;
|
|
854
|
-
}
|
|
855
|
-
if (this.pendingEvents.length >= this.maxPendingEvents) {
|
|
856
|
-
this.eventsDropped++;
|
|
857
|
-
this.processingHalted = true;
|
|
858
|
-
this.status = 'error';
|
|
859
|
-
this.sseStream?.close();
|
|
860
|
-
this.notifyError(new Error('AgentLoop event queue capacity exceeded; processing halted'));
|
|
861
|
-
this.config.onTradeResult?.({
|
|
862
|
-
action: 'degraded',
|
|
863
|
-
response: 'Degraded: AgentLoop event queue capacity exceeded; execution is halted.',
|
|
864
|
-
});
|
|
865
|
-
this.notifyStatus();
|
|
866
|
-
return;
|
|
867
|
-
}
|
|
868
|
-
this.pendingEvents.push({ event, generation: this.lifecycleGeneration });
|
|
869
|
-
this.startDrain();
|
|
870
|
-
}
|
|
871
|
-
async processEvent(event, generation) {
|
|
872
|
-
try {
|
|
873
|
-
const portfolio = await this.fetchPortfolio();
|
|
874
|
-
if (!this.isGenerationCurrent(generation))
|
|
875
|
-
return;
|
|
876
|
-
if (!hasRuntimeStatusSnapshot(portfolio)) {
|
|
877
|
-
this.config.onTradeResult?.({
|
|
878
|
-
action: 'degraded',
|
|
879
|
-
response: 'Degraded: agent_status is unavailable or missing runtime state; LLM decision skipped and trade_command was not called.',
|
|
880
|
-
});
|
|
881
|
-
return;
|
|
882
|
-
}
|
|
883
|
-
if (isRuntimePaused(portfolio)) {
|
|
884
|
-
this.config.onTradeResult?.({
|
|
885
|
-
action: 'hold',
|
|
886
|
-
response: 'Runtime paused: event ignored before LLM decision.',
|
|
887
|
-
});
|
|
888
|
-
return;
|
|
889
|
-
}
|
|
890
|
-
const eventRuleChain = getEventRuleChain(event);
|
|
891
|
-
const eventRulePin = parseBehaviorRuleIdentityPin(event.data);
|
|
892
|
-
const eventRequiresPin = event.type === 'subscription_event' || event.type === 'subscription_digest';
|
|
893
|
-
const rulesBinding = await this.fetchBehaviorRules(false, eventRuleChain, eventRulePin?.revisionId ?? null);
|
|
894
|
-
if (!this.isGenerationCurrent(generation))
|
|
895
|
-
return;
|
|
896
|
-
if (!rulesBinding
|
|
897
|
-
|| (eventRequiresPin && !eventRulePin)
|
|
898
|
-
|| (eventRulePin && !behaviorRuleBindingMatchesPin(rulesBinding, eventRulePin))) {
|
|
899
|
-
this.config.onTradeResult?.({
|
|
900
|
-
action: 'blocked',
|
|
901
|
-
response: 'Blocked: the event exact rule revision is unavailable, invalid, or no longer matches active policy; LLM decision skipped and trade_command was not called.',
|
|
902
|
-
});
|
|
903
|
-
return;
|
|
904
|
-
}
|
|
905
|
-
// Apply model routing if configured
|
|
906
|
-
let selectedModel = null;
|
|
907
|
-
let modelTier = null;
|
|
908
|
-
if (this.modelRouter) {
|
|
909
|
-
const score = this.modelRouter.score(event);
|
|
910
|
-
selectedModel = this.modelRouter.selectModel(event);
|
|
911
|
-
modelTier = score >= 60 ? 'full' : 'cheap';
|
|
912
|
-
this.decisionHandler.setModel(selectedModel);
|
|
913
|
-
this.telemetry.reportModelRoute({
|
|
914
|
-
eventType: event.type,
|
|
915
|
-
score,
|
|
916
|
-
selectedModel,
|
|
917
|
-
tier: modelTier,
|
|
918
|
-
});
|
|
919
|
-
}
|
|
920
|
-
const llmCallStart = Date.now();
|
|
921
|
-
const portfolioValue = portfolio.totalValueUsd ?? portfolio.totalValueSol ?? 0;
|
|
922
|
-
const portfolioValueUnit = portfolio.totalValueUsd !== undefined
|
|
923
|
-
? 'USD'
|
|
924
|
-
: portfolio.totalValueSol !== undefined ? 'SOL' : 'unknown unit';
|
|
925
|
-
const decision = await this.decisionHandler.handleEvent(event, {
|
|
926
|
-
compressedRules: rulesBinding.compressedRules,
|
|
927
|
-
portfolioValue,
|
|
928
|
-
portfolioValueUnit,
|
|
929
|
-
portfolioSummary: portfolio.summary,
|
|
930
|
-
});
|
|
931
|
-
if (!this.isGenerationCurrent(generation))
|
|
932
|
-
return;
|
|
933
|
-
const llmLatencyMs = Date.now() - llmCallStart;
|
|
934
|
-
// Report LLM call metrics — DecisionHandler exposes last call stats via getCostTracker
|
|
935
|
-
const lastCall = this.decisionHandler.getLastCallStats();
|
|
936
|
-
if (lastCall) {
|
|
937
|
-
this.telemetry.reportLlmCall({
|
|
938
|
-
model: lastCall.model,
|
|
939
|
-
inputTokens: lastCall.inputTokens,
|
|
940
|
-
outputTokens: lastCall.outputTokens,
|
|
941
|
-
latencyMs: llmLatencyMs,
|
|
942
|
-
costUsd: lastCall.costUsd,
|
|
943
|
-
});
|
|
944
|
-
}
|
|
945
|
-
if (!decision || decision.action === 'hold')
|
|
946
|
-
return;
|
|
947
|
-
this.decisionsExecuted++;
|
|
948
|
-
this.config.onDecision?.(decision);
|
|
949
|
-
this.telemetry.reportDecision({
|
|
950
|
-
action: decision.action,
|
|
951
|
-
token: decision.token,
|
|
952
|
-
amount: decision.amount,
|
|
953
|
-
confidence: decision.confidence,
|
|
954
|
-
});
|
|
955
|
-
if (decision.action === 'blocked'
|
|
956
|
-
|| decision.action === 'degraded'
|
|
957
|
-
|| decision.action === 'approval_required') {
|
|
958
|
-
this.config.onTradeResult?.({
|
|
959
|
-
action: decision.action,
|
|
960
|
-
token: decision.token,
|
|
961
|
-
amount: decision.amount,
|
|
962
|
-
response: decision.reasoning ?? `Decision ${decision.action}: trade_command was not called.`,
|
|
963
|
-
});
|
|
964
|
-
return;
|
|
965
|
-
}
|
|
966
|
-
// Execute via MCP only when the caller explicitly opted out of shadow mode.
|
|
967
|
-
if (decision.action === 'buy' || decision.action === 'sell') {
|
|
968
|
-
const executableDecision = validateExecutableTradeDecision(decision, this.maxEvidenceAgeMs);
|
|
969
|
-
if (!executableDecision.allowed) {
|
|
970
|
-
const prefix = executableDecision.action === 'degraded'
|
|
971
|
-
? 'Degraded'
|
|
972
|
-
: executableDecision.action === 'approval_required'
|
|
973
|
-
? 'Approval required'
|
|
974
|
-
: 'Blocked';
|
|
975
|
-
this.config.onTradeResult?.({
|
|
976
|
-
action: executableDecision.action,
|
|
977
|
-
token: decision.token,
|
|
978
|
-
amount: decision.amount,
|
|
979
|
-
response: `${prefix}: ${executableDecision.reason}; trade_command was not called.`,
|
|
980
|
-
});
|
|
981
|
-
return;
|
|
982
|
-
}
|
|
983
|
-
if (this.config.shadowMode !== false) {
|
|
984
|
-
this.config.onTradeResult?.({
|
|
985
|
-
action: 'shadow',
|
|
986
|
-
token: decision.token,
|
|
987
|
-
amount: decision.amount,
|
|
988
|
-
response: 'Shadow mode: trade_command was not called.',
|
|
989
|
-
});
|
|
990
|
-
return;
|
|
991
|
-
}
|
|
992
|
-
const executionSnapshot = await this.fetchPortfolio(true);
|
|
993
|
-
if (!this.isGenerationCurrent(generation))
|
|
994
|
-
return;
|
|
995
|
-
if (!isRuntimeLiveArmed(executionSnapshot)) {
|
|
996
|
-
this.config.onTradeResult?.({
|
|
997
|
-
action: 'blocked',
|
|
998
|
-
token: decision.token,
|
|
999
|
-
amount: decision.amount,
|
|
1000
|
-
response: 'Runtime not armed: backend autonomous_runtime is not live_armed; trade_command was not called.',
|
|
1001
|
-
});
|
|
1002
|
-
return;
|
|
1003
|
-
}
|
|
1004
|
-
const executionRulesBinding = await this.fetchBehaviorRules(true, rulesBinding.chain, rulesBinding.revisionId);
|
|
1005
|
-
if (!this.isGenerationCurrent(generation))
|
|
1006
|
-
return;
|
|
1007
|
-
if (!executionRulesBinding || !behaviorRuleBindingsMatch(rulesBinding, executionRulesBinding)) {
|
|
1008
|
-
this.config.onTradeResult?.({
|
|
1009
|
-
action: 'blocked',
|
|
1010
|
-
token: decision.token,
|
|
1011
|
-
amount: decision.amount,
|
|
1012
|
-
response: 'Behavior-rule revision changed or became unverifiable after the decision; trade_command was not called.',
|
|
1013
|
-
});
|
|
1014
|
-
return;
|
|
1015
|
-
}
|
|
1016
|
-
if (executionRulesBinding.chain !== null
|
|
1017
|
-
&& executionRulesBinding.chain !== executableDecision.chain) {
|
|
1018
|
-
this.config.onTradeResult?.({
|
|
1019
|
-
action: 'blocked',
|
|
1020
|
-
token: decision.token,
|
|
1021
|
-
amount: decision.amount,
|
|
1022
|
-
response: 'Behavior-rule revision chain does not match the executable decision chain; trade_command was not called.',
|
|
1023
|
-
});
|
|
1024
|
-
return;
|
|
1025
|
-
}
|
|
1026
|
-
// --- Client-side BehaviorRule pre-check ---
|
|
1027
|
-
const tradeAmount = parseFloat(decision.amount ?? '0') || 0;
|
|
1028
|
-
this.resetHourlyCounterIfNeeded();
|
|
1029
|
-
const policyNativeUnit = executionRulesBinding.executionPolicy.sizing.nativeAmountUnit;
|
|
1030
|
-
const nativeUnitMatches = policyNativeUnit === executableDecision.amountUnit
|
|
1031
|
-
|| (policyNativeUnit === null
|
|
1032
|
-
&& (executableDecision.amountUnit === 'SOL' || executableDecision.amountUnit === 'ETH'));
|
|
1033
|
-
const ruleCheck = (0, rule_checker_1.checkAllRules)(tradeAmount, this.tradesThisHour, {
|
|
1034
|
-
...(nativeUnitMatches && executionRulesBinding.executionPolicy.sizing.maxTradeNative !== null
|
|
1035
|
-
? { maxTradeSol: executionRulesBinding.executionPolicy.sizing.maxTradeNative }
|
|
1036
|
-
: {}),
|
|
1037
|
-
...(executionRulesBinding.executionPolicy.sizing.maxTradesPerHour !== null
|
|
1038
|
-
? { maxTradesPerHour: executionRulesBinding.executionPolicy.sizing.maxTradesPerHour }
|
|
1039
|
-
: {}),
|
|
1040
|
-
});
|
|
1041
|
-
if (!ruleCheck.allowed) {
|
|
1042
|
-
// Block the trade: convert to "hold", notify via onError, skip MCP call
|
|
1043
|
-
this.notifyError(new Error(`[rule-checker] Trade blocked: ${ruleCheck.reason}`));
|
|
1044
|
-
decision.ruleCorrection = {
|
|
1045
|
-
original: decision.action,
|
|
1046
|
-
corrected: 'hold',
|
|
1047
|
-
reason: ruleCheck.reason ?? 'behavior rule violation',
|
|
1048
|
-
};
|
|
1049
|
-
decision.action = 'hold';
|
|
1050
|
-
this.config.onDecision?.(decision);
|
|
1051
|
-
return;
|
|
1052
|
-
}
|
|
1053
|
-
const tradeMessage = buildTradeCommandMessage(decision, executableDecision.chain, executableDecision.amountUnit);
|
|
1054
|
-
if (!this.isGenerationCurrent(generation))
|
|
1055
|
-
return;
|
|
1056
|
-
const tradeResponse = await this.mcp.callTool('trade_command', {
|
|
1057
|
-
message: tradeMessage,
|
|
1058
|
-
chat_id: this.sessionId,
|
|
1059
|
-
idempotency_key: `sdk-${event.id ?? (0, node_crypto_1.randomUUID)()}`,
|
|
1060
|
-
autonomous: true,
|
|
1061
|
-
requiresEvidence: true,
|
|
1062
|
-
evidenceId: decision.evidenceId,
|
|
1063
|
-
sourceHealth: decision.sourceHealth,
|
|
1064
|
-
missingFacts: decision.missingFacts,
|
|
1065
|
-
requiredApprovals: decision.requiredApprovals ?? [],
|
|
1066
|
-
exitPolicy: executionRulesBinding.executionPolicy.exit,
|
|
1067
|
-
amountUnit: executableDecision.amountUnit,
|
|
1068
|
-
amountSource: decision.amountSource,
|
|
1069
|
-
ruleRevision: {
|
|
1070
|
-
schemaVersion: executionRulesBinding.schemaVersion,
|
|
1071
|
-
revisionId: executionRulesBinding.revisionId,
|
|
1072
|
-
revision: executionRulesBinding.revision,
|
|
1073
|
-
chain: executionRulesBinding.chain,
|
|
1074
|
-
compilerVersion: executionRulesBinding.compilerVersion,
|
|
1075
|
-
sourceDigest: executionRulesBinding.sourceDigest,
|
|
1076
|
-
rulesDigest: executionRulesBinding.rulesDigest,
|
|
1077
|
-
compiledDigest: executionRulesBinding.compiledDigest,
|
|
1078
|
-
compilationStatus: executionRulesBinding.compilationStatus,
|
|
1079
|
-
diagnostics: executionRulesBinding.diagnostics,
|
|
1080
|
-
},
|
|
1081
|
-
entryPolicy: {
|
|
1082
|
-
amount: decision.amount,
|
|
1083
|
-
amountUnit: executableDecision.amountUnit,
|
|
1084
|
-
amountSource: decision.amountSource,
|
|
1085
|
-
exitPolicy: executionRulesBinding.executionPolicy.exit,
|
|
1086
|
-
executionPolicyDigest: executionRulesBinding.executionPolicy.policyDigest,
|
|
1087
|
-
},
|
|
1088
|
-
});
|
|
1089
|
-
if (!this.isGenerationCurrent(generation))
|
|
1090
|
-
return;
|
|
1091
|
-
const tradeOutcome = classifyTradeCommandOutcome(tradeResponse, decision);
|
|
1092
|
-
if (tradeOutcome.submitted) {
|
|
1093
|
-
this.tradesExecuted++;
|
|
1094
|
-
this.tradesThisHour++;
|
|
1095
|
-
this.lastTradeAt = Date.now();
|
|
1096
|
-
this.config.onTradeResult?.({
|
|
1097
|
-
action: decision.action,
|
|
1098
|
-
token: decision.token,
|
|
1099
|
-
amount: decision.amount,
|
|
1100
|
-
amountUnit: executableDecision.amountUnit,
|
|
1101
|
-
response: tradeOutcome.responseText,
|
|
1102
|
-
});
|
|
1103
|
-
return;
|
|
1104
|
-
}
|
|
1105
|
-
this.config.onTradeResult?.({
|
|
1106
|
-
action: tradeOutcome.action,
|
|
1107
|
-
token: decision.token,
|
|
1108
|
-
amount: decision.amount,
|
|
1109
|
-
amountUnit: executableDecision.amountUnit,
|
|
1110
|
-
response: tradeOutcome.responseText,
|
|
1111
|
-
});
|
|
1112
|
-
}
|
|
1113
|
-
}
|
|
1114
|
-
catch (err) {
|
|
1115
|
-
this.notifyError(err instanceof Error ? err : new Error(String(err)));
|
|
1116
|
-
}
|
|
1117
|
-
}
|
|
1118
|
-
/**
|
|
1119
|
-
* Fetch exposed runtime status via `agent_status`.
|
|
1120
|
-
* Result is cached for 30 seconds. On failure, returns an empty snapshot
|
|
1121
|
-
* so the decision loop continues with degraded context.
|
|
1122
|
-
*/
|
|
1123
|
-
async fetchPortfolio(forceRefresh = false) {
|
|
1124
|
-
const now = Date.now();
|
|
1125
|
-
if (!forceRefresh && this.portfolioCache && (now - this.portfolioCache.fetchedAt) < PORTFOLIO_TTL_MS) {
|
|
1126
|
-
return this.portfolioCache.snapshot;
|
|
1127
|
-
}
|
|
1128
|
-
try {
|
|
1129
|
-
const response = await this.mcp.agentStatus();
|
|
1130
|
-
const parsed = (0, mcp_client_1.parseToolJson)(response);
|
|
1131
|
-
const snapshot = parsed
|
|
1132
|
-
? buildRuntimeStatusSnapshot(parsed)
|
|
1133
|
-
: {};
|
|
1134
|
-
this.portfolioCache = { snapshot, fetchedAt: now };
|
|
1135
|
-
return snapshot;
|
|
1136
|
-
}
|
|
1137
|
-
catch (err) {
|
|
1138
|
-
// Graceful degradation: continue with empty snapshot.
|
|
1139
|
-
this.notifyError(new Error('agent_status fetch failed; continuing with empty snapshot'));
|
|
1140
|
-
const snapshot = {};
|
|
1141
|
-
this.portfolioCache = { snapshot, fetchedAt: now };
|
|
1142
|
-
return snapshot;
|
|
1143
|
-
}
|
|
1144
|
-
}
|
|
1145
|
-
/** Fetch an exact immutable behavior-rule revision binding. Failures are cached
|
|
1146
|
-
* briefly and return null so neither decisions nor submissions proceed unbound. */
|
|
1147
|
-
async fetchBehaviorRules(forceRefresh = false, chain = null, revisionId = null) {
|
|
1148
|
-
const now = Date.now();
|
|
1149
|
-
if (!forceRefresh
|
|
1150
|
-
&& this.rulesCache
|
|
1151
|
-
&& this.rulesCache.chain === chain
|
|
1152
|
-
&& this.rulesCache.revisionId === revisionId) {
|
|
1153
|
-
const ttl = this.rulesCache.binding ? RULES_TTL_MS : RULES_FAILURE_TTL_MS;
|
|
1154
|
-
if ((now - this.rulesCache.fetchedAt) < ttl) {
|
|
1155
|
-
return this.rulesCache.binding;
|
|
1156
|
-
}
|
|
1157
|
-
}
|
|
1158
|
-
const scopeUri = chain
|
|
1159
|
-
? `balchemy://behavior-rules/${this.publicId}/${chain}`
|
|
1160
|
-
: `balchemy://behavior-rules/${this.publicId}`;
|
|
1161
|
-
const uri = revisionId ? `${scopeUri}/revisions/${revisionId}` : scopeUri;
|
|
1162
|
-
try {
|
|
1163
|
-
const contents = await this.mcp.readResource(uri);
|
|
1164
|
-
const text = contents[0]?.text ?? '';
|
|
1165
|
-
let binding = null;
|
|
1166
|
-
try {
|
|
1167
|
-
binding = parseBehaviorRuleBinding(JSON.parse(text));
|
|
1168
|
-
}
|
|
1169
|
-
catch {
|
|
1170
|
-
binding = null;
|
|
1171
|
-
}
|
|
1172
|
-
if (binding && binding.chain !== null && binding.chain !== chain)
|
|
1173
|
-
binding = null;
|
|
1174
|
-
this.rulesCache = { binding, chain, revisionId, fetchedAt: now };
|
|
1175
|
-
return binding;
|
|
1176
|
-
}
|
|
1177
|
-
catch (err) {
|
|
1178
|
-
this.notifyError(new Error('behavior-rules resource fetch failed; exact revision unavailable'));
|
|
1179
|
-
this.rulesCache = { binding: null, chain, revisionId, fetchedAt: now };
|
|
1180
|
-
return null;
|
|
1181
|
-
}
|
|
1182
|
-
}
|
|
1183
|
-
/**
|
|
1184
|
-
* Reset the hourly trade counter when the clock rolls to a new hour.
|
|
1185
|
-
* Uses truncated-hour comparison so the counter resets on exact hour boundaries.
|
|
1186
|
-
*/
|
|
1187
|
-
resetHourlyCounterIfNeeded() {
|
|
1188
|
-
const nowHour = Math.floor(Date.now() / 3_600_000) * 3_600_000;
|
|
1189
|
-
if (nowHour !== this.currentHourStart) {
|
|
1190
|
-
this.tradesThisHour = 0;
|
|
1191
|
-
this.currentHourStart = nowHour;
|
|
1192
|
-
}
|
|
1193
|
-
}
|
|
1194
|
-
createLlmAdapter() {
|
|
1195
|
-
switch (this.config.llmProvider) {
|
|
1196
|
-
case 'anthropic':
|
|
1197
|
-
return new anthropic_1.AnthropicAdapter(this.config.llmApiKey, this.config.llmModel, this.config.llmTimeoutMs);
|
|
1198
|
-
case 'openai':
|
|
1199
|
-
return new openai_1.OpenAiAdapter(this.config.llmApiKey, this.config.llmModel, this.config.llmTimeoutMs, this.config.llmBaseUrl);
|
|
1200
|
-
case 'custom':
|
|
1201
|
-
if (!this.config.llmAdapter) {
|
|
1202
|
-
throw new Error('Custom LLM adapter must be provided via config.llmAdapter');
|
|
1203
|
-
}
|
|
1204
|
-
return this.config.llmAdapter;
|
|
1205
|
-
default: {
|
|
1206
|
-
const exhaustive = this.config.llmProvider;
|
|
1207
|
-
throw new Error(`Unknown LLM provider: ${exhaustive}`);
|
|
1208
|
-
}
|
|
1209
|
-
}
|
|
1210
|
-
}
|
|
1211
|
-
startDrain() {
|
|
1212
|
-
if (this.drainPromise)
|
|
1213
|
-
return;
|
|
1214
|
-
this.drainPromise = this.drainEvents().finally(() => {
|
|
1215
|
-
this.drainPromise = null;
|
|
1216
|
-
if (this.pendingEvents.length > 0 && !this.processingHalted) {
|
|
1217
|
-
this.startDrain();
|
|
1218
|
-
}
|
|
1219
|
-
});
|
|
1220
|
-
}
|
|
1221
|
-
async drainEvents() {
|
|
1222
|
-
while (this.pendingEvents.length > 0 && !this.processingHalted) {
|
|
1223
|
-
if (!this.costTracker.canCallLlm() || this.decisionHandler.isPaused()) {
|
|
1224
|
-
this.eventsDropped += this.pendingEvents.length;
|
|
1225
|
-
this.pendingEvents.length = 0;
|
|
1226
|
-
this.status = this.costTracker.canCallLlm() ? 'llm_failing' : 'budget_exhausted';
|
|
1227
|
-
this.notifyStatus();
|
|
1228
|
-
return;
|
|
1229
|
-
}
|
|
1230
|
-
const next = this.pendingEvents.shift();
|
|
1231
|
-
if (!next || !this.isGenerationCurrent(next.generation))
|
|
1232
|
-
continue;
|
|
1233
|
-
await this.processEvent(next.event, next.generation);
|
|
1234
|
-
}
|
|
1235
|
-
}
|
|
1236
|
-
isGenerationCurrent(generation) {
|
|
1237
|
-
return generation === undefined
|
|
1238
|
-
|| (!this.processingHalted && generation === this.lifecycleGeneration);
|
|
1239
|
-
}
|
|
1240
|
-
async awaitCurrentDrain() {
|
|
1241
|
-
const drain = this.drainPromise;
|
|
1242
|
-
if (!drain)
|
|
1243
|
-
return;
|
|
1244
|
-
await Promise.race([
|
|
1245
|
-
drain,
|
|
1246
|
-
new Promise((resolve) => setTimeout(resolve, STOP_DRAIN_TIMEOUT_MS)),
|
|
1247
|
-
]);
|
|
1248
|
-
}
|
|
1249
|
-
notifyError(error) {
|
|
1250
|
-
try {
|
|
1251
|
-
const message = (0, redaction_1.redactSecretLikeText)(error.message)
|
|
1252
|
-
.replace(/https?:\/\/\S+/gi, '[source]')
|
|
1253
|
-
.slice(0, 512);
|
|
1254
|
-
this.config.onError?.(new Error(message));
|
|
1255
|
-
}
|
|
1256
|
-
catch {
|
|
1257
|
-
// User callbacks are observers and cannot become runtime authority.
|
|
1258
|
-
}
|
|
1259
|
-
}
|
|
1260
|
-
notifyStatus() {
|
|
1261
|
-
try {
|
|
1262
|
-
this.config.onStatusChange?.(this.getStatus());
|
|
1263
|
-
}
|
|
1264
|
-
catch (error) {
|
|
1265
|
-
this.notifyError(error instanceof Error ? error : new Error('AgentLoop status callback failed'));
|
|
1266
|
-
}
|
|
1267
|
-
}
|
|
1268
|
-
}
|
|
1269
|
-
exports.AgentLoop = AgentLoop;
|
|
1270
|
-
//# sourceMappingURL=agent-loop.js.map
|