agentbnb 8.2.2 → 8.3.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 (62) hide show
  1. package/dist/{card-EX2EYGCZ.js → card-BN643ZOY.js} +6 -2
  2. package/dist/card-T2XJZA5A.js +92 -0
  3. package/dist/{chunk-3LWBH7P3.js → chunk-4NFJ3VYZ.js} +20 -1
  4. package/dist/chunk-5AIYALBX.js +857 -0
  5. package/dist/chunk-6QMDJVMS.js +238 -0
  6. package/dist/{chunk-LKLKYXLV.js → chunk-74LZDEDT.js} +6 -4
  7. package/dist/{chunk-GKVTD4EZ.js → chunk-77KGEDH4.js} +1 -1
  8. package/dist/{chunk-QCGIG7WW.js → chunk-7IQE34QK.js} +14 -7
  9. package/dist/{chunk-QHZGOG3O.js → chunk-D242QZCR.js} +168 -41
  10. package/dist/chunk-EE3V3DXK.js +60 -0
  11. package/dist/{chunk-RYISHSHB.js → chunk-F3KIEVJ2.js} +207 -265
  12. package/dist/{chunk-XBGVQMQJ.js → chunk-FELGHDCA.js} +16 -39
  13. package/dist/{chunk-EJKW57ZV.js → chunk-GIEJVKZZ.js} +1 -1
  14. package/dist/{chunk-WVY2W7AA.js → chunk-I7KWA7OB.js} +20 -0
  15. package/dist/{chunk-4IPJJRTP.js → chunk-IGQNP3ZO.js} +5 -2
  16. package/dist/chunk-NQANA6WH.js +797 -0
  17. package/dist/{chunk-Z4MCGKTL.js → chunk-NX27AFPA.js} +15 -2
  18. package/dist/{chunk-Z2GEFFDO.js → chunk-O4Q7BRG6.js} +2 -2
  19. package/dist/{chunk-SSK653A6.js → chunk-PQIP7EXY.js} +6 -0
  20. package/dist/{chunk-EG6RS4JC.js → chunk-QFPXZITP.js} +20 -65
  21. package/dist/chunk-R4F4XII4.js +264 -0
  22. package/dist/{chunk-DYQOFGGI.js → chunk-RVBW2QXU.js} +178 -49
  23. package/dist/{chunk-CQFBNTGT.js → chunk-S7DZHKCG.js} +25 -12
  24. package/dist/chunk-U6LP4KWN.js +238 -0
  25. package/dist/{chunk-MWOXW7JQ.js → chunk-VJ7XBEY6.js} +24 -16
  26. package/dist/chunk-WTHMHNKC.js +129 -0
  27. package/dist/{chunk-OCSU2S6W.js → chunk-WX3GZVFG.js} +2 -1
  28. package/dist/{chunk-CKOOVZOI.js → chunk-YKMBFQC2.js} +37 -5
  29. package/dist/{chunk-S3V6R3EN.js → chunk-ZU2TP7CN.js} +70 -27
  30. package/dist/cli/index.js +211 -278
  31. package/dist/client-OKJJ3UP2.js +19 -0
  32. package/dist/client-UQBGCIPA.js +20 -0
  33. package/dist/conduct-4JDMWBQD.js +22 -0
  34. package/dist/{conduct-AZFLNUX3.js → conduct-VYYBCPHA.js} +14 -13
  35. package/dist/{conductor-mode-WKB42PYM.js → conductor-mode-OPGQJFLA.js} +12 -8
  36. package/dist/{conductor-mode-PLTB6MS3.js → conductor-mode-SBDCRIX6.js} +16 -11
  37. package/dist/execute-FZLQGIXB.js +14 -0
  38. package/dist/execute-TEZPQ5WP.js +15 -0
  39. package/dist/index.d.ts +172 -11
  40. package/dist/index.js +1529 -433
  41. package/dist/{process-guard-GH5LRNWO.js → process-guard-TNSUNHSR.js} +1 -1
  42. package/dist/{publish-capability-QDR2QIZ2.js → publish-capability-HVYILTPR.js} +4 -3
  43. package/dist/{reliability-metrics-QG7WC5QK.js → reliability-metrics-G7LPUYJD.js} +3 -1
  44. package/dist/reliability-metrics-RRUKJ4ME.js +20 -0
  45. package/dist/{request-NX7GSPIG.js → request-KJNKR27T.js} +96 -43
  46. package/dist/{serve-skill-E6EJQYAK.js → serve-skill-GC6NIQ5T.js} +10 -11
  47. package/dist/{server-VBCT32FC.js → server-YV3XPTX5.js} +11 -10
  48. package/dist/{service-coordinator-KMSA6BST.js → service-coordinator-RY5AKUZS.js} +420 -171
  49. package/dist/{skill-config-FETXPNVP.js → skill-config-5O2VR546.js} +1 -1
  50. package/dist/skills/agentbnb/bootstrap.js +550 -231
  51. package/dist/websocket-client-3U27WJUU.js +7 -0
  52. package/dist/{websocket-client-4Z5P54RU.js → websocket-client-SNDF3B6N.js} +1 -1
  53. package/package.json +18 -12
  54. package/skills/agentbnb/install.sh +0 -0
  55. package/dist/chunk-MCED4GDW.js +0 -1572
  56. package/dist/chunk-NWIQJ2CL.js +0 -108
  57. package/dist/chunk-WNXXLCV5.js +0 -32
  58. package/dist/client-XOLP5IUZ.js +0 -12
  59. package/dist/conduct-VPUYTNEA.js +0 -21
  60. package/dist/execute-NNDCXTN4.js +0 -13
  61. package/dist/execute-RIRHTIBU.js +0 -16
  62. package/dist/websocket-client-QOVARTRN.js +0 -7
