@balchemyai/agent-sdk 0.3.11 → 0.4.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.
Files changed (142) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/LICENSE +21 -0
  3. package/README.md +152 -6
  4. package/dist/agent-loop/agent-loop.d.ts +19 -8
  5. package/dist/agent-loop/agent-loop.d.ts.map +1 -1
  6. package/dist/agent-loop/agent-loop.js +620 -120
  7. package/dist/agent-loop/agent-loop.js.map +1 -1
  8. package/dist/agent-loop/decision-handler.d.ts.map +1 -1
  9. package/dist/agent-loop/decision-handler.js +64 -3
  10. package/dist/agent-loop/decision-handler.js.map +1 -1
  11. package/dist/agent-loop/llm-adapters/anthropic.d.ts +4 -3
  12. package/dist/agent-loop/llm-adapters/anthropic.d.ts.map +1 -1
  13. package/dist/agent-loop/llm-adapters/anthropic.js +79 -40
  14. package/dist/agent-loop/llm-adapters/anthropic.js.map +1 -1
  15. package/dist/agent-loop/llm-adapters/openai.d.ts +4 -3
  16. package/dist/agent-loop/llm-adapters/openai.d.ts.map +1 -1
  17. package/dist/agent-loop/llm-adapters/openai.js +91 -36
  18. package/dist/agent-loop/llm-adapters/openai.js.map +1 -1
  19. package/dist/agent-loop/llm-adapters/transport.d.ts +5 -0
  20. package/dist/agent-loop/llm-adapters/transport.d.ts.map +1 -0
  21. package/dist/agent-loop/llm-adapters/transport.js +63 -0
  22. package/dist/agent-loop/llm-adapters/transport.js.map +1 -0
  23. package/dist/agent-loop/llm-cost-tracker.d.ts +4 -0
  24. package/dist/agent-loop/llm-cost-tracker.d.ts.map +1 -1
  25. package/dist/agent-loop/llm-cost-tracker.js +37 -5
  26. package/dist/agent-loop/llm-cost-tracker.js.map +1 -1
  27. package/dist/agent-loop/rule-checker.d.ts +1 -20
  28. package/dist/agent-loop/rule-checker.d.ts.map +1 -1
  29. package/dist/agent-loop/rule-checker.js +0 -2
  30. package/dist/agent-loop/rule-checker.js.map +1 -1
  31. package/dist/agent-loop/telemetry-reporter.d.ts +8 -14
  32. package/dist/agent-loop/telemetry-reporter.d.ts.map +1 -1
  33. package/dist/agent-loop/telemetry-reporter.js +74 -8
  34. package/dist/agent-loop/telemetry-reporter.js.map +1 -1
  35. package/dist/agent-loop/types.d.ts +25 -9
  36. package/dist/agent-loop/types.d.ts.map +1 -1
  37. package/dist/agent-loop/types.js +0 -7
  38. package/dist/agent-loop/types.js.map +1 -1
  39. package/dist/agent-loop/webhook-receiver.d.ts +21 -2
  40. package/dist/agent-loop/webhook-receiver.d.ts.map +1 -1
  41. package/dist/agent-loop/webhook-receiver.js +196 -33
  42. package/dist/agent-loop/webhook-receiver.js.map +1 -1
  43. package/dist/auth/onboarding.d.ts.map +1 -1
  44. package/dist/auth/onboarding.js +15 -0
  45. package/dist/auth/onboarding.js.map +1 -1
  46. package/dist/client/http-client.d.ts +4 -2
  47. package/dist/client/http-client.d.ts.map +1 -1
  48. package/dist/client/http-client.js +88 -16
  49. package/dist/client/http-client.js.map +1 -1
  50. package/dist/errors/agent-sdk-error.d.ts +6 -0
  51. package/dist/errors/agent-sdk-error.d.ts.map +1 -1
  52. package/dist/errors/agent-sdk-error.js +16 -0
  53. package/dist/errors/agent-sdk-error.js.map +1 -1
  54. package/dist/errors/failure-metadata.d.ts +19 -0
  55. package/dist/errors/failure-metadata.d.ts.map +1 -0
  56. package/dist/errors/failure-metadata.js +177 -0
  57. package/dist/errors/failure-metadata.js.map +1 -0
  58. package/dist/index.d.ts +27 -9
  59. package/dist/index.d.ts.map +1 -1
  60. package/dist/index.js +109 -15
  61. package/dist/index.js.map +1 -1
  62. package/dist/local-runner/assessment-client.d.ts +111 -0
  63. package/dist/local-runner/assessment-client.d.ts.map +1 -0
  64. package/dist/local-runner/assessment-client.js +417 -0
  65. package/dist/local-runner/assessment-client.js.map +1 -0
  66. package/dist/local-runner/control-client.d.ts +126 -0
  67. package/dist/local-runner/control-client.d.ts.map +1 -0
  68. package/dist/local-runner/control-client.js +370 -0
  69. package/dist/local-runner/control-client.js.map +1 -0
  70. package/dist/local-runner/execution-build-client.d.ts +184 -0
  71. package/dist/local-runner/execution-build-client.d.ts.map +1 -0
  72. package/dist/local-runner/execution-build-client.js +389 -0
  73. package/dist/local-runner/execution-build-client.js.map +1 -0
  74. package/dist/local-runner/execution-submit-client.d.ts +126 -0
  75. package/dist/local-runner/execution-submit-client.d.ts.map +1 -0
  76. package/dist/local-runner/execution-submit-client.js +287 -0
  77. package/dist/local-runner/execution-submit-client.js.map +1 -0
  78. package/dist/local-runner/llm-client.d.ts +20 -0
  79. package/dist/local-runner/llm-client.d.ts.map +1 -0
  80. package/dist/local-runner/llm-client.js +23 -0
  81. package/dist/local-runner/llm-client.js.map +1 -0
  82. package/dist/local-runner/owner-positions.d.ts +32 -0
  83. package/dist/local-runner/owner-positions.d.ts.map +1 -0
  84. package/dist/local-runner/owner-positions.js +89 -0
  85. package/dist/local-runner/owner-positions.js.map +1 -0
  86. package/dist/local-runner/pairing-client.d.ts +95 -0
  87. package/dist/local-runner/pairing-client.d.ts.map +1 -0
  88. package/dist/local-runner/pairing-client.js +186 -0
  89. package/dist/local-runner/pairing-client.js.map +1 -0
  90. package/dist/local-runner/research-client.d.ts +98 -0
  91. package/dist/local-runner/research-client.d.ts.map +1 -0
  92. package/dist/local-runner/research-client.js +344 -0
  93. package/dist/local-runner/research-client.js.map +1 -0
  94. package/dist/local-runner/runner-proof-transport.d.ts +55 -0
  95. package/dist/local-runner/runner-proof-transport.d.ts.map +1 -0
  96. package/dist/local-runner/runner-proof-transport.js +258 -0
  97. package/dist/local-runner/runner-proof-transport.js.map +1 -0
  98. package/dist/local-runner/runtime-client.d.ts +122 -0
  99. package/dist/local-runner/runtime-client.d.ts.map +1 -0
  100. package/dist/local-runner/runtime-client.js +265 -0
  101. package/dist/local-runner/runtime-client.js.map +1 -0
  102. package/dist/local-runner/sell-assessment-client.d.ts +113 -0
  103. package/dist/local-runner/sell-assessment-client.d.ts.map +1 -0
  104. package/dist/local-runner/sell-assessment-client.js +225 -0
  105. package/dist/local-runner/sell-assessment-client.js.map +1 -0
  106. package/dist/local-runner/signals-client.d.ts +91 -0
  107. package/dist/local-runner/signals-client.d.ts.map +1 -0
  108. package/dist/local-runner/signals-client.js +357 -0
  109. package/dist/local-runner/signals-client.js.map +1 -0
  110. package/dist/local-runner/solana-platform-account.d.ts +5 -0
  111. package/dist/local-runner/solana-platform-account.d.ts.map +1 -0
  112. package/dist/local-runner/solana-platform-account.js +66 -0
  113. package/dist/local-runner/solana-platform-account.js.map +1 -0
  114. package/dist/local-runner/trading-wallet-client.d.ts +67 -0
  115. package/dist/local-runner/trading-wallet-client.d.ts.map +1 -0
  116. package/dist/local-runner/trading-wallet-client.js +144 -0
  117. package/dist/local-runner/trading-wallet-client.js.map +1 -0
  118. package/dist/mcp/mcp-client.d.ts +31 -4
  119. package/dist/mcp/mcp-client.d.ts.map +1 -1
  120. package/dist/mcp/mcp-client.js +491 -83
  121. package/dist/mcp/mcp-client.js.map +1 -1
  122. package/dist/streaming/sse-event-stream.d.ts +14 -0
  123. package/dist/streaming/sse-event-stream.d.ts.map +1 -1
  124. package/dist/streaming/sse-event-stream.js +153 -13
  125. package/dist/streaming/sse-event-stream.js.map +1 -1
  126. package/dist/types.d.ts +11 -2
  127. package/dist/types.d.ts.map +1 -1
  128. package/dist/utils/package-version.d.ts +2 -0
  129. package/dist/utils/package-version.d.ts.map +1 -0
  130. package/dist/utils/package-version.js +54 -0
  131. package/dist/utils/package-version.js.map +1 -0
  132. package/dist/utils/redaction.d.ts +4 -0
  133. package/dist/utils/redaction.d.ts.map +1 -1
  134. package/dist/utils/redaction.js +54 -0
  135. package/dist/utils/redaction.js.map +1 -1
  136. package/dist/utils/retry.d.ts +22 -13
  137. package/dist/utils/retry.d.ts.map +1 -1
  138. package/dist/utils/retry.js +76 -50
  139. package/dist/utils/retry.js.map +1 -1
  140. package/docs/DEPLOYMENT.md +1 -1
  141. package/docs/error-retry-strategy.md +16 -6
  142. package/package.json +9 -9