@@ -0,0 +1,238 @@
1
+ import {
2
+ ensureAgentsTable,
3
+ resolveCanonicalIdentity
4
+ } from "./chunk-EE3V3DXK.js";
5
+
6
+ // src/credit/owner-normalization.ts
7
+ var RESERVED_OWNERS = /* @__PURE__ */ new Set(["platform_treasury"]);
8
+ function tableExists(db, table) {
9
+ const row = db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(table);
10
+ return row !== void 0;
11
+ }
12
+ function mergeBalanceRows(db, oldOwner, newOwner, now) {
13
+ if (!tableExists(db, "credit_balances")) return;
14
+ const oldRow = db.prepare("SELECT balance FROM credit_balances WHERE owner = ?").get(oldOwner);
15
+ if (!oldRow) return;
16
+ const newRow = db.prepare("SELECT balance FROM credit_balances WHERE owner = ?").get(newOwner);
17
+ if (newRow) {
18
+ db.prepare(
19
+ "UPDATE credit_balances SET balance = balance + ?, updated_at = ? WHERE owner = ?"
20
+ ).run(oldRow.balance, now, newOwner);
21
+ db.prepare("DELETE FROM credit_balances WHERE owner = ?").run(oldOwner);
22
+ return;
23
+ }
24
+ db.prepare("UPDATE credit_balances SET owner = ?, updated_at = ? WHERE owner = ?").run(
25
+ newOwner,
26
+ now,
27
+ oldOwner
28
+ );
29
+ }
30
+ function mergeProviderRegistryRows(db, oldOwner, newOwner) {
31
+ if (!tableExists(db, "provider_registry")) return;
32
+ const oldRow = db.prepare("SELECT provider_number FROM provider_registry WHERE owner = ?").get(oldOwner);
33
+ if (!oldRow) return;
34
+ const newRow = db.prepare("SELECT provider_number FROM provider_registry WHERE owner = ?").get(newOwner);
35
+ if (newRow) {
36
+ db.prepare("DELETE FROM provider_registry WHERE owner = ?").run(oldOwner);
37
+ return;
38
+ }
39
+ db.prepare("UPDATE provider_registry SET owner = ? WHERE owner = ?").run(newOwner, oldOwner);
40
+ }
41
+ function mergeReliabilityRows(db, oldOwner, newOwner, now) {
42
+ if (!tableExists(db, "provider_reliability_metrics")) return;
43
+ const oldRow = db.prepare("SELECT * FROM provider_reliability_metrics WHERE owner = ?").get(oldOwner);
44
+ if (!oldRow) return;
45
+ const newRow = db.prepare("SELECT * FROM provider_reliability_metrics WHERE owner = ?").get(newOwner);
46
+ if (!newRow) {
47
+ db.prepare(
48
+ "UPDATE provider_reliability_metrics SET owner = ?, updated_at = ? WHERE owner = ?"
49
+ ).run(newOwner, now, oldOwner);
50
+ return;
51
+ }
52
+ const cycleStartCandidates = [oldRow.cycle_start, newRow.cycle_start].filter(Boolean);
53
+ const mergedCycleStart = cycleStartCandidates.length > 0 ? cycleStartCandidates.slice().sort((left, right) => left.localeCompare(right))[0] : now;
54
+ db.prepare(
55
+ `UPDATE provider_reliability_metrics
56
+ SET current_streak = ?,
57
+ longest_streak = ?,
58
+ total_hires = ?,
59
+ repeat_hires = ?,
60
+ feedback_count = ?,
61
+ feedback_sum = ?,
62
+ availability_checks = ?,
63
+ availability_hits = ?,
64
+ cycle_start = ?,
65
+ updated_at = ?
66
+ WHERE owner = ?`
67
+ ).run(
68
+ Math.max(oldRow.current_streak, newRow.current_streak),
69
+ Math.max(oldRow.longest_streak, newRow.longest_streak),
70
+ oldRow.total_hires + newRow.total_hires,
71
+ oldRow.repeat_hires + newRow.repeat_hires,
72
+ oldRow.feedback_count + newRow.feedback_count,
73
+ oldRow.feedback_sum + newRow.feedback_sum,
74
+ oldRow.availability_checks + newRow.availability_checks,
75
+ oldRow.availability_hits + newRow.availability_hits,
76
+ mergedCycleStart,
77
+ now,
78
+ newOwner
79
+ );
80
+ db.prepare("DELETE FROM provider_reliability_metrics WHERE owner = ?").run(oldOwner);
81
+ }
82
+ function migrateCreditOwnerData(db, oldOwner, newOwner) {
83
+ if (!oldOwner || !newOwner || oldOwner === newOwner) return;
84
+ const now = (/* @__PURE__ */ new Date()).toISOString();
85
+ db.transaction(() => {
86
+ mergeBalanceRows(db, oldOwner, newOwner, now);
87
+ if (tableExists(db, "credit_transactions")) {
88
+ db.prepare("UPDATE credit_transactions SET owner = ? WHERE owner = ?").run(newOwner, oldOwner);
89
+ }
90
+ if (tableExists(db, "credit_escrow")) {
91
+ db.prepare("UPDATE credit_escrow SET owner = ? WHERE owner = ?").run(newOwner, oldOwner);
92
+ }
93
+ mergeProviderRegistryRows(db, oldOwner, newOwner);
94
+ if (tableExists(db, "demand_vouchers")) {
95
+ db.prepare("UPDATE demand_vouchers SET owner = ? WHERE owner = ?").run(newOwner, oldOwner);
96
+ }
97
+ mergeReliabilityRows(db, oldOwner, newOwner, now);
98
+ })();
99
+ }
100
+ function canonicalizeCreditOwner(db, owner) {
101
+ if (!owner || RESERVED_OWNERS.has(owner)) {
102
+ return owner;
103
+ }
104
+ ensureAgentsTable(db);
105
+ const resolved = resolveCanonicalIdentity(db, owner);
106
+ if (!resolved.resolved) {
107
+ return owner;
108
+ }
109
+ const aliases = /* @__PURE__ */ new Set();
110
+ if (owner !== resolved.agent_id) {
111
+ aliases.add(owner);
112
+ }
113
+ if (resolved.legacy_owner && resolved.legacy_owner !== resolved.agent_id) {
114
+ aliases.add(resolved.legacy_owner);
115
+ }
116
+ for (const alias of aliases) {
117
+ migrateCreditOwnerData(db, alias, resolved.agent_id);
118
+ }
119
+ return resolved.agent_id;
120
+ }
121
+
122
+ // src/credit/reliability-metrics.ts
123
+ var RELIABILITY_METRICS_SCHEMA = `
124
+ CREATE TABLE IF NOT EXISTS provider_reliability_metrics (
125
+ owner TEXT PRIMARY KEY,
126
+ current_streak INTEGER NOT NULL DEFAULT 0,
127
+ longest_streak INTEGER NOT NULL DEFAULT 0,
128
+ total_hires INTEGER NOT NULL DEFAULT 0,
129
+ repeat_hires INTEGER NOT NULL DEFAULT 0,
130
+ feedback_count INTEGER NOT NULL DEFAULT 0,
131
+ feedback_sum REAL NOT NULL DEFAULT 0,
132
+ availability_checks INTEGER NOT NULL DEFAULT 0,
133
+ availability_hits INTEGER NOT NULL DEFAULT 0,
134
+ cycle_start TEXT NOT NULL,
135
+ updated_at TEXT NOT NULL
136
+ );
137
+ `;
138
+ function ensureReliabilityTable(db) {
139
+ db.exec(RELIABILITY_METRICS_SCHEMA);
140
+ }
141
+ function ensureRow(db, owner) {
142
+ const canonicalOwner = canonicalizeCreditOwner(db, owner);
143
+ const now = (/* @__PURE__ */ new Date()).toISOString();
144
+ db.prepare(
145
+ `INSERT OR IGNORE INTO provider_reliability_metrics
146
+ (owner, current_streak, longest_streak, total_hires, repeat_hires,
147
+ feedback_count, feedback_sum, availability_checks, availability_hits,
148
+ cycle_start, updated_at)
149
+ VALUES (?, 0, 0, 0, 0, 0, 0, 0, 0, ?, ?)`
150
+ ).run(canonicalOwner, now, now);
151
+ }
152
+ function recordSuccessfulHire(db, providerOwner, consumerOwner) {
153
+ const canonicalProviderOwner = canonicalizeCreditOwner(db, providerOwner);
154
+ const canonicalConsumerOwner = canonicalizeCreditOwner(db, consumerOwner);
155
+ const now = (/* @__PURE__ */ new Date()).toISOString();
156
+ ensureRow(db, canonicalProviderOwner);
157
+ const isRepeat = db.prepare(
158
+ `SELECT COUNT(*) as cnt FROM credit_transactions
159
+ WHERE owner = ? AND reason = 'settlement'
160
+ AND reference_id IN (
161
+ SELECT id FROM credit_escrow WHERE owner = ?
162
+ )`
163
+ ).get(canonicalProviderOwner, canonicalConsumerOwner);
164
+ const repeatIncrement = (isRepeat?.cnt ?? 0) > 0 ? 1 : 0;
165
+ db.prepare(
166
+ `UPDATE provider_reliability_metrics
167
+ SET current_streak = current_streak + 1,
168
+ longest_streak = MAX(longest_streak, current_streak + 1),
169
+ total_hires = total_hires + 1,
170
+ repeat_hires = repeat_hires + ?,
171
+ updated_at = ?
172
+ WHERE owner = ?`
173
+ ).run(repeatIncrement, now, canonicalProviderOwner);
174
+ }
175
+ function recordQualityFailure(db, providerOwner) {
176
+ const canonicalProviderOwner = canonicalizeCreditOwner(db, providerOwner);
177
+ const now = (/* @__PURE__ */ new Date()).toISOString();
178
+ ensureRow(db, canonicalProviderOwner);
179
+ db.prepare(
180
+ `UPDATE provider_reliability_metrics
181
+ SET current_streak = 0, updated_at = ?
182
+ WHERE owner = ?`
183
+ ).run(now, canonicalProviderOwner);
184
+ }
185
+ function recordFeedback(db, providerOwner, score) {
186
+ const canonicalProviderOwner = canonicalizeCreditOwner(db, providerOwner);
187
+ const now = (/* @__PURE__ */ new Date()).toISOString();
188
+ ensureRow(db, canonicalProviderOwner);
189
+ db.prepare(
190
+ `UPDATE provider_reliability_metrics
191
+ SET feedback_count = feedback_count + 1,
192
+ feedback_sum = feedback_sum + ?,
193
+ updated_at = ?
194
+ WHERE owner = ?`
195
+ ).run(score, now, canonicalProviderOwner);
196
+ }
197
+ function recordAvailabilityCheck(db, providerOwner, wasAvailable) {
198
+ const canonicalProviderOwner = canonicalizeCreditOwner(db, providerOwner);
199
+ const now = (/* @__PURE__ */ new Date()).toISOString();
200
+ ensureRow(db, canonicalProviderOwner);
201
+ db.prepare(
202
+ `UPDATE provider_reliability_metrics
203
+ SET availability_checks = availability_checks + 1,
204
+ availability_hits = availability_hits + ?,
205
+ updated_at = ?
206
+ WHERE owner = ?`
207
+ ).run(wasAvailable ? 1 : 0, now, canonicalProviderOwner);
208
+ }
209
+ function getReliabilityMetrics(db, owner) {
210
+ const canonicalOwner = canonicalizeCreditOwner(db, owner);
211
+ const row = db.prepare(
212
+ `SELECT current_streak, longest_streak, total_hires, repeat_hires,
213
+ feedback_count, feedback_sum, availability_checks, availability_hits
214
+ FROM provider_reliability_metrics WHERE owner = ?`
215
+ ).get(canonicalOwner);
216
+ if (!row) return null;
217
+ return {
218
+ current_streak: row.current_streak,
219
+ longest_streak: row.longest_streak,
220
+ total_hires: row.total_hires,
221
+ repeat_hires: row.repeat_hires,
222
+ repeat_hire_rate: row.total_hires > 0 ? row.repeat_hires / row.total_hires : 0,
223
+ avg_feedback_score: row.feedback_count > 0 ? row.feedback_sum / row.feedback_count : 0,
224
+ availability_rate: row.availability_checks > 0 ? row.availability_hits / row.availability_checks : 0
225
+ };
226
+ }
227
+
228
+ export {
229
+ migrateCreditOwnerData,
230
+ canonicalizeCreditOwner,
231
+ RELIABILITY_METRICS_SCHEMA,
232
+ ensureReliabilityTable,
233
+ recordSuccessfulHire,
234
+ recordQualityFailure,
235
+ recordFeedback,
236
+ recordAvailabilityCheck,
237
+ getReliabilityMetrics
238
+ };
@@ -3,22 +3,24 @@ import {
3
3
  getBalance,
4
4
  getTransactions,
5
5
  holdEscrow,
6
- lookupAgent,
7
6
  migrateOwner,
8
7
  openCreditDb,
9
8
  releaseEscrow,
10
9
  settleEscrow
11
- } from "./chunk-RYISHSHB.js";
10
+ } from "./chunk-F3KIEVJ2.js";
12
11
  import {
13
12
  generateKeyPair,
14
13
  loadKeyPair,
15
14
  saveKeyPair,
16
15
  signEscrowReceipt,
17
16
  verifyEscrowReceipt
18
- } from "./chunk-EJKW57ZV.js";
17
+ } from "./chunk-GIEJVKZZ.js";
18
+ import {
19
+ lookupAgent
20
+ } from "./chunk-WTHMHNKC.js";
19
21
  import {
20
22
  AgentBnBError
21
- } from "./chunk-WVY2W7AA.js";
23
+ } from "./chunk-I7KWA7OB.js";
22
24
 
23
25
  // src/identity/identity.ts
24
26
  import { z } from "zod";
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  AgentBnBError
3
- } from "./chunk-WVY2W7AA.js";
3
+ } from "./chunk-I7KWA7OB.js";
4
4
 
5
5
  // src/autonomy/tiers.ts
6
6
  import { randomUUID } from "crypto";
@@ -3,15 +3,15 @@ import {
3
3
  } from "./chunk-3MJT4PZG.js";
4
4
  import {
5
5
  scorePeers
6
- } from "./chunk-QHZGOG3O.js";
6
+ } from "./chunk-D242QZCR.js";
7
7
  import {
8
8
  fetchRemoteCards,
9
9
  searchCards
10
- } from "./chunk-RYISHSHB.js";
10
+ } from "./chunk-F3KIEVJ2.js";
11
11
  import {
12
12
  requestCapability,
13
13
  requestCapabilityBatch
14
- } from "./chunk-CKOOVZOI.js";
14
+ } from "./chunk-YKMBFQC2.js";
15
15
 
16
16
  // src/conductor/decomposition-validator.ts
17
17
  function validateAndNormalizeSubtasks(raw, context) {
@@ -471,6 +471,7 @@ async function executeSingleTask(pt, gatewayToken, timeoutMs, requesterOwner, re
471
471
  async function orchestrate(opts) {
472
472
  const { subtasks, matches, gatewayToken, resolveAgentUrl, timeoutMs = 3e5, maxBudget, relayClient, requesterOwner } = opts;
473
473
  const startTime = Date.now();
474
+ const hardDeadline = startTime + timeoutMs;
474
475
  const teamMemberMap = /* @__PURE__ */ new Map();
475
476
  if (opts.team) {
476
477
  for (const member of opts.team.matched) {
@@ -492,6 +493,12 @@ async function orchestrate(opts) {
492
493
  const waves = computeWaves(subtasks);
493
494
  const subtaskMap = new Map(subtasks.map((s) => [s.id, s]));
494
495
  for (const wave of waves) {
496
+ const remainingWaveMs = hardDeadline - Date.now();
497
+ if (remainingWaveMs <= 0) {
498
+ errors.push(`Orchestration timed out after ${timeoutMs}ms`);
499
+ break;
500
+ }
501
+ const waveTimeoutMs = Math.max(1, Math.min(timeoutMs, remainingWaveMs));
495
502
  if (maxBudget !== void 0 && totalCredits >= maxBudget) {
496
503
  errors.push(`Budget exceeded: spent ${totalCredits} cr, max ${maxBudget} cr`);
497
504
  break;
@@ -565,7 +572,7 @@ async function orchestrate(opts) {
565
572
  gatewayUrl,
566
573
  gatewayToken,
567
574
  items.map(({ _pt, ...item }) => item),
568
- { timeoutMs }
575
+ { timeoutMs: waveTimeoutMs }
569
576
  );
570
577
  return items.map((item) => {
571
578
  const res = batchResults.get(item.id);
@@ -589,7 +596,7 @@ async function orchestrate(opts) {
589
596
  } catch (batchErr) {
590
597
  return Promise.all(group.map(async (pt) => {
591
598
  try {
592
- const res = await executeSingleTask(pt, gatewayToken, timeoutMs, requesterOwner, relayClient, resolveAgentUrl);
599
+ const res = await executeSingleTask(pt, gatewayToken, waveTimeoutMs, requesterOwner, relayClient, resolveAgentUrl);
593
600
  return { status: "fulfilled", value: res };
594
601
  } catch (err) {
595
602
  return { status: "rejected", reason: err };
@@ -603,7 +610,7 @@ async function orchestrate(opts) {
603
610
  batchPromises.push(
604
611
  (async () => {
605
612
  try {
606
- const res = await executeSingleTask(pt, gatewayToken, timeoutMs, requesterOwner, relayClient, resolveAgentUrl);
613
+ const res = await executeSingleTask(pt, gatewayToken, waveTimeoutMs, requesterOwner, relayClient, resolveAgentUrl);
607
614
  return [{ status: "fulfilled", value: res }];
608
615
  } catch (err) {
609
616
  return [{ status: "rejected", reason: err }];
@@ -616,7 +623,7 @@ async function orchestrate(opts) {
616
623
  batchPromises.push(
617
624
  (async () => {
618
625
  try {
619
- const res = await executeSingleTask(pt, gatewayToken, timeoutMs, requesterOwner, relayClient, resolveAgentUrl);
626
+ const res = await executeSingleTask(pt, gatewayToken, waveTimeoutMs, requesterOwner, relayClient, resolveAgentUrl);
620
627
  return [{ status: "fulfilled", value: res }];
621
628
  } catch (err) {
622
629
  return [{ status: "rejected", reason: err }];
@@ -2,10 +2,10 @@ import {
2
2
  createPendingRequest,
3
3
  getAutonomyTier,
4
4
  insertAuditEvent
5
- } from "./chunk-GKVTD4EZ.js";
5
+ } from "./chunk-77KGEDH4.js";
6
6
  import {
7
7
  resolveTargetCapability
8
- } from "./chunk-CQFBNTGT.js";
8
+ } from "./chunk-S7DZHKCG.js";
9
9
  import {
10
10
  fetchRemoteCards,
11
11
  getBalance,
@@ -13,14 +13,82 @@ import {
13
13
  releaseEscrow,
14
14
  searchCards,
15
15
  settleEscrow
16
- } from "./chunk-RYISHSHB.js";
16
+ } from "./chunk-F3KIEVJ2.js";
17
+ import {
18
+ RelayClient
19
+ } from "./chunk-NX27AFPA.js";
17
20
  import {
18
21
  requestCapability,
19
22
  requestViaRelay
20
- } from "./chunk-CKOOVZOI.js";
23
+ } from "./chunk-YKMBFQC2.js";
21
24
  import {
22
25
  findPeer
23
26
  } from "./chunk-5AH3CMOX.js";
27
+ import {
28
+ resolveCanonicalIdentity
29
+ } from "./chunk-WTHMHNKC.js";
30
+ import {
31
+ AgentBnBError
32
+ } from "./chunk-I7KWA7OB.js";
33
+
34
+ // src/gateway/relay-dispatch.ts
35
+ import { randomUUID } from "crypto";
36
+ async function requestViaTemporaryRelay(opts) {
37
+ const {
38
+ registryUrl,
39
+ owner,
40
+ token,
41
+ targetOwner,
42
+ targetAgentId,
43
+ cardId,
44
+ skillId,
45
+ params,
46
+ timeoutMs = 3e5
47
+ } = opts;
48
+ const requesterId = `${owner}:req:${randomUUID()}`;
49
+ const relay = new RelayClient({
50
+ registryUrl,
51
+ owner: requesterId,
52
+ token,
53
+ card: {
54
+ spec_version: "1.0",
55
+ id: randomUUID(),
56
+ owner: requesterId,
57
+ name: requesterId,
58
+ description: "Temporary relay requester",
59
+ level: 1,
60
+ inputs: [],
61
+ outputs: [],
62
+ pricing: { credits_per_call: 0 },
63
+ availability: { online: false }
64
+ },
65
+ onRequest: async () => ({
66
+ error: { code: -32601, message: "Temporary relay requester does not serve capabilities" }
67
+ }),
68
+ silent: true
69
+ });
70
+ try {
71
+ await relay.connect();
72
+ } catch (err) {
73
+ relay.disconnect();
74
+ const message = err instanceof Error ? err.message : String(err);
75
+ throw new AgentBnBError(`Relay connection failed: ${message}`, "RELAY_UNAVAILABLE");
76
+ }
77
+ try {
78
+ return await requestViaRelay(relay, {
79
+ targetOwner,
80
+ targetAgentId,
81
+ cardId,
82
+ skillId,
83
+ params,
84
+ requester: owner,
85
+ // actual owner for credit tracking on relay server
86
+ timeoutMs
87
+ });
88
+ } finally {
89
+ relay.disconnect();
90
+ }
91
+ }
24
92
 
25
93
  // src/credit/budget.ts
26
94
  var DEFAULT_BUDGET_CONFIG = {
@@ -68,7 +136,6 @@ var BudgetManager = class {
68
136
  };
69
137
 
70
138
  // src/autonomy/auto-request.ts
71
- import { randomUUID } from "crypto";
72
139
  function minMaxNormalize(values) {
73
140
  if (values.length === 0) return [];
74
141
  if (values.length === 1) return [1];
@@ -79,8 +146,17 @@ function minMaxNormalize(values) {
79
146
  }
80
147
  return values.map((v) => (v - min) / (max - min));
81
148
  }
82
- function scorePeers(candidates, selfOwner) {
83
- const eligible = candidates.filter((c) => c.card.owner !== selfOwner);
149
+ function scorePeers(candidates, selfOwner, registryDb) {
150
+ const selfIdentity = registryDb ? resolveCanonicalIdentity(registryDb, selfOwner) : null;
151
+ const eligible = candidates.filter((c) => {
152
+ if (c.card.owner === selfOwner) return false;
153
+ if (!registryDb || !selfIdentity?.resolved) return true;
154
+ if (typeof c.card.agent_id === "string" && c.card.agent_id.length > 0) {
155
+ return c.card.agent_id !== selfIdentity.agent_id;
156
+ }
157
+ const peerIdentity = resolveCanonicalIdentity(registryDb, c.card.owner);
158
+ return !peerIdentity.resolved || peerIdentity.agent_id !== selfIdentity.agent_id;
159
+ });
84
160
  if (eligible.length === 0) return [];
85
161
  const successRates = eligible.map((c) => {
86
162
  if (c.skillMetadata?.success_rate !== void 0) {
@@ -149,6 +225,14 @@ var AutoRequestor = class {
149
225
  * @returns The result of the auto-request attempt.
150
226
  */
151
227
  async requestWithAutonomy(need) {
228
+ const selfIdentity = resolveCanonicalIdentity(this.registryDb, this.owner);
229
+ const isSelfTarget = (targetOwner, targetAgentId) => {
230
+ if (targetOwner === this.owner) return true;
231
+ if (!selfIdentity.resolved) return false;
232
+ if (targetAgentId && targetAgentId === selfIdentity.agent_id) return true;
233
+ const targetOwnerIdentity = resolveCanonicalIdentity(this.registryDb, targetOwner);
234
+ return targetOwnerIdentity.resolved && targetOwnerIdentity.agent_id === selfIdentity.agent_id;
235
+ };
152
236
  let cards = searchCards(this.registryDb, need.query, { online: true });
153
237
  if (cards.length === 0 && this.registryUrl) {
154
238
  try {
@@ -190,7 +274,7 @@ var AutoRequestor = class {
190
274
  }
191
275
  }
192
276
  }
193
- const scored = scorePeers(candidates, this.owner);
277
+ const scored = scorePeers(candidates, this.owner, this.registryDb);
194
278
  const resolverOptions = {
195
279
  registryDb: this.registryDb,
196
280
  registryUrl: this.registryUrl,
@@ -199,7 +283,7 @@ var AutoRequestor = class {
199
283
  let resolvedTarget = null;
200
284
  if (scored.length === 0) {
201
285
  resolvedTarget = await resolveTargetCapability(need.query, resolverOptions);
202
- if (!resolvedTarget || resolvedTarget.owner === this.owner || resolvedTarget.credits_per_call > need.maxCostCredits) {
286
+ if (!resolvedTarget || isSelfTarget(resolvedTarget.owner, resolvedTarget.agent_id) || resolvedTarget.credits_per_call > need.maxCostCredits) {
203
287
  this.logFailure("auto_request_failed", "system", "none", 3, 0, "none", "No eligible peer found");
204
288
  return { status: "no_peer", reason: "No eligible peer found" };
205
289
  }
@@ -207,7 +291,7 @@ var AutoRequestor = class {
207
291
  const top = scored[0];
208
292
  const targetKey = top.skillId ?? top.card.id;
209
293
  resolvedTarget = await resolveTargetCapability(targetKey, resolverOptions) ?? await resolveTargetCapability(need.query, resolverOptions);
210
- if (!resolvedTarget || resolvedTarget.owner === this.owner) {
294
+ if (!resolvedTarget || isSelfTarget(resolvedTarget.owner, resolvedTarget.agent_id)) {
211
295
  this.logFailure("auto_request_failed", top.card.id, top.skillId ?? "none", 3, top.cost, top.card.owner, "No eligible peer found");
212
296
  return { status: "no_peer", reason: "No eligible peer found" };
213
297
  }
@@ -258,9 +342,75 @@ var AutoRequestor = class {
258
342
  );
259
343
  return { status: "budget_blocked", reason: "Insufficient credits \u2014 reserve floor would be breached" };
260
344
  }
345
+ const requestParams = selectedSkillId ? { skill_id: selectedSkillId, ...need.params, requester: this.owner } : { ...need.params, requester: this.owner };
346
+ if (selectedViaRelay && selectedCost > 0) {
347
+ if (!this.registryUrl) {
348
+ this.logFailure(
349
+ "auto_request_failed",
350
+ selectedCardId,
351
+ selectedSkillId ?? "none",
352
+ tier,
353
+ selectedCost,
354
+ selectedPeer,
355
+ "Relay target found but registryUrl is not configured"
356
+ );
357
+ return { status: "no_peer", reason: "Relay target found but registryUrl is not configured" };
358
+ }
359
+ try {
360
+ const execResult = await requestViaTemporaryRelay({
361
+ registryUrl: this.registryUrl,
362
+ owner: this.owner,
363
+ token: "auto-request-token",
364
+ targetOwner: selectedPeer,
365
+ cardId: selectedCardId,
366
+ skillId: selectedSkillId,
367
+ params: requestParams
368
+ });
369
+ if (tier === 2) {
370
+ insertAuditEvent(this.registryDb, {
371
+ type: "auto_request_notify",
372
+ card_id: selectedCardId,
373
+ skill_id: selectedSkillId ?? selectedCardId,
374
+ tier_invoked: 2,
375
+ credits: selectedCost,
376
+ peer: selectedPeer
377
+ });
378
+ } else {
379
+ insertAuditEvent(this.registryDb, {
380
+ type: "auto_request",
381
+ card_id: selectedCardId,
382
+ skill_id: selectedSkillId ?? selectedCardId,
383
+ tier_invoked: 1,
384
+ credits: selectedCost,
385
+ peer: selectedPeer
386
+ });
387
+ }
388
+ return {
389
+ status: "success",
390
+ result: execResult,
391
+ peer: selectedPeer,
392
+ creditsSpent: selectedCost
393
+ };
394
+ } catch (err) {
395
+ const reason = err instanceof Error ? err.message : String(err);
396
+ this.logFailure(
397
+ "auto_request_failed",
398
+ selectedCardId,
399
+ selectedSkillId ?? "none",
400
+ tier,
401
+ selectedCost,
402
+ selectedPeer,
403
+ `Execution failed: ${reason}`
404
+ );
405
+ return {
406
+ status: "failed",
407
+ reason: `Execution failed: ${reason}`,
408
+ peer: selectedPeer
409
+ };
410
+ }
411
+ }
261
412
  const escrowId = holdEscrow(this.creditDb, this.owner, selectedCost, selectedCardId);
262
413
  try {
263
- const requestParams = selectedSkillId ? { skill_id: selectedSkillId, ...need.params, requester: this.owner } : { ...need.params, requester: this.owner };
264
414
  let execResult;
265
415
  if (selectedViaRelay) {
266
416
  if (!this.registryUrl) {
@@ -276,39 +426,15 @@ var AutoRequestor = class {
276
426
  releaseEscrow(this.creditDb, escrowId);
277
427
  return { status: "no_peer", reason: "Relay target found but registryUrl is not configured" };
278
428
  }
279
- const relayRequesterOwner = `${this.owner}:req:${randomUUID()}`;
280
- const { RelayClient } = await import("./websocket-client-QOVARTRN.js");
281
- const relayClient = new RelayClient({
429
+ execResult = await requestViaTemporaryRelay({
282
430
  registryUrl: this.registryUrl,
283
- owner: relayRequesterOwner,
431
+ owner: this.owner,
284
432
  token: "auto-request-token",
285
- card: {
286
- spec_version: "1.0",
287
- id: randomUUID(),
288
- owner: relayRequesterOwner,
289
- name: relayRequesterOwner,
290
- description: "Auto-request requester",
291
- level: 1,
292
- inputs: [],
293
- outputs: [],
294
- pricing: { credits_per_call: 1 },
295
- availability: { online: false }
296
- },
297
- onRequest: async () => ({ error: { code: -32601, message: "Auto-request relay requester does not serve capabilities" } }),
298
- silent: true
433
+ targetOwner: selectedPeer,
434
+ cardId: selectedCardId,
435
+ skillId: selectedSkillId,
436
+ params: requestParams
299
437
  });
300
- try {
301
- await relayClient.connect();
302
- execResult = await requestViaRelay(relayClient, {
303
- targetOwner: selectedPeer,
304
- cardId: selectedCardId,
305
- skillId: selectedSkillId,
306
- params: requestParams,
307
- requester: this.owner
308
- });
309
- } finally {
310
- relayClient.disconnect();
311
- }
312
438
  } else {
313
439
  const peerConfig = findPeer(selectedPeer);
314
440
  if (!peerConfig) {
@@ -395,6 +521,7 @@ var AutoRequestor = class {
395
521
  };
396
522
 
397
523
  export {
524
+ requestViaTemporaryRelay,
398
525
  DEFAULT_BUDGET_CONFIG,
399
526
  BudgetManager,
400
527
  scorePeers,