@@ -12,14 +12,214 @@ const anthropic_1 = require("./llm-adapters/anthropic");
12
12
  const model_router_1 = require("./model-router");
13
13
  const telemetry_reporter_1 = require("./telemetry-reporter");
14
14
  const rule_checker_1 = require("./rule-checker");
15
+ const redaction_1 = require("../utils/redaction");
15
16
  const PORTFOLIO_TTL_MS = 30_000; // 30 seconds
16
17
  const RULES_TTL_MS = 5 * 60_000; // 5 minutes
17
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}$/;
18
26
  function asRecord(value) {
19
27
  return typeof value === 'object' && value !== null && !Array.isArray(value)
20
28
  ? value
21
29
  : null;
22
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
+ }
23
223
  function buildRuntimeStatusSnapshot(parsed) {
24
224
  const structured = asRecord(parsed.structured) ?? parsed;
25
225
  const reply = typeof parsed.reply === 'string' && parsed.reply.trim()
@@ -80,10 +280,36 @@ function normalizeTradeChain(chain) {
80
280
  return 'solana';
81
281
  if (normalized === 'base')
82
282
  return 'base';
83
- if (normalized === 'ethereum' || normalized === 'eth')
84
- return 'ethereum';
85
283
  return null;
86
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
+ }
87
313
  function isNonEmptyString(value) {
88
314
  return typeof value === 'string' && value.trim().length > 0;
89
315
  }
@@ -97,7 +323,16 @@ function isStringArray(value) {
97
323
  function hasExitPolicy(value) {
98
324
  return isNonEmptyString(value) || isNonEmptyObject(value);
99
325
  }
100
- function sourceHealthIsUsable(value) {
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()) {
101
336
  const initialRecords = Array.isArray(value)
102
337
  ? value.map(asRecord).filter((item) => item !== null)
103
338
  : [asRecord(value)].filter((item) => item !== null);
@@ -105,6 +340,7 @@ function sourceHealthIsUsable(value) {
105
340
  return false;
106
341
  }
107
342
  let sawPositiveHealthSignal = false;
343
+ let sawFreshHealthSignal = false;
108
344
  const stack = [...initialRecords];
109
345
  while (stack.length > 0) {
110
346
  const current = stack.pop();
@@ -114,8 +350,10 @@ function sourceHealthIsUsable(value) {
114
350
  if (current.ok === false || current.degraded === true || current.unavailable === true) {
115
351
  return false;
116
352
  }
353
+ let currentHasHealthSignal = false;
117
354
  if (current.ok === true) {
118
355
  sawPositiveHealthSignal = true;
356
+ currentHasHealthSignal = true;
119
357
  }
120
358
  for (const key of ['status', 'state', 'health', 'sourceStatus']) {
121
359
  const raw = current[key];
@@ -128,8 +366,23 @@ function sourceHealthIsUsable(value) {
128
366
  }
129
367
  if (GOOD_SOURCE_HEALTH_VALUES.has(normalized)) {
130
368
  sawPositiveHealthSignal = true;
369
+ currentHasHealthSignal = true;
131
370
  }
132
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
+ }
133
386
  for (const key of ['sources', 'sourceHealth', 'source_health', 'providers', 'sourceStatuses']) {
134
387
  const nested = current[key];
135
388
  if (Array.isArray(nested)) {
@@ -143,9 +396,9 @@ function sourceHealthIsUsable(value) {
143
396
  }
144
397
  }
145
398
  }
146
- return sawPositiveHealthSignal;
399
+ return sawPositiveHealthSignal && sawFreshHealthSignal;
147
400
  }
148
- function validateExecutableTradeDecision(decision) {
401
+ function validateExecutableTradeDecision(decision, maxEvidenceAgeMs) {
149
402
  if (!isNonEmptyString(decision.token)) {
150
403
  return { allowed: false, action: 'blocked', reason: 'decision is missing exact token' };
151
404
  }
@@ -171,8 +424,8 @@ function validateExecutableTradeDecision(decision) {
171
424
  if (!isNonEmptyString(decision.evidenceId)) {
172
425
  return { allowed: false, action: 'blocked', reason: 'decision is missing evidence id' };
173
426
  }
174
- if (!sourceHealthIsUsable(decision.sourceHealth)) {
175
- return { allowed: false, action: 'degraded', reason: 'source health is missing or degraded' };
427
+ if (!sourceHealthIsUsable(decision.sourceHealth, maxEvidenceAgeMs)) {
428
+ return { allowed: false, action: 'degraded', reason: 'source health is missing, stale, future-dated, or degraded' };
176
429
  }
177
430
  if (!isStringArray(decision.missingFacts)) {
178
431
  return { allowed: false, action: 'blocked', reason: 'missingFacts must be an explicit array' };
@@ -314,15 +567,19 @@ class AgentLoop {
314
567
  status = 'stopped';
315
568
  startedAt = 0;
316
569
  eventsReceived = 0;
570
+ eventsDropped = 0;
317
571
  decisionsExecuted = 0;
318
572
  tradesExecuted = 0;
319
573
  lastEventAt;
320
574
  lastTradeAt;
321
- seenTraceIds = new Set();
575
+ seenTraceIds = new Map();
576
+ pendingEvents = [];
577
+ drainPromise = null;
578
+ processingHalted = false;
579
+ lifecycleGeneration = 0;
322
580
  portfolioCache = null;
323
581
  rulesCache = null;
324
582
  /** Client-side behavior rule limits for pre-check enforcement. */
325
- ruleLimits;
326
583
  /** Trades executed in the current clock-hour (reset each hour). */
327
584
  tradesThisHour = 0;
328
585
  /** Timestamp (ms) of the hour boundary when tradesThisHour was last reset. */
@@ -330,15 +587,51 @@ class AgentLoop {
330
587
  /** publicId extracted from the MCP endpoint path (last path segment). */
331
588
  publicId;
332
589
  sessionId;
590
+ userMessageIdempotencyNamespace = (0, node_crypto_1.randomUUID)();
591
+ userMessageSequence = 0;
592
+ maxPendingEvents;
593
+ maxEventAgeMs;
594
+ maxEvidenceAgeMs;
333
595
  constructor(config) {
334
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
+ }
335
610
  this.sseEndpoint = config.sseEndpoint ??
336
- `${config.mcpEndpoint}/events/sse`;
337
- // Extract publicId from endpoint (last path segment after filtering empty segments)
338
- this.publicId = config.mcpEndpoint.split('/').filter(Boolean).pop() ?? '';
611
+ `${config.mcpEndpoint.replace(/\/+$/, '')}/events/sse`;
612
+ this.publicId = endpointSegments[endpointSegments.length - 1] ?? '';
339
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
+ }
340
632
  this.costTracker = new llm_cost_tracker_1.LlmCostTracker({
341
633
  maxDailyUsd: config.maxDailyLlmCost ?? 5,
634
+ pricingUsdPerMillion: config.llmPricingUsdPerMillion,
342
635
  });
343
636
  this.llm = this.createLlmAdapter();
344
637
  this.decisionHandler = new decision_handler_1.DecisionHandler(this.llm, this.costTracker, {
@@ -359,60 +652,98 @@ class AgentLoop {
359
652
  else {
360
653
  this.modelRouter = null;
361
654
  }
362
- // Extract client-side rule limits from behaviorRules config
363
- this.ruleLimits = extractRuleLimits(config.behaviorRules);
364
655
  // Derive the telemetry endpoint from the MCP endpoint:
365
656
  // https://api.balchemy.ai/mcp/abc123 → https://api.balchemy.ai/api/agent-telemetry/abc123
366
- const telemetryEndpoint = config.mcpEndpoint.replace(/\/mcp\//, '/api/agent-telemetry/');
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();
367
660
  this.telemetry = new telemetry_reporter_1.TelemetryReporter(telemetryEndpoint, config.apiKey, 30_000, undefined, { sdkVersion: config.sdkVersion, cliVersion: config.cliVersion });
368
661
  }
369
662
  async start() {
663
+ if (this.status !== 'stopped') {
664
+ throw new Error(`AgentLoop cannot start from status ${this.status}`);
665
+ }
370
666
  this.status = 'starting';
371
667
  this.startedAt = Date.now();
668
+ this.processingHalted = false;
669
+ this.lifecycleGeneration++;
372
670
  this.telemetry.start();
373
- // Start webhook receiver if configured
374
- if (this.config.webhookPort && this.config.webhookSecret) {
375
- this.webhookReceiver = new webhook_receiver_1.WebhookReceiver({
376
- secret: this.config.webhookSecret,
377
- port: this.config.webhookPort,
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,
378
686
  });
379
- await this.webhookReceiver.start((event) => this.handleEvent(event));
380
- }
381
- // Start SSE stream
382
- this.sseStream = new sse_event_stream_1.SseEventStream(this.sseEndpoint, this.config.apiKey, {
383
- maxReconnects: 0, // unlimited
384
- reconnectDelayMs: 2000,
385
- maxReconnectDelayMs: 30_000,
386
- jitterFactor: 0.25,
387
- });
388
- this.unsubscribeSse = this.sseStream.subscribe((sseEvent) => {
389
- const event = {
390
- id: sseEvent.id,
391
- type: sseEvent.event,
392
- data: sseEvent.data,
393
- timestamp: Date.now(),
394
- source: 'sse',
395
- };
396
- this.handleEvent(event);
397
- }, (err) => {
398
- this.config.onError?.(err instanceof Error ? err : new Error(String(err)));
399
- });
400
- this.status = 'running';
401
- this.config.onStatusChange?.(this.getStatus());
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
+ }
402
723
  }
403
724
  async stop() {
404
725
  this.status = 'stopped';
726
+ this.processingHalted = true;
727
+ this.lifecycleGeneration++;
728
+ this.eventsDropped += this.pendingEvents.length;
729
+ this.pendingEvents.length = 0;
405
730
  this.unsubscribeSse?.();
406
731
  this.sseStream?.close();
407
732
  await this.webhookReceiver?.stop();
408
- this.telemetry.stop();
409
- this.config.onStatusChange?.(this.getStatus());
733
+ await this.awaitCurrentDrain();
734
+ await this.telemetry.stop();
735
+ this.unsubscribeSse = null;
736
+ this.sseStream = null;
737
+ this.webhookReceiver = null;
738
+ this.notifyStatus();
410
739
  }
411
740
  getStatus() {
412
741
  return {
413
742
  status: this.status,
414
743
  uptime: this.startedAt > 0 ? Date.now() - this.startedAt : 0,
415
744
  eventsReceived: this.eventsReceived,
745
+ eventsDropped: this.eventsDropped,
746
+ pendingEvents: this.pendingEvents.length,
416
747
  decisionsExecuted: this.decisionsExecuted,
417
748
  tradesExecuted: this.tradesExecuted,
418
749
  llmCallsToday: this.costTracker.getCallCount(),
@@ -421,7 +752,7 @@ class AgentLoop {
421
752
  consecutiveLlmFailures: this.decisionHandler.getConsecutiveFailures(),
422
753
  lastEventAt: this.lastEventAt,
423
754
  lastTradeAt: this.lastTradeAt,
424
- sseConnected: this.status === 'running',
755
+ sseConnected: this.sseStream?.isConnected() ?? false,
425
756
  webhookActive: this.webhookReceiver !== null,
426
757
  };
427
758
  }
@@ -432,10 +763,21 @@ class AgentLoop {
432
763
  * On network / tool error, calls `config.onError` and returns an error string.
433
764
  */
434
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')}`;
435
776
  try {
436
777
  const response = await this.mcp.callTool('ask_bot', {
437
778
  message,
438
779
  chat_id: this.sessionId,
780
+ idempotency_key: idempotencyKey,
439
781
  });
440
782
  const text = response.content?.find((c) => c.type === 'text')?.text ?? '';
441
783
  try {
@@ -447,50 +789,90 @@ class AgentLoop {
447
789
  return text;
448
790
  }
449
791
  }
450
- catch (err) {
451
- const msg = err instanceof Error ? err.message : String(err);
452
- this.config.onError?.(new Error(`ask_bot failed: ${msg}`));
453
- return `Error: ${msg}`;
792
+ catch {
793
+ this.notifyError(new Error('ask_bot failed'));
794
+ return 'Error: ask_bot failed';
454
795
  }
455
796
  }
456
797
  handleEvent(event) {
457
- // Deduplicate across SSE + webhook
458
- if (event.id && this.seenTraceIds.has(event.id))
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'));
459
812
  return;
460
- if (event.id) {
461
- this.seenTraceIds.add(event.id);
462
- // Limit set size
463
- if (this.seenTraceIds.size > 10_000) {
464
- const first = this.seenTraceIds.values().next().value;
465
- if (first)
466
- this.seenTraceIds.delete(first);
467
- }
468
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);
469
835
  this.eventsReceived++;
470
836
  this.lastEventAt = Date.now();
471
- this.config.onEvent?.(event);
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
+ }
472
843
  // Check budget
473
844
  if (!this.costTracker.canCallLlm()) {
474
- if (this.status !== 'budget_exhausted') {
475
- this.status = 'budget_exhausted';
476
- this.config.onStatusChange?.(this.getStatus());
477
- }
845
+ this.status = 'budget_exhausted';
846
+ this.notifyStatus();
478
847
  return;
479
848
  }
480
849
  // Check if decision handler is paused (too many failures)
481
850
  if (this.decisionHandler.isPaused()) {
482
- if (this.status !== 'llm_failing') {
483
- this.status = 'llm_failing';
484
- this.config.onStatusChange?.(this.getStatus());
485
- }
851
+ this.status = 'llm_failing';
852
+ this.notifyStatus();
486
853
  return;
487
854
  }
488
- // Process asynchronously
489
- void this.processEvent(event);
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();
490
870
  }
491
- async processEvent(event) {
871
+ async processEvent(event, generation) {
492
872
  try {
493
873
  const portfolio = await this.fetchPortfolio();
874
+ if (!this.isGenerationCurrent(generation))
875
+ return;
494
876
  if (!hasRuntimeStatusSnapshot(portfolio)) {
495
877
  this.config.onTradeResult?.({
496
878
  action: 'degraded',
@@ -505,11 +887,18 @@ class AgentLoop {
505
887
  });
506
888
  return;
507
889
  }
508
- const compressedRules = await this.fetchBehaviorRules();
509
- if (!compressedRules.trim()) {
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))) {
510
899
  this.config.onTradeResult?.({
511
900
  action: 'blocked',
512
- response: 'Blocked: behavior rules are unavailable or empty; LLM decision skipped and trade_command was not called.',
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.',
513
902
  });
514
903
  return;
515
904
  }
@@ -534,11 +923,13 @@ class AgentLoop {
534
923
  ? 'USD'
535
924
  : portfolio.totalValueSol !== undefined ? 'SOL' : 'unknown unit';
536
925
  const decision = await this.decisionHandler.handleEvent(event, {
537
- compressedRules,
926
+ compressedRules: rulesBinding.compressedRules,
538
927
  portfolioValue,
539
928
  portfolioValueUnit,
540
929
  portfolioSummary: portfolio.summary,
541
930
  });
931
+ if (!this.isGenerationCurrent(generation))
932
+ return;
542
933
  const llmLatencyMs = Date.now() - llmCallStart;
543
934
  // Report LLM call metrics — DecisionHandler exposes last call stats via getCostTracker
544
935
  const lastCall = this.decisionHandler.getLastCallStats();
@@ -560,7 +951,6 @@ class AgentLoop {
560
951
  token: decision.token,
561
952
  amount: decision.amount,
562
953
  confidence: decision.confidence,
563
- reasoning: decision.reasoning,
564
954
  });
565
955
  if (decision.action === 'blocked'
566
956
  || decision.action === 'degraded'
@@ -575,7 +965,7 @@ class AgentLoop {
575
965
  }
576
966
  // Execute via MCP only when the caller explicitly opted out of shadow mode.
577
967
  if (decision.action === 'buy' || decision.action === 'sell') {
578
- const executableDecision = validateExecutableTradeDecision(decision);
968
+ const executableDecision = validateExecutableTradeDecision(decision, this.maxEvidenceAgeMs);
579
969
  if (!executableDecision.allowed) {
580
970
  const prefix = executableDecision.action === 'degraded'
581
971
  ? 'Degraded'
@@ -600,6 +990,8 @@ class AgentLoop {
600
990
  return;
601
991
  }
602
992
  const executionSnapshot = await this.fetchPortfolio(true);
993
+ if (!this.isGenerationCurrent(generation))
994
+ return;
603
995
  if (!isRuntimeLiveArmed(executionSnapshot)) {
604
996
  this.config.onTradeResult?.({
605
997
  action: 'blocked',
@@ -609,13 +1001,46 @@ class AgentLoop {
609
1001
  });
610
1002
  return;
611
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
+ }
612
1026
  // --- Client-side BehaviorRule pre-check ---
613
1027
  const tradeAmount = parseFloat(decision.amount ?? '0') || 0;
614
1028
  this.resetHourlyCounterIfNeeded();
615
- const ruleCheck = (0, rule_checker_1.checkAllRules)(tradeAmount, this.tradesThisHour, this.ruleLimits);
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
+ });
616
1041
  if (!ruleCheck.allowed) {
617
1042
  // Block the trade: convert to "hold", notify via onError, skip MCP call
618
- this.config.onError?.(new Error(`[rule-checker] Trade blocked: ${ruleCheck.reason}`));
1043
+ this.notifyError(new Error(`[rule-checker] Trade blocked: ${ruleCheck.reason}`));
619
1044
  decision.ruleCorrection = {
620
1045
  original: decision.action,
621
1046
  corrected: 'hold',
@@ -626,6 +1051,8 @@ class AgentLoop {
626
1051
  return;
627
1052
  }
628
1053
  const tradeMessage = buildTradeCommandMessage(decision, executableDecision.chain, executableDecision.amountUnit);
1054
+ if (!this.isGenerationCurrent(generation))
1055
+ return;
629
1056
  const tradeResponse = await this.mcp.callTool('trade_command', {
630
1057
  message: tradeMessage,
631
1058
  chat_id: this.sessionId,
@@ -636,10 +1063,31 @@ class AgentLoop {
636
1063
  sourceHealth: decision.sourceHealth,
637
1064
  missingFacts: decision.missingFacts,
638
1065
  requiredApprovals: decision.requiredApprovals ?? [],
639
- exitPolicy: decision.exitPolicy,
1066
+ exitPolicy: executionRulesBinding.executionPolicy.exit,
640
1067
  amountUnit: executableDecision.amountUnit,
641
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
+ },
642
1088
  });
1089
+ if (!this.isGenerationCurrent(generation))
1090
+ return;
643
1091
  const tradeOutcome = classifyTradeCommandOutcome(tradeResponse, decision);
644
1092
  if (tradeOutcome.submitted) {
645
1093
  this.tradesExecuted++;
@@ -664,7 +1112,7 @@ class AgentLoop {
664
1112
  }
665
1113
  }
666
1114
  catch (err) {
667
- this.config.onError?.(err instanceof Error ? err : new Error(String(err)));
1115
+ this.notifyError(err instanceof Error ? err : new Error(String(err)));
668
1116
  }
669
1117
  }
670
1118
  /**
@@ -687,41 +1135,49 @@ class AgentLoop {
687
1135
  return snapshot;
688
1136
  }
689
1137
  catch (err) {
690
- const msg = err instanceof Error ? err.message : String(err);
691
1138
  // Graceful degradation: continue with empty snapshot.
692
- this.config.onError?.(new Error(`agent_status fetch failed: ${msg}; continuing with empty snapshot`));
1139
+ this.notifyError(new Error('agent_status fetch failed; continuing with empty snapshot'));
693
1140
  const snapshot = {};
694
1141
  this.portfolioCache = { snapshot, fetchedAt: now };
695
1142
  return snapshot;
696
1143
  }
697
1144
  }
698
- /**
699
- * Fetch compressed behavior rules from the MCP resource
700
- * `balchemy://behavior-rules/{publicId}`.
701
- * Result is cached for 5 minutes. On failure, returns empty string
702
- * so decisions still proceed without rule context.
703
- */
704
- async fetchBehaviorRules() {
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) {
705
1148
  const now = Date.now();
706
- if (this.rulesCache) {
707
- const ttl = this.rulesCache.compressed.length > 0 ? RULES_TTL_MS : RULES_FAILURE_TTL_MS;
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;
708
1154
  if ((now - this.rulesCache.fetchedAt) < ttl) {
709
- return this.rulesCache.compressed;
1155
+ return this.rulesCache.binding;
710
1156
  }
711
1157
  }
712
- const uri = `balchemy://behavior-rules/${this.publicId}`;
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;
713
1162
  try {
714
1163
  const contents = await this.mcp.readResource(uri);
715
- const compressed = contents[0]?.text ?? '';
716
- this.rulesCache = { compressed, fetchedAt: now };
717
- return compressed;
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;
718
1176
  }
719
1177
  catch (err) {
720
- const msg = err instanceof Error ? err.message : String(err);
721
- // Graceful degradation: continue without rule context.
722
- this.config.onError?.(new Error(`behavior-rules resource fetch failed: ${msg}; continuing without rules`));
723
- this.rulesCache = { compressed: '', fetchedAt: now };
724
- return '';
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;
725
1181
  }
726
1182
  }
727
1183
  /**
@@ -742,29 +1198,73 @@ class AgentLoop {
742
1198
  case 'openai':
743
1199
  return new openai_1.OpenAiAdapter(this.config.llmApiKey, this.config.llmModel, this.config.llmTimeoutMs, this.config.llmBaseUrl);
744
1200
  case 'custom':
745
- throw new Error('Custom LLM adapter must be provided via config.llmAdapter');
1201
+ if (!this.config.llmAdapter) {
1202
+ throw new Error('Custom LLM adapter must be provided via config.llmAdapter');
1203
+ }
1204
+ return this.config.llmAdapter;
746
1205
  default: {
747
1206
  const exhaustive = this.config.llmProvider;
748
1207
  throw new Error(`Unknown LLM provider: ${exhaustive}`);
749
1208
  }
750
1209
  }
751
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
+ }
752
1268
  }
753
1269
  exports.AgentLoop = AgentLoop;
754
- /**
755
- * Extract the two hard-limit fields from the untyped behaviorRules config bag.
756
- * Returns an empty object (no limits enforced) if the config is absent or malformed.
757
- */
758
- function extractRuleLimits(rules) {
759
- if (!rules)
760
- return {};
761
- const limits = {};
762
- if (typeof rules['maxTradeSol'] === 'number' && rules['maxTradeSol'] > 0) {
763
- limits.maxTradeSol = rules['maxTradeSol'];
764
- }
765
- if (typeof rules['maxTradesPerHour'] === 'number' && rules['maxTradesPerHour'] > 0) {
766
- limits.maxTradesPerHour = rules['maxTradesPerHour'];
767
- }
768
- return limits;
769
- }
770
1270
  //# sourceMappingURL=agent-loop.js.map