agentbnb 8.2.3 → 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.
- package/dist/{card-EX2EYGCZ.js → card-BN643ZOY.js} +6 -2
- package/dist/card-T2XJZA5A.js +92 -0
- package/dist/{chunk-3LWBH7P3.js → chunk-4NFJ3VYZ.js} +20 -1
- package/dist/chunk-5AIYALBX.js +857 -0
- package/dist/chunk-6QMDJVMS.js +238 -0
- package/dist/{chunk-LKLKYXLV.js → chunk-74LZDEDT.js} +6 -4
- package/dist/{chunk-GKVTD4EZ.js → chunk-77KGEDH4.js} +1 -1
- package/dist/{chunk-QCGIG7WW.js → chunk-7IQE34QK.js} +14 -7
- package/dist/{chunk-QHZGOG3O.js → chunk-D242QZCR.js} +168 -41
- package/dist/chunk-EE3V3DXK.js +60 -0
- package/dist/{chunk-RYISHSHB.js → chunk-F3KIEVJ2.js} +207 -265
- package/dist/{chunk-XBGVQMQJ.js → chunk-FELGHDCA.js} +16 -39
- package/dist/{chunk-EJKW57ZV.js → chunk-GIEJVKZZ.js} +1 -1
- package/dist/{chunk-WVY2W7AA.js → chunk-I7KWA7OB.js} +20 -0
- package/dist/{chunk-4IPJJRTP.js → chunk-IGQNP3ZO.js} +5 -2
- package/dist/chunk-NQANA6WH.js +797 -0
- package/dist/{chunk-Z4MCGKTL.js → chunk-NX27AFPA.js} +15 -2
- package/dist/{chunk-Z2GEFFDO.js → chunk-O4Q7BRG6.js} +2 -2
- package/dist/{chunk-SSK653A6.js → chunk-PQIP7EXY.js} +6 -0
- package/dist/{chunk-EG6RS4JC.js → chunk-QFPXZITP.js} +20 -65
- package/dist/chunk-R4F4XII4.js +264 -0
- package/dist/{chunk-DYQOFGGI.js → chunk-RVBW2QXU.js} +178 -49
- package/dist/{chunk-CQFBNTGT.js → chunk-S7DZHKCG.js} +25 -12
- package/dist/chunk-U6LP4KWN.js +238 -0
- package/dist/{chunk-MWOXW7JQ.js → chunk-VJ7XBEY6.js} +24 -16
- package/dist/chunk-WTHMHNKC.js +129 -0
- package/dist/{chunk-OCSU2S6W.js → chunk-WX3GZVFG.js} +2 -1
- package/dist/{chunk-CKOOVZOI.js → chunk-YKMBFQC2.js} +37 -5
- package/dist/{chunk-S3V6R3EN.js → chunk-ZU2TP7CN.js} +70 -27
- package/dist/cli/index.js +203 -237
- package/dist/client-OKJJ3UP2.js +19 -0
- package/dist/client-UQBGCIPA.js +20 -0
- package/dist/conduct-4JDMWBQD.js +22 -0
- package/dist/{conduct-AZFLNUX3.js → conduct-VYYBCPHA.js} +14 -13
- package/dist/{conductor-mode-WKB42PYM.js → conductor-mode-OPGQJFLA.js} +12 -8
- package/dist/{conductor-mode-PLTB6MS3.js → conductor-mode-SBDCRIX6.js} +16 -11
- package/dist/execute-FZLQGIXB.js +14 -0
- package/dist/execute-TEZPQ5WP.js +15 -0
- package/dist/index.d.ts +172 -11
- package/dist/index.js +1529 -433
- package/dist/{process-guard-GH5LRNWO.js → process-guard-TNSUNHSR.js} +1 -1
- package/dist/{publish-capability-QDR2QIZ2.js → publish-capability-HVYILTPR.js} +4 -3
- package/dist/{reliability-metrics-QG7WC5QK.js → reliability-metrics-G7LPUYJD.js} +3 -1
- package/dist/reliability-metrics-RRUKJ4ME.js +20 -0
- package/dist/{request-OERS5BE7.js → request-KJNKR27T.js} +76 -71
- package/dist/{serve-skill-E6EJQYAK.js → serve-skill-GC6NIQ5T.js} +10 -11
- package/dist/{server-46VEG2W7.js → server-YV3XPTX5.js} +11 -10
- package/dist/{service-coordinator-KMSA6BST.js → service-coordinator-RY5AKUZS.js} +420 -171
- package/dist/{skill-config-FETXPNVP.js → skill-config-5O2VR546.js} +1 -1
- package/dist/skills/agentbnb/bootstrap.js +528 -253
- package/dist/websocket-client-3U27WJUU.js +7 -0
- package/dist/{websocket-client-4Z5P54RU.js → websocket-client-SNDF3B6N.js} +1 -1
- package/package.json +1 -1
- package/dist/chunk-MCED4GDW.js +0 -1572
- package/dist/chunk-NWIQJ2CL.js +0 -108
- package/dist/chunk-TUCEDQGM.js +0 -44
- package/dist/chunk-WNXXLCV5.js +0 -32
- package/dist/client-XOLP5IUZ.js +0 -12
- package/dist/conduct-VPUYTNEA.js +0 -21
- package/dist/execute-NNDCXTN4.js +0 -13
- package/dist/execute-RIRHTIBU.js +0 -16
- package/dist/websocket-client-QOVARTRN.js +0 -7
package/dist/chunk-MCED4GDW.js
DELETED
|
@@ -1,1572 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
ensureReliabilityTable,
|
|
3
|
-
recordSuccessfulHire
|
|
4
|
-
} from "./chunk-NWIQJ2CL.js";
|
|
5
|
-
import {
|
|
6
|
-
AgentBnBError,
|
|
7
|
-
AnyCardSchema,
|
|
8
|
-
CapabilityCardSchema
|
|
9
|
-
} from "./chunk-WVY2W7AA.js";
|
|
10
|
-
|
|
11
|
-
// src/registry/request-log.ts
|
|
12
|
-
var SINCE_MS = {
|
|
13
|
-
"24h": 864e5,
|
|
14
|
-
"7d": 6048e5,
|
|
15
|
-
"30d": 2592e6
|
|
16
|
-
};
|
|
17
|
-
function createRequestLogTable(db) {
|
|
18
|
-
db.exec(`
|
|
19
|
-
CREATE TABLE IF NOT EXISTS request_log (
|
|
20
|
-
id TEXT PRIMARY KEY,
|
|
21
|
-
card_id TEXT NOT NULL,
|
|
22
|
-
card_name TEXT NOT NULL,
|
|
23
|
-
requester TEXT NOT NULL,
|
|
24
|
-
status TEXT NOT NULL CHECK(status IN ('success', 'failure', 'timeout')),
|
|
25
|
-
latency_ms INTEGER NOT NULL,
|
|
26
|
-
credits_charged INTEGER NOT NULL,
|
|
27
|
-
created_at TEXT NOT NULL
|
|
28
|
-
);
|
|
29
|
-
|
|
30
|
-
CREATE INDEX IF NOT EXISTS request_log_created_at_idx
|
|
31
|
-
ON request_log (created_at DESC);
|
|
32
|
-
`);
|
|
33
|
-
try {
|
|
34
|
-
db.exec("ALTER TABLE request_log ADD COLUMN skill_id TEXT");
|
|
35
|
-
} catch {
|
|
36
|
-
}
|
|
37
|
-
try {
|
|
38
|
-
db.exec("ALTER TABLE request_log ADD COLUMN action_type TEXT");
|
|
39
|
-
} catch {
|
|
40
|
-
}
|
|
41
|
-
try {
|
|
42
|
-
db.exec("ALTER TABLE request_log ADD COLUMN tier_invoked INTEGER");
|
|
43
|
-
} catch {
|
|
44
|
-
}
|
|
45
|
-
try {
|
|
46
|
-
db.exec("ALTER TABLE request_log ADD COLUMN failure_reason TEXT");
|
|
47
|
-
} catch {
|
|
48
|
-
}
|
|
49
|
-
try {
|
|
50
|
-
db.exec("ALTER TABLE request_log ADD COLUMN team_id TEXT");
|
|
51
|
-
} catch {
|
|
52
|
-
}
|
|
53
|
-
try {
|
|
54
|
-
db.exec("ALTER TABLE request_log ADD COLUMN role TEXT");
|
|
55
|
-
} catch {
|
|
56
|
-
}
|
|
57
|
-
try {
|
|
58
|
-
db.exec("ALTER TABLE request_log ADD COLUMN capability_type TEXT");
|
|
59
|
-
} catch {
|
|
60
|
-
}
|
|
61
|
-
}
|
|
62
|
-
function insertRequestLog(db, entry) {
|
|
63
|
-
const stmt = db.prepare(`
|
|
64
|
-
INSERT INTO request_log (id, card_id, card_name, requester, status, latency_ms, credits_charged, created_at, skill_id, action_type, tier_invoked, failure_reason, team_id, role, capability_type)
|
|
65
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
66
|
-
`);
|
|
67
|
-
stmt.run(
|
|
68
|
-
entry.id,
|
|
69
|
-
entry.card_id,
|
|
70
|
-
entry.card_name,
|
|
71
|
-
entry.requester,
|
|
72
|
-
entry.status,
|
|
73
|
-
entry.latency_ms,
|
|
74
|
-
entry.credits_charged,
|
|
75
|
-
entry.created_at,
|
|
76
|
-
entry.skill_id ?? null,
|
|
77
|
-
entry.action_type ?? null,
|
|
78
|
-
entry.tier_invoked ?? null,
|
|
79
|
-
entry.failure_reason ?? null,
|
|
80
|
-
entry.team_id ?? null,
|
|
81
|
-
entry.role ?? null,
|
|
82
|
-
entry.capability_type ?? null
|
|
83
|
-
);
|
|
84
|
-
}
|
|
85
|
-
function getSkillRequestCount(db, skillId, windowMs) {
|
|
86
|
-
const cutoff = new Date(Date.now() - windowMs).toISOString();
|
|
87
|
-
const stmt = db.prepare(
|
|
88
|
-
`SELECT COUNT(*) as cnt FROM request_log
|
|
89
|
-
WHERE skill_id = ? AND created_at >= ? AND status = 'success' AND action_type IS NULL`
|
|
90
|
-
);
|
|
91
|
-
const row = stmt.get(skillId, cutoff);
|
|
92
|
-
return row.cnt;
|
|
93
|
-
}
|
|
94
|
-
function getActivityFeed(db, limit = 20, since) {
|
|
95
|
-
const effectiveLimit = Math.min(limit, 100);
|
|
96
|
-
if (since !== void 0) {
|
|
97
|
-
const stmt2 = db.prepare(`
|
|
98
|
-
SELECT r.id, r.card_name, r.requester, c.owner AS provider,
|
|
99
|
-
r.status, r.credits_charged, r.latency_ms, r.created_at, r.action_type
|
|
100
|
-
FROM request_log r
|
|
101
|
-
LEFT JOIN capability_cards c ON r.card_id = c.id
|
|
102
|
-
WHERE (r.action_type IS NULL OR r.action_type IN ('auto_share', 'agent_joined'))
|
|
103
|
-
AND r.created_at > ?
|
|
104
|
-
ORDER BY r.created_at DESC
|
|
105
|
-
LIMIT ?
|
|
106
|
-
`);
|
|
107
|
-
return stmt2.all(since, effectiveLimit);
|
|
108
|
-
}
|
|
109
|
-
const stmt = db.prepare(`
|
|
110
|
-
SELECT r.id, r.card_name, r.requester, c.owner AS provider,
|
|
111
|
-
r.status, r.credits_charged, r.latency_ms, r.created_at, r.action_type
|
|
112
|
-
FROM request_log r
|
|
113
|
-
LEFT JOIN capability_cards c ON r.card_id = c.id
|
|
114
|
-
WHERE (r.action_type IS NULL OR r.action_type IN ('auto_share', 'agent_joined'))
|
|
115
|
-
ORDER BY r.created_at DESC
|
|
116
|
-
LIMIT ?
|
|
117
|
-
`);
|
|
118
|
-
return stmt.all(effectiveLimit);
|
|
119
|
-
}
|
|
120
|
-
function getRequestLog(db, limit = 10, since) {
|
|
121
|
-
if (since !== void 0) {
|
|
122
|
-
const cutoff = new Date(Date.now() - SINCE_MS[since]).toISOString();
|
|
123
|
-
const stmt2 = db.prepare(`
|
|
124
|
-
SELECT id, card_id, card_name, requester, status, latency_ms, credits_charged, created_at, skill_id, action_type, tier_invoked, failure_reason, team_id, role, capability_type
|
|
125
|
-
FROM request_log
|
|
126
|
-
WHERE created_at >= ?
|
|
127
|
-
ORDER BY created_at DESC
|
|
128
|
-
LIMIT ?
|
|
129
|
-
`);
|
|
130
|
-
return stmt2.all(cutoff, limit);
|
|
131
|
-
}
|
|
132
|
-
const stmt = db.prepare(`
|
|
133
|
-
SELECT id, card_id, card_name, requester, status, latency_ms, credits_charged, created_at, skill_id, action_type, tier_invoked, failure_reason, team_id, role
|
|
134
|
-
FROM request_log
|
|
135
|
-
ORDER BY created_at DESC
|
|
136
|
-
LIMIT ?
|
|
137
|
-
`);
|
|
138
|
-
return stmt.all(limit);
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
// src/registry/store.ts
|
|
142
|
-
import Database from "better-sqlite3";
|
|
143
|
-
|
|
144
|
-
// src/feedback/store.ts
|
|
145
|
-
import { randomUUID } from "crypto";
|
|
146
|
-
function initFeedbackTable(db) {
|
|
147
|
-
db.exec(`
|
|
148
|
-
CREATE TABLE IF NOT EXISTS feedback (
|
|
149
|
-
id TEXT PRIMARY KEY,
|
|
150
|
-
transaction_id TEXT NOT NULL,
|
|
151
|
-
provider_agent TEXT NOT NULL,
|
|
152
|
-
skill_id TEXT NOT NULL,
|
|
153
|
-
requester_agent TEXT NOT NULL,
|
|
154
|
-
rating INTEGER NOT NULL,
|
|
155
|
-
latency_ms INTEGER NOT NULL,
|
|
156
|
-
result_quality TEXT NOT NULL,
|
|
157
|
-
quality_details TEXT,
|
|
158
|
-
would_reuse INTEGER NOT NULL,
|
|
159
|
-
cost_value_ratio TEXT NOT NULL,
|
|
160
|
-
timestamp TEXT NOT NULL,
|
|
161
|
-
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
162
|
-
);
|
|
163
|
-
|
|
164
|
-
CREATE INDEX IF NOT EXISTS feedback_provider_idx ON feedback(provider_agent);
|
|
165
|
-
CREATE INDEX IF NOT EXISTS feedback_skill_idx ON feedback(skill_id);
|
|
166
|
-
`);
|
|
167
|
-
}
|
|
168
|
-
function insertFeedback(db, feedback) {
|
|
169
|
-
const id = randomUUID();
|
|
170
|
-
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
171
|
-
db.prepare(`
|
|
172
|
-
INSERT INTO feedback (
|
|
173
|
-
id, transaction_id, provider_agent, skill_id, requester_agent,
|
|
174
|
-
rating, latency_ms, result_quality, quality_details,
|
|
175
|
-
would_reuse, cost_value_ratio, timestamp, created_at
|
|
176
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
177
|
-
`).run(
|
|
178
|
-
id,
|
|
179
|
-
feedback.transaction_id,
|
|
180
|
-
feedback.provider_agent,
|
|
181
|
-
feedback.skill_id,
|
|
182
|
-
feedback.requester_agent,
|
|
183
|
-
feedback.rating,
|
|
184
|
-
feedback.latency_ms,
|
|
185
|
-
feedback.result_quality,
|
|
186
|
-
feedback.quality_details ?? null,
|
|
187
|
-
feedback.would_reuse ? 1 : 0,
|
|
188
|
-
feedback.cost_value_ratio,
|
|
189
|
-
feedback.timestamp,
|
|
190
|
-
now
|
|
191
|
-
);
|
|
192
|
-
return id;
|
|
193
|
-
}
|
|
194
|
-
function getFeedbackForSkill(db, skillId, limit = 20) {
|
|
195
|
-
const rows = db.prepare(`
|
|
196
|
-
SELECT * FROM feedback
|
|
197
|
-
WHERE skill_id = ?
|
|
198
|
-
ORDER BY timestamp DESC
|
|
199
|
-
LIMIT ?
|
|
200
|
-
`).all(skillId, limit);
|
|
201
|
-
return rows.map(rowToFeedback);
|
|
202
|
-
}
|
|
203
|
-
function getFeedbackForProvider(db, providerAgent, sinceDays) {
|
|
204
|
-
let rows;
|
|
205
|
-
if (sinceDays !== void 0) {
|
|
206
|
-
rows = db.prepare(`
|
|
207
|
-
SELECT * FROM feedback
|
|
208
|
-
WHERE provider_agent = ?
|
|
209
|
-
AND timestamp >= datetime('now', ? || ' days')
|
|
210
|
-
ORDER BY timestamp DESC
|
|
211
|
-
`).all(providerAgent, `-${sinceDays}`);
|
|
212
|
-
} else {
|
|
213
|
-
rows = db.prepare(`
|
|
214
|
-
SELECT * FROM feedback
|
|
215
|
-
WHERE provider_agent = ?
|
|
216
|
-
ORDER BY timestamp DESC
|
|
217
|
-
`).all(providerAgent);
|
|
218
|
-
}
|
|
219
|
-
return rows.map(rowToFeedback);
|
|
220
|
-
}
|
|
221
|
-
function rowToFeedback(row) {
|
|
222
|
-
return {
|
|
223
|
-
transaction_id: row["transaction_id"],
|
|
224
|
-
provider_agent: row["provider_agent"],
|
|
225
|
-
skill_id: row["skill_id"],
|
|
226
|
-
requester_agent: row["requester_agent"],
|
|
227
|
-
rating: row["rating"],
|
|
228
|
-
latency_ms: row["latency_ms"],
|
|
229
|
-
result_quality: row["result_quality"],
|
|
230
|
-
quality_details: row["quality_details"] ?? void 0,
|
|
231
|
-
would_reuse: row["would_reuse"] === 1,
|
|
232
|
-
cost_value_ratio: row["cost_value_ratio"],
|
|
233
|
-
timestamp: row["timestamp"]
|
|
234
|
-
};
|
|
235
|
-
}
|
|
236
|
-
|
|
237
|
-
// src/evolution/store.ts
|
|
238
|
-
import { randomUUID as randomUUID2 } from "crypto";
|
|
239
|
-
function initEvolutionTable(db) {
|
|
240
|
-
db.exec(`
|
|
241
|
-
CREATE TABLE IF NOT EXISTS evolution_versions (
|
|
242
|
-
id TEXT PRIMARY KEY,
|
|
243
|
-
template_name TEXT NOT NULL,
|
|
244
|
-
template_version TEXT NOT NULL,
|
|
245
|
-
publisher_agent TEXT NOT NULL,
|
|
246
|
-
changelog TEXT NOT NULL,
|
|
247
|
-
core_memory_snapshot TEXT NOT NULL,
|
|
248
|
-
fitness_improvement REAL NOT NULL,
|
|
249
|
-
timestamp TEXT NOT NULL,
|
|
250
|
-
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
251
|
-
);
|
|
252
|
-
|
|
253
|
-
CREATE INDEX IF NOT EXISTS evolution_template_idx
|
|
254
|
-
ON evolution_versions(template_name, created_at DESC);
|
|
255
|
-
`);
|
|
256
|
-
}
|
|
257
|
-
function insertEvolution(db, ev) {
|
|
258
|
-
const id = randomUUID2();
|
|
259
|
-
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
260
|
-
db.prepare(`
|
|
261
|
-
INSERT INTO evolution_versions (
|
|
262
|
-
id, template_name, template_version, publisher_agent,
|
|
263
|
-
changelog, core_memory_snapshot, fitness_improvement, timestamp, created_at
|
|
264
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
265
|
-
`).run(
|
|
266
|
-
id,
|
|
267
|
-
ev.template_name,
|
|
268
|
-
ev.template_version,
|
|
269
|
-
ev.publisher_agent,
|
|
270
|
-
ev.changelog,
|
|
271
|
-
JSON.stringify(ev.core_memory_snapshot),
|
|
272
|
-
ev.fitness_improvement,
|
|
273
|
-
ev.timestamp,
|
|
274
|
-
now
|
|
275
|
-
);
|
|
276
|
-
return id;
|
|
277
|
-
}
|
|
278
|
-
function getLatestEvolution(db, templateName) {
|
|
279
|
-
const row = db.prepare(`
|
|
280
|
-
SELECT * FROM evolution_versions
|
|
281
|
-
WHERE template_name = ?
|
|
282
|
-
ORDER BY created_at DESC
|
|
283
|
-
LIMIT 1
|
|
284
|
-
`).get(templateName);
|
|
285
|
-
if (!row) return null;
|
|
286
|
-
return rowToEvolution(row);
|
|
287
|
-
}
|
|
288
|
-
function getEvolutionHistory(db, templateName, limit = 20) {
|
|
289
|
-
const rows = db.prepare(`
|
|
290
|
-
SELECT * FROM evolution_versions
|
|
291
|
-
WHERE template_name = ?
|
|
292
|
-
ORDER BY created_at DESC
|
|
293
|
-
LIMIT ?
|
|
294
|
-
`).all(templateName, limit);
|
|
295
|
-
return rows.map(rowToEvolution);
|
|
296
|
-
}
|
|
297
|
-
function rowToEvolution(row) {
|
|
298
|
-
return {
|
|
299
|
-
template_name: row["template_name"],
|
|
300
|
-
template_version: row["template_version"],
|
|
301
|
-
publisher_agent: row["publisher_agent"],
|
|
302
|
-
changelog: row["changelog"],
|
|
303
|
-
core_memory_snapshot: JSON.parse(row["core_memory_snapshot"]),
|
|
304
|
-
fitness_improvement: row["fitness_improvement"],
|
|
305
|
-
timestamp: row["timestamp"]
|
|
306
|
-
};
|
|
307
|
-
}
|
|
308
|
-
|
|
309
|
-
// src/registry/store.ts
|
|
310
|
-
var V2_FTS_TRIGGERS = `
|
|
311
|
-
DROP TRIGGER IF EXISTS cards_ai;
|
|
312
|
-
DROP TRIGGER IF EXISTS cards_au;
|
|
313
|
-
DROP TRIGGER IF EXISTS cards_ad;
|
|
314
|
-
|
|
315
|
-
CREATE TRIGGER cards_ai AFTER INSERT ON capability_cards BEGIN
|
|
316
|
-
INSERT INTO cards_fts(rowid, id, owner, name, description, tags)
|
|
317
|
-
VALUES (
|
|
318
|
-
new.rowid,
|
|
319
|
-
new.id,
|
|
320
|
-
new.owner,
|
|
321
|
-
COALESCE(
|
|
322
|
-
(SELECT group_concat(
|
|
323
|
-
COALESCE(json_extract(value, '$.id'), '') || ' ' || COALESCE(json_extract(value, '$.name'), ''),
|
|
324
|
-
' '
|
|
325
|
-
)
|
|
326
|
-
FROM json_each(json_extract(new.data, '$.skills'))),
|
|
327
|
-
json_extract(new.data, '$.name'),
|
|
328
|
-
''
|
|
329
|
-
),
|
|
330
|
-
COALESCE(
|
|
331
|
-
(SELECT group_concat(json_extract(value, '$.description'), ' ')
|
|
332
|
-
FROM json_each(json_extract(new.data, '$.skills'))),
|
|
333
|
-
json_extract(new.data, '$.description'),
|
|
334
|
-
''
|
|
335
|
-
),
|
|
336
|
-
COALESCE(
|
|
337
|
-
(SELECT group_concat(json_extract(value, '$.metadata.tags'), ' ')
|
|
338
|
-
FROM json_each(json_extract(new.data, '$.skills'))),
|
|
339
|
-
(SELECT group_concat(value, ' ')
|
|
340
|
-
FROM json_each(json_extract(new.data, '$.metadata.tags'))),
|
|
341
|
-
''
|
|
342
|
-
)
|
|
343
|
-
|| ' ' || COALESCE(
|
|
344
|
-
(SELECT group_concat(json_extract(skill.value, '$.capability_type'), ' ')
|
|
345
|
-
FROM json_each(json_extract(new.data, '$.skills')) AS skill),
|
|
346
|
-
''
|
|
347
|
-
)
|
|
348
|
-
|| ' ' || COALESCE(
|
|
349
|
-
(SELECT group_concat(cap_type.value, ' ')
|
|
350
|
-
FROM json_each(json_extract(new.data, '$.skills')) AS skill,
|
|
351
|
-
json_each(json_extract(skill.value, '$.capability_types')) AS cap_type),
|
|
352
|
-
''
|
|
353
|
-
)
|
|
354
|
-
);
|
|
355
|
-
END;
|
|
356
|
-
|
|
357
|
-
CREATE TRIGGER cards_au AFTER UPDATE ON capability_cards BEGIN
|
|
358
|
-
INSERT INTO cards_fts(cards_fts, rowid, id, owner, name, description, tags)
|
|
359
|
-
VALUES (
|
|
360
|
-
'delete',
|
|
361
|
-
old.rowid,
|
|
362
|
-
old.id,
|
|
363
|
-
old.owner,
|
|
364
|
-
COALESCE(
|
|
365
|
-
(SELECT group_concat(
|
|
366
|
-
COALESCE(json_extract(value, '$.id'), '') || ' ' || COALESCE(json_extract(value, '$.name'), ''),
|
|
367
|
-
' '
|
|
368
|
-
)
|
|
369
|
-
FROM json_each(json_extract(old.data, '$.skills'))),
|
|
370
|
-
json_extract(old.data, '$.name'),
|
|
371
|
-
''
|
|
372
|
-
),
|
|
373
|
-
COALESCE(
|
|
374
|
-
(SELECT group_concat(json_extract(value, '$.description'), ' ')
|
|
375
|
-
FROM json_each(json_extract(old.data, '$.skills'))),
|
|
376
|
-
json_extract(old.data, '$.description'),
|
|
377
|
-
''
|
|
378
|
-
),
|
|
379
|
-
COALESCE(
|
|
380
|
-
(SELECT group_concat(json_extract(value, '$.metadata.tags'), ' ')
|
|
381
|
-
FROM json_each(json_extract(old.data, '$.skills'))),
|
|
382
|
-
(SELECT group_concat(value, ' ')
|
|
383
|
-
FROM json_each(json_extract(old.data, '$.metadata.tags'))),
|
|
384
|
-
''
|
|
385
|
-
)
|
|
386
|
-
|| ' ' || COALESCE(
|
|
387
|
-
(SELECT group_concat(json_extract(skill.value, '$.capability_type'), ' ')
|
|
388
|
-
FROM json_each(json_extract(old.data, '$.skills')) AS skill),
|
|
389
|
-
''
|
|
390
|
-
)
|
|
391
|
-
|| ' ' || COALESCE(
|
|
392
|
-
(SELECT group_concat(cap_type.value, ' ')
|
|
393
|
-
FROM json_each(json_extract(old.data, '$.skills')) AS skill,
|
|
394
|
-
json_each(json_extract(skill.value, '$.capability_types')) AS cap_type),
|
|
395
|
-
''
|
|
396
|
-
)
|
|
397
|
-
);
|
|
398
|
-
INSERT INTO cards_fts(rowid, id, owner, name, description, tags)
|
|
399
|
-
VALUES (
|
|
400
|
-
new.rowid,
|
|
401
|
-
new.id,
|
|
402
|
-
new.owner,
|
|
403
|
-
COALESCE(
|
|
404
|
-
(SELECT group_concat(
|
|
405
|
-
COALESCE(json_extract(value, '$.id'), '') || ' ' || COALESCE(json_extract(value, '$.name'), ''),
|
|
406
|
-
' '
|
|
407
|
-
)
|
|
408
|
-
FROM json_each(json_extract(new.data, '$.skills'))),
|
|
409
|
-
json_extract(new.data, '$.name'),
|
|
410
|
-
''
|
|
411
|
-
),
|
|
412
|
-
COALESCE(
|
|
413
|
-
(SELECT group_concat(json_extract(value, '$.description'), ' ')
|
|
414
|
-
FROM json_each(json_extract(new.data, '$.skills'))),
|
|
415
|
-
json_extract(new.data, '$.description'),
|
|
416
|
-
''
|
|
417
|
-
),
|
|
418
|
-
COALESCE(
|
|
419
|
-
(SELECT group_concat(json_extract(value, '$.metadata.tags'), ' ')
|
|
420
|
-
FROM json_each(json_extract(new.data, '$.skills'))),
|
|
421
|
-
(SELECT group_concat(value, ' ')
|
|
422
|
-
FROM json_each(json_extract(new.data, '$.metadata.tags'))),
|
|
423
|
-
''
|
|
424
|
-
)
|
|
425
|
-
|| ' ' || COALESCE(
|
|
426
|
-
(SELECT group_concat(json_extract(skill.value, '$.capability_type'), ' ')
|
|
427
|
-
FROM json_each(json_extract(new.data, '$.skills')) AS skill),
|
|
428
|
-
''
|
|
429
|
-
)
|
|
430
|
-
|| ' ' || COALESCE(
|
|
431
|
-
(SELECT group_concat(cap_type.value, ' ')
|
|
432
|
-
FROM json_each(json_extract(new.data, '$.skills')) AS skill,
|
|
433
|
-
json_each(json_extract(skill.value, '$.capability_types')) AS cap_type),
|
|
434
|
-
''
|
|
435
|
-
)
|
|
436
|
-
);
|
|
437
|
-
END;
|
|
438
|
-
|
|
439
|
-
CREATE TRIGGER cards_ad AFTER DELETE ON capability_cards BEGIN
|
|
440
|
-
INSERT INTO cards_fts(cards_fts, rowid, id, owner, name, description, tags)
|
|
441
|
-
VALUES (
|
|
442
|
-
'delete',
|
|
443
|
-
old.rowid,
|
|
444
|
-
old.id,
|
|
445
|
-
old.owner,
|
|
446
|
-
COALESCE(
|
|
447
|
-
(SELECT group_concat(
|
|
448
|
-
COALESCE(json_extract(value, '$.id'), '') || ' ' || COALESCE(json_extract(value, '$.name'), ''),
|
|
449
|
-
' '
|
|
450
|
-
)
|
|
451
|
-
FROM json_each(json_extract(old.data, '$.skills'))),
|
|
452
|
-
json_extract(old.data, '$.name'),
|
|
453
|
-
''
|
|
454
|
-
),
|
|
455
|
-
COALESCE(
|
|
456
|
-
(SELECT group_concat(json_extract(value, '$.description'), ' ')
|
|
457
|
-
FROM json_each(json_extract(old.data, '$.skills'))),
|
|
458
|
-
json_extract(old.data, '$.description'),
|
|
459
|
-
''
|
|
460
|
-
),
|
|
461
|
-
COALESCE(
|
|
462
|
-
(SELECT group_concat(json_extract(value, '$.metadata.tags'), ' ')
|
|
463
|
-
FROM json_each(json_extract(old.data, '$.skills'))),
|
|
464
|
-
(SELECT group_concat(value, ' ')
|
|
465
|
-
FROM json_each(json_extract(old.data, '$.metadata.tags'))),
|
|
466
|
-
''
|
|
467
|
-
)
|
|
468
|
-
|| ' ' || COALESCE(
|
|
469
|
-
(SELECT group_concat(json_extract(skill.value, '$.capability_type'), ' ')
|
|
470
|
-
FROM json_each(json_extract(old.data, '$.skills')) AS skill),
|
|
471
|
-
''
|
|
472
|
-
)
|
|
473
|
-
|| ' ' || COALESCE(
|
|
474
|
-
(SELECT group_concat(cap_type.value, ' ')
|
|
475
|
-
FROM json_each(json_extract(old.data, '$.skills')) AS skill,
|
|
476
|
-
json_each(json_extract(skill.value, '$.capability_types')) AS cap_type),
|
|
477
|
-
''
|
|
478
|
-
)
|
|
479
|
-
);
|
|
480
|
-
END;
|
|
481
|
-
`;
|
|
482
|
-
function openDatabase(path = ":memory:") {
|
|
483
|
-
const db = new Database(path);
|
|
484
|
-
db.pragma("journal_mode = WAL");
|
|
485
|
-
db.pragma("foreign_keys = ON");
|
|
486
|
-
db.exec(`
|
|
487
|
-
CREATE TABLE IF NOT EXISTS capability_cards (
|
|
488
|
-
id TEXT PRIMARY KEY,
|
|
489
|
-
owner TEXT NOT NULL,
|
|
490
|
-
data TEXT NOT NULL,
|
|
491
|
-
created_at TEXT NOT NULL,
|
|
492
|
-
updated_at TEXT NOT NULL
|
|
493
|
-
);
|
|
494
|
-
|
|
495
|
-
CREATE TABLE IF NOT EXISTS pending_requests (
|
|
496
|
-
id TEXT PRIMARY KEY,
|
|
497
|
-
skill_query TEXT NOT NULL,
|
|
498
|
-
max_cost_credits REAL NOT NULL,
|
|
499
|
-
selected_peer TEXT,
|
|
500
|
-
selected_card_id TEXT,
|
|
501
|
-
selected_skill_id TEXT,
|
|
502
|
-
credits REAL NOT NULL,
|
|
503
|
-
status TEXT NOT NULL DEFAULT 'pending',
|
|
504
|
-
params TEXT,
|
|
505
|
-
created_at TEXT NOT NULL,
|
|
506
|
-
resolved_at TEXT
|
|
507
|
-
);
|
|
508
|
-
|
|
509
|
-
CREATE VIRTUAL TABLE IF NOT EXISTS cards_fts USING fts5(
|
|
510
|
-
id UNINDEXED,
|
|
511
|
-
owner,
|
|
512
|
-
name,
|
|
513
|
-
description,
|
|
514
|
-
tags,
|
|
515
|
-
content=""
|
|
516
|
-
);
|
|
517
|
-
|
|
518
|
-
-- Expression index for capability_type lookups (used by Conductor routing).
|
|
519
|
-
-- Turns json_extract full-table-scan into O(log n) B-tree lookup.
|
|
520
|
-
CREATE INDEX IF NOT EXISTS idx_cards_capability_type
|
|
521
|
-
ON capability_cards(json_extract(data, '$.capability_type'));
|
|
522
|
-
|
|
523
|
-
-- Owner index for listCards(owner) and other owner-scoped queries.
|
|
524
|
-
CREATE INDEX IF NOT EXISTS idx_cards_owner
|
|
525
|
-
ON capability_cards(owner);
|
|
526
|
-
`);
|
|
527
|
-
createRequestLogTable(db);
|
|
528
|
-
initFeedbackTable(db);
|
|
529
|
-
initEvolutionTable(db);
|
|
530
|
-
runMigrations(db);
|
|
531
|
-
return db;
|
|
532
|
-
}
|
|
533
|
-
function runMigrations(db) {
|
|
534
|
-
const version = db.pragma("user_version")[0]?.user_version ?? 0;
|
|
535
|
-
if (version < 2) {
|
|
536
|
-
migrateV1toV2(db);
|
|
537
|
-
return;
|
|
538
|
-
}
|
|
539
|
-
if (version < 3) {
|
|
540
|
-
migrateV2toV3(db);
|
|
541
|
-
}
|
|
542
|
-
}
|
|
543
|
-
function migrateV1toV2(db) {
|
|
544
|
-
const migrate = db.transaction(() => {
|
|
545
|
-
const rows = db.prepare("SELECT rowid, id, data FROM capability_cards").all();
|
|
546
|
-
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
547
|
-
for (const row of rows) {
|
|
548
|
-
const parsed = JSON.parse(row.data);
|
|
549
|
-
if (parsed["spec_version"] === "2.0") continue;
|
|
550
|
-
const v1 = parsed;
|
|
551
|
-
const v2 = {
|
|
552
|
-
spec_version: "2.0",
|
|
553
|
-
id: v1.id,
|
|
554
|
-
owner: v1.owner,
|
|
555
|
-
agent_name: v1.name,
|
|
556
|
-
skills: [
|
|
557
|
-
{
|
|
558
|
-
id: `skill-${v1.id}`,
|
|
559
|
-
name: v1.name,
|
|
560
|
-
description: v1.description,
|
|
561
|
-
level: v1.level,
|
|
562
|
-
inputs: v1.inputs,
|
|
563
|
-
outputs: v1.outputs,
|
|
564
|
-
pricing: v1.pricing,
|
|
565
|
-
availability: { online: v1.availability.online },
|
|
566
|
-
powered_by: v1.powered_by,
|
|
567
|
-
metadata: v1.metadata,
|
|
568
|
-
_internal: v1._internal
|
|
569
|
-
}
|
|
570
|
-
],
|
|
571
|
-
availability: v1.availability,
|
|
572
|
-
created_at: v1.created_at,
|
|
573
|
-
updated_at: now
|
|
574
|
-
};
|
|
575
|
-
db.prepare("UPDATE capability_cards SET data = ?, updated_at = ? WHERE id = ?").run(
|
|
576
|
-
JSON.stringify(v2),
|
|
577
|
-
now,
|
|
578
|
-
v2.id
|
|
579
|
-
);
|
|
580
|
-
}
|
|
581
|
-
db.exec(V2_FTS_TRIGGERS);
|
|
582
|
-
rebuildCardsFts(db);
|
|
583
|
-
db.pragma("user_version = 3");
|
|
584
|
-
});
|
|
585
|
-
migrate();
|
|
586
|
-
}
|
|
587
|
-
function migrateV2toV3(db) {
|
|
588
|
-
const migrate = db.transaction(() => {
|
|
589
|
-
db.exec(V2_FTS_TRIGGERS);
|
|
590
|
-
rebuildCardsFts(db);
|
|
591
|
-
db.pragma("user_version = 3");
|
|
592
|
-
});
|
|
593
|
-
migrate();
|
|
594
|
-
}
|
|
595
|
-
function rebuildCardsFts(db) {
|
|
596
|
-
db.exec(`INSERT INTO cards_fts(cards_fts) VALUES('delete-all')`);
|
|
597
|
-
const allRows = db.prepare("SELECT rowid, id, owner, data FROM capability_cards").all();
|
|
598
|
-
const ftsInsert = db.prepare(
|
|
599
|
-
"INSERT INTO cards_fts(rowid, id, owner, name, description, tags) VALUES (?, ?, ?, ?, ?, ?)"
|
|
600
|
-
);
|
|
601
|
-
for (const row of allRows) {
|
|
602
|
-
const data = JSON.parse(row.data);
|
|
603
|
-
const skills = data["skills"] ?? [];
|
|
604
|
-
let name;
|
|
605
|
-
let description;
|
|
606
|
-
let tags;
|
|
607
|
-
if (skills.length > 0) {
|
|
608
|
-
name = skills.map((s) => `${String(s["id"] ?? "")} ${String(s["name"] ?? "")}`.trim()).join(" ");
|
|
609
|
-
description = skills.map((s) => String(s["description"] ?? "")).join(" ");
|
|
610
|
-
tags = [
|
|
611
|
-
// tags from metadata.tags[]
|
|
612
|
-
...skills.flatMap((s) => {
|
|
613
|
-
const meta = s["metadata"];
|
|
614
|
-
return meta?.["tags"] ?? [];
|
|
615
|
-
}),
|
|
616
|
-
// capability_type (singular)
|
|
617
|
-
...skills.map((s) => s["capability_type"]).filter((v) => typeof v === "string" && v.length > 0),
|
|
618
|
-
// capability_types[] (plural)
|
|
619
|
-
...skills.flatMap((s) => s["capability_types"] ?? [])
|
|
620
|
-
].join(" ");
|
|
621
|
-
} else {
|
|
622
|
-
name = String(data["name"] ?? "");
|
|
623
|
-
description = String(data["description"] ?? "");
|
|
624
|
-
const meta = data["metadata"];
|
|
625
|
-
const rawTags = meta?.["tags"] ?? [];
|
|
626
|
-
tags = rawTags.join(" ");
|
|
627
|
-
}
|
|
628
|
-
ftsInsert.run(row.rowid, row.id, row.owner, name, description, tags);
|
|
629
|
-
}
|
|
630
|
-
}
|
|
631
|
-
function insertCard(db, card) {
|
|
632
|
-
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
633
|
-
const withTimestamps = { ...card, created_at: card.created_at ?? now, updated_at: now };
|
|
634
|
-
const parsed = CapabilityCardSchema.safeParse(withTimestamps);
|
|
635
|
-
if (!parsed.success) {
|
|
636
|
-
throw new AgentBnBError(
|
|
637
|
-
`Card validation failed: ${parsed.error.message}`,
|
|
638
|
-
"VALIDATION_ERROR"
|
|
639
|
-
);
|
|
640
|
-
}
|
|
641
|
-
const stmt = db.prepare(`
|
|
642
|
-
INSERT INTO capability_cards (id, owner, data, created_at, updated_at)
|
|
643
|
-
VALUES (?, ?, ?, ?, ?)
|
|
644
|
-
`);
|
|
645
|
-
stmt.run(
|
|
646
|
-
parsed.data.id,
|
|
647
|
-
parsed.data.owner,
|
|
648
|
-
JSON.stringify(parsed.data),
|
|
649
|
-
parsed.data.created_at ?? now,
|
|
650
|
-
parsed.data.updated_at ?? now
|
|
651
|
-
);
|
|
652
|
-
}
|
|
653
|
-
function getCard(db, id) {
|
|
654
|
-
const stmt = db.prepare("SELECT data FROM capability_cards WHERE id = ?");
|
|
655
|
-
const row = stmt.get(id);
|
|
656
|
-
if (!row) return null;
|
|
657
|
-
return JSON.parse(row.data);
|
|
658
|
-
}
|
|
659
|
-
function updateCard(db, id, owner, updates) {
|
|
660
|
-
const existing = getCard(db, id);
|
|
661
|
-
if (!existing) {
|
|
662
|
-
throw new AgentBnBError(`Card not found: ${id}`, "NOT_FOUND");
|
|
663
|
-
}
|
|
664
|
-
if (existing.owner !== owner) {
|
|
665
|
-
throw new AgentBnBError("Forbidden: you do not own this card", "FORBIDDEN");
|
|
666
|
-
}
|
|
667
|
-
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
668
|
-
const merged = { ...existing, ...updates, updated_at: now };
|
|
669
|
-
const parsed = AnyCardSchema.safeParse(merged);
|
|
670
|
-
if (!parsed.success) {
|
|
671
|
-
throw new AgentBnBError(
|
|
672
|
-
`Card validation failed: ${parsed.error.message}`,
|
|
673
|
-
"VALIDATION_ERROR"
|
|
674
|
-
);
|
|
675
|
-
}
|
|
676
|
-
const stmt = db.prepare(`
|
|
677
|
-
UPDATE capability_cards
|
|
678
|
-
SET data = ?, updated_at = ?
|
|
679
|
-
WHERE id = ?
|
|
680
|
-
`);
|
|
681
|
-
stmt.run(JSON.stringify(parsed.data), now, id);
|
|
682
|
-
}
|
|
683
|
-
function updateReputation(db, cardId, success, latencyMs) {
|
|
684
|
-
const existing = getCard(db, cardId);
|
|
685
|
-
if (!existing) return;
|
|
686
|
-
const ALPHA = 0.1;
|
|
687
|
-
const observed = success ? 1 : 0;
|
|
688
|
-
const prevSuccessRate = existing.metadata?.success_rate;
|
|
689
|
-
const prevLatency = existing.metadata?.avg_latency_ms;
|
|
690
|
-
const newSuccessRate = prevSuccessRate === void 0 ? observed : ALPHA * observed + (1 - ALPHA) * prevSuccessRate;
|
|
691
|
-
const newLatency = prevLatency === void 0 ? latencyMs : ALPHA * latencyMs + (1 - ALPHA) * prevLatency;
|
|
692
|
-
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
693
|
-
const updatedMetadata = {
|
|
694
|
-
...existing.metadata,
|
|
695
|
-
success_rate: Math.round(newSuccessRate * 1e3) / 1e3,
|
|
696
|
-
avg_latency_ms: Math.round(newLatency)
|
|
697
|
-
};
|
|
698
|
-
const updatedCard = { ...existing, metadata: updatedMetadata, updated_at: now };
|
|
699
|
-
const stmt = db.prepare(`
|
|
700
|
-
UPDATE capability_cards
|
|
701
|
-
SET data = ?, updated_at = ?
|
|
702
|
-
WHERE id = ?
|
|
703
|
-
`);
|
|
704
|
-
stmt.run(JSON.stringify(updatedCard), now, cardId);
|
|
705
|
-
}
|
|
706
|
-
function updateSkillAvailability(db, cardId, skillId, online) {
|
|
707
|
-
const row = db.prepare("SELECT data FROM capability_cards WHERE id = ?").get(cardId);
|
|
708
|
-
if (!row) return;
|
|
709
|
-
const card = JSON.parse(row.data);
|
|
710
|
-
const skills = card["skills"];
|
|
711
|
-
if (!skills) return;
|
|
712
|
-
const skill = skills.find((s) => s["id"] === skillId);
|
|
713
|
-
if (!skill) return;
|
|
714
|
-
const existing = skill["availability"] ?? {};
|
|
715
|
-
skill["availability"] = { ...existing, online };
|
|
716
|
-
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
717
|
-
db.prepare("UPDATE capability_cards SET data = ?, updated_at = ? WHERE id = ?").run(
|
|
718
|
-
JSON.stringify(card),
|
|
719
|
-
now,
|
|
720
|
-
cardId
|
|
721
|
-
);
|
|
722
|
-
}
|
|
723
|
-
function updateSkillIdleRate(db, cardId, skillId, idleRate) {
|
|
724
|
-
const row = db.prepare("SELECT data FROM capability_cards WHERE id = ?").get(cardId);
|
|
725
|
-
if (!row) return;
|
|
726
|
-
const card = JSON.parse(row.data);
|
|
727
|
-
const skills = card["skills"];
|
|
728
|
-
if (!skills) return;
|
|
729
|
-
const skill = skills.find((s) => s["id"] === skillId);
|
|
730
|
-
if (!skill) return;
|
|
731
|
-
const existing = skill["_internal"] ?? {};
|
|
732
|
-
skill["_internal"] = {
|
|
733
|
-
...existing,
|
|
734
|
-
idle_rate: idleRate,
|
|
735
|
-
idle_rate_computed_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
736
|
-
};
|
|
737
|
-
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
738
|
-
db.prepare("UPDATE capability_cards SET data = ?, updated_at = ? WHERE id = ?").run(
|
|
739
|
-
JSON.stringify(card),
|
|
740
|
-
now,
|
|
741
|
-
cardId
|
|
742
|
-
);
|
|
743
|
-
}
|
|
744
|
-
function listCards(db, owner) {
|
|
745
|
-
let stmt;
|
|
746
|
-
let rows;
|
|
747
|
-
if (owner !== void 0) {
|
|
748
|
-
stmt = db.prepare("SELECT data FROM capability_cards WHERE owner = ?");
|
|
749
|
-
rows = stmt.all(owner);
|
|
750
|
-
} else {
|
|
751
|
-
stmt = db.prepare("SELECT data FROM capability_cards");
|
|
752
|
-
rows = stmt.all();
|
|
753
|
-
}
|
|
754
|
-
return rows.map((row) => JSON.parse(row.data));
|
|
755
|
-
}
|
|
756
|
-
function getCardsByCapabilityType(db, capabilityType) {
|
|
757
|
-
const rows = db.prepare(
|
|
758
|
-
"SELECT data FROM capability_cards WHERE json_extract(data, '$.capability_type') = ?"
|
|
759
|
-
).all(capabilityType);
|
|
760
|
-
return rows.map((row) => JSON.parse(row.data));
|
|
761
|
-
}
|
|
762
|
-
function getCardsBySkillCapability(db, capabilityType) {
|
|
763
|
-
const rows = db.prepare("SELECT data FROM capability_cards").all();
|
|
764
|
-
return rows.map((row) => JSON.parse(row.data)).filter((card) => {
|
|
765
|
-
const skills = card["skills"];
|
|
766
|
-
if (!skills) return false;
|
|
767
|
-
return skills.some((skill) => {
|
|
768
|
-
if (skill["capability_type"] === capabilityType) return true;
|
|
769
|
-
const types = skill["capability_types"];
|
|
770
|
-
return Array.isArray(types) && types.includes(capabilityType);
|
|
771
|
-
});
|
|
772
|
-
});
|
|
773
|
-
}
|
|
774
|
-
|
|
775
|
-
// src/credit/ledger.ts
|
|
776
|
-
import Database2 from "better-sqlite3";
|
|
777
|
-
import { randomUUID as randomUUID3 } from "crypto";
|
|
778
|
-
|
|
779
|
-
// src/identity/agent-identity.ts
|
|
780
|
-
var AGENTS_SCHEMA = `
|
|
781
|
-
CREATE TABLE IF NOT EXISTS agents (
|
|
782
|
-
agent_id TEXT PRIMARY KEY,
|
|
783
|
-
display_name TEXT NOT NULL,
|
|
784
|
-
public_key TEXT NOT NULL,
|
|
785
|
-
operator_id TEXT,
|
|
786
|
-
server_id TEXT,
|
|
787
|
-
legacy_owner TEXT,
|
|
788
|
-
created_at TEXT NOT NULL,
|
|
789
|
-
updated_at TEXT NOT NULL
|
|
790
|
-
);
|
|
791
|
-
|
|
792
|
-
CREATE INDEX IF NOT EXISTS idx_agents_operator ON agents(operator_id);
|
|
793
|
-
CREATE INDEX IF NOT EXISTS idx_agents_legacy_owner ON agents(legacy_owner);
|
|
794
|
-
`;
|
|
795
|
-
function ensureAgentsTable(db) {
|
|
796
|
-
db.exec(AGENTS_SCHEMA);
|
|
797
|
-
}
|
|
798
|
-
function lookupAgent(db, agentId) {
|
|
799
|
-
return db.prepare("SELECT * FROM agents WHERE agent_id = ?").get(agentId) ?? null;
|
|
800
|
-
}
|
|
801
|
-
|
|
802
|
-
// src/credit/ledger.ts
|
|
803
|
-
var CREDIT_SCHEMA = `
|
|
804
|
-
CREATE TABLE IF NOT EXISTS credit_balances (
|
|
805
|
-
owner TEXT PRIMARY KEY,
|
|
806
|
-
balance INTEGER NOT NULL DEFAULT 0,
|
|
807
|
-
updated_at TEXT NOT NULL
|
|
808
|
-
);
|
|
809
|
-
|
|
810
|
-
CREATE TABLE IF NOT EXISTS credit_transactions (
|
|
811
|
-
id TEXT PRIMARY KEY,
|
|
812
|
-
owner TEXT NOT NULL,
|
|
813
|
-
amount INTEGER NOT NULL,
|
|
814
|
-
reason TEXT NOT NULL,
|
|
815
|
-
reference_id TEXT,
|
|
816
|
-
created_at TEXT NOT NULL
|
|
817
|
-
);
|
|
818
|
-
|
|
819
|
-
CREATE TABLE IF NOT EXISTS credit_escrow (
|
|
820
|
-
id TEXT PRIMARY KEY,
|
|
821
|
-
owner TEXT NOT NULL,
|
|
822
|
-
amount INTEGER NOT NULL,
|
|
823
|
-
card_id TEXT NOT NULL,
|
|
824
|
-
status TEXT NOT NULL DEFAULT 'held',
|
|
825
|
-
created_at TEXT NOT NULL,
|
|
826
|
-
settled_at TEXT
|
|
827
|
-
);
|
|
828
|
-
|
|
829
|
-
CREATE TABLE IF NOT EXISTS provider_registry (
|
|
830
|
-
owner TEXT PRIMARY KEY,
|
|
831
|
-
provider_number INTEGER NOT NULL,
|
|
832
|
-
registered_at TEXT NOT NULL
|
|
833
|
-
);
|
|
834
|
-
|
|
835
|
-
CREATE TABLE IF NOT EXISTS demand_vouchers (
|
|
836
|
-
id TEXT PRIMARY KEY,
|
|
837
|
-
owner TEXT NOT NULL,
|
|
838
|
-
amount INTEGER NOT NULL,
|
|
839
|
-
remaining INTEGER NOT NULL,
|
|
840
|
-
created_at TEXT NOT NULL,
|
|
841
|
-
expires_at TEXT NOT NULL,
|
|
842
|
-
is_active INTEGER NOT NULL DEFAULT 1
|
|
843
|
-
);
|
|
844
|
-
|
|
845
|
-
CREATE INDEX IF NOT EXISTS idx_transactions_owner ON credit_transactions(owner, created_at);
|
|
846
|
-
CREATE INDEX IF NOT EXISTS idx_escrow_owner ON credit_escrow(owner);
|
|
847
|
-
`;
|
|
848
|
-
function openCreditDb(path = ":memory:") {
|
|
849
|
-
const db = new Database2(path);
|
|
850
|
-
db.pragma("journal_mode = WAL");
|
|
851
|
-
db.pragma("foreign_keys = ON");
|
|
852
|
-
db.exec(CREDIT_SCHEMA);
|
|
853
|
-
try {
|
|
854
|
-
db.exec("ALTER TABLE credit_escrow ADD COLUMN funding_source TEXT NOT NULL DEFAULT 'balance'");
|
|
855
|
-
} catch {
|
|
856
|
-
}
|
|
857
|
-
ensureReliabilityTable(db);
|
|
858
|
-
ensureAgentsTable(db);
|
|
859
|
-
return db;
|
|
860
|
-
}
|
|
861
|
-
function bootstrapAgent(db, owner, amount = 100) {
|
|
862
|
-
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
863
|
-
let isNew = false;
|
|
864
|
-
db.transaction(() => {
|
|
865
|
-
const result = db.prepare("INSERT OR IGNORE INTO credit_balances (owner, balance, updated_at) VALUES (?, ?, ?)").run(owner, amount, now);
|
|
866
|
-
if (result.changes > 0) {
|
|
867
|
-
isNew = true;
|
|
868
|
-
db.prepare(
|
|
869
|
-
"INSERT INTO credit_transactions (id, owner, amount, reason, reference_id, created_at) VALUES (?, ?, ?, ?, ?, ?)"
|
|
870
|
-
).run(randomUUID3(), owner, amount, "bootstrap", null, now);
|
|
871
|
-
}
|
|
872
|
-
})();
|
|
873
|
-
if (isNew) {
|
|
874
|
-
issueVoucher(db, owner, 50, 30);
|
|
875
|
-
}
|
|
876
|
-
}
|
|
877
|
-
function getBalance(db, owner) {
|
|
878
|
-
const row = db.prepare("SELECT balance FROM credit_balances WHERE owner = ?").get(owner);
|
|
879
|
-
return row?.balance ?? 0;
|
|
880
|
-
}
|
|
881
|
-
function getTransactions(db, owner, opts = 100) {
|
|
882
|
-
const page = typeof opts === "number" ? { limit: opts } : opts;
|
|
883
|
-
const limit = page.limit ?? 100;
|
|
884
|
-
const conditions = ["owner = ?"];
|
|
885
|
-
const params = [owner];
|
|
886
|
-
if (page.before) {
|
|
887
|
-
conditions.push("created_at < ?");
|
|
888
|
-
params.push(page.before);
|
|
889
|
-
}
|
|
890
|
-
if (page.after) {
|
|
891
|
-
conditions.push("created_at > ?");
|
|
892
|
-
params.push(page.after);
|
|
893
|
-
}
|
|
894
|
-
params.push(limit);
|
|
895
|
-
return db.prepare(
|
|
896
|
-
`SELECT id, owner, amount, reason, reference_id, created_at FROM credit_transactions WHERE ${conditions.join(" AND ")} ORDER BY created_at DESC LIMIT ?`
|
|
897
|
-
).all(...params);
|
|
898
|
-
}
|
|
899
|
-
function registerProvider(db, owner) {
|
|
900
|
-
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
901
|
-
const maxRow = db.prepare("SELECT MAX(provider_number) as maxNum FROM provider_registry").get();
|
|
902
|
-
const nextNum = (maxRow?.maxNum ?? 0) + 1;
|
|
903
|
-
db.prepare("INSERT OR IGNORE INTO provider_registry (owner, provider_number, registered_at) VALUES (?, ?, ?)").run(owner, nextNum, now);
|
|
904
|
-
const row = db.prepare("SELECT provider_number FROM provider_registry WHERE owner = ?").get(owner);
|
|
905
|
-
return row.provider_number;
|
|
906
|
-
}
|
|
907
|
-
function getProviderNumber(db, owner) {
|
|
908
|
-
const row = db.prepare("SELECT provider_number FROM provider_registry WHERE owner = ?").get(owner);
|
|
909
|
-
return row?.provider_number ?? null;
|
|
910
|
-
}
|
|
911
|
-
function getProviderBonus(providerNumber) {
|
|
912
|
-
if (providerNumber <= 50) return 2;
|
|
913
|
-
if (providerNumber <= 200) return 1.5;
|
|
914
|
-
return 1;
|
|
915
|
-
}
|
|
916
|
-
function issueVoucher(db, owner, amount = 50, daysValid = 30) {
|
|
917
|
-
const id = randomUUID3();
|
|
918
|
-
const now = /* @__PURE__ */ new Date();
|
|
919
|
-
const expiresAt = new Date(now.getTime() + daysValid * 24 * 60 * 60 * 1e3);
|
|
920
|
-
db.prepare(
|
|
921
|
-
"INSERT INTO demand_vouchers (id, owner, amount, remaining, created_at, expires_at, is_active) VALUES (?, ?, ?, ?, ?, ?, 1)"
|
|
922
|
-
).run(id, owner, amount, amount, now.toISOString(), expiresAt.toISOString());
|
|
923
|
-
return id;
|
|
924
|
-
}
|
|
925
|
-
function getActiveVoucher(db, owner) {
|
|
926
|
-
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
927
|
-
const row = db.prepare(
|
|
928
|
-
"SELECT id, remaining, expires_at FROM demand_vouchers WHERE owner = ? AND is_active = 1 AND remaining > 0 AND expires_at > ? ORDER BY created_at ASC LIMIT 1"
|
|
929
|
-
).get(owner, now);
|
|
930
|
-
return row ?? null;
|
|
931
|
-
}
|
|
932
|
-
function consumeVoucher(db, voucherId, amount) {
|
|
933
|
-
db.prepare(
|
|
934
|
-
"UPDATE demand_vouchers SET remaining = remaining - ? WHERE id = ? AND remaining >= ?"
|
|
935
|
-
).run(amount, voucherId, amount);
|
|
936
|
-
}
|
|
937
|
-
function recordEarning(db, owner, amount, _cardId, receiptNonce) {
|
|
938
|
-
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
939
|
-
db.transaction(() => {
|
|
940
|
-
const existing = db.prepare(
|
|
941
|
-
"SELECT id FROM credit_transactions WHERE reference_id = ? AND reason = 'remote_earning'"
|
|
942
|
-
).get(receiptNonce);
|
|
943
|
-
if (existing) return;
|
|
944
|
-
db.prepare(
|
|
945
|
-
"INSERT OR IGNORE INTO credit_balances (owner, balance, updated_at) VALUES (?, 0, ?)"
|
|
946
|
-
).run(owner, now);
|
|
947
|
-
db.prepare(
|
|
948
|
-
"UPDATE credit_balances SET balance = balance + ?, updated_at = ? WHERE owner = ?"
|
|
949
|
-
).run(amount, now, owner);
|
|
950
|
-
db.prepare(
|
|
951
|
-
"INSERT INTO credit_transactions (id, owner, amount, reason, reference_id, created_at) VALUES (?, ?, ?, ?, ?, ?)"
|
|
952
|
-
).run(randomUUID3(), owner, amount, "remote_earning", receiptNonce, now);
|
|
953
|
-
})();
|
|
954
|
-
}
|
|
955
|
-
function migrateOwner(db, oldOwner, newOwner) {
|
|
956
|
-
if (oldOwner === newOwner) return;
|
|
957
|
-
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
958
|
-
db.transaction(() => {
|
|
959
|
-
const oldRow = db.prepare("SELECT balance FROM credit_balances WHERE owner = ?").get(oldOwner);
|
|
960
|
-
if (!oldRow) return;
|
|
961
|
-
const newRow = db.prepare("SELECT balance FROM credit_balances WHERE owner = ?").get(newOwner);
|
|
962
|
-
if (newRow) {
|
|
963
|
-
db.prepare("UPDATE credit_balances SET balance = balance + ?, updated_at = ? WHERE owner = ?").run(oldRow.balance, now, newOwner);
|
|
964
|
-
} else {
|
|
965
|
-
db.prepare("UPDATE credit_balances SET owner = ?, updated_at = ? WHERE owner = ?").run(newOwner, now, oldOwner);
|
|
966
|
-
}
|
|
967
|
-
if (newRow) {
|
|
968
|
-
db.prepare("DELETE FROM credit_balances WHERE owner = ?").run(oldOwner);
|
|
969
|
-
}
|
|
970
|
-
db.prepare("UPDATE credit_transactions SET owner = ? WHERE owner = ?").run(newOwner, oldOwner);
|
|
971
|
-
db.prepare("UPDATE credit_escrow SET owner = ? WHERE owner = ?").run(newOwner, oldOwner);
|
|
972
|
-
})();
|
|
973
|
-
}
|
|
974
|
-
|
|
975
|
-
// src/credit/escrow.ts
|
|
976
|
-
import { randomUUID as randomUUID4 } from "crypto";
|
|
977
|
-
var NETWORK_FEE_RATE = 0.05;
|
|
978
|
-
function holdEscrow(db, owner, amount, cardId) {
|
|
979
|
-
const escrowId = randomUUID4();
|
|
980
|
-
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
981
|
-
const hold = db.transaction(() => {
|
|
982
|
-
const voucher = getActiveVoucher(db, owner);
|
|
983
|
-
if (voucher && voucher.remaining >= amount) {
|
|
984
|
-
consumeVoucher(db, voucher.id, amount);
|
|
985
|
-
db.prepare(
|
|
986
|
-
"INSERT INTO credit_escrow (id, owner, amount, card_id, status, created_at, funding_source) VALUES (?, ?, ?, ?, ?, ?, ?)"
|
|
987
|
-
).run(escrowId, owner, amount, cardId, "held", now, "voucher");
|
|
988
|
-
db.prepare(
|
|
989
|
-
"INSERT INTO credit_transactions (id, owner, amount, reason, reference_id, created_at) VALUES (?, ?, ?, ?, ?, ?)"
|
|
990
|
-
).run(randomUUID4(), owner, -amount, "voucher_hold", escrowId, now);
|
|
991
|
-
} else {
|
|
992
|
-
const row = db.prepare("SELECT balance FROM credit_balances WHERE owner = ?").get(owner);
|
|
993
|
-
if (!row || row.balance < amount) {
|
|
994
|
-
throw new AgentBnBError("Insufficient credits", "INSUFFICIENT_CREDITS");
|
|
995
|
-
}
|
|
996
|
-
db.prepare(
|
|
997
|
-
"UPDATE credit_balances SET balance = balance - ?, updated_at = ? WHERE owner = ? AND balance >= ?"
|
|
998
|
-
).run(amount, now, owner, amount);
|
|
999
|
-
db.prepare(
|
|
1000
|
-
"INSERT INTO credit_escrow (id, owner, amount, card_id, status, created_at, funding_source) VALUES (?, ?, ?, ?, ?, ?, ?)"
|
|
1001
|
-
).run(escrowId, owner, amount, cardId, "held", now, "balance");
|
|
1002
|
-
db.prepare(
|
|
1003
|
-
"INSERT INTO credit_transactions (id, owner, amount, reason, reference_id, created_at) VALUES (?, ?, ?, ?, ?, ?)"
|
|
1004
|
-
).run(randomUUID4(), owner, -amount, "escrow_hold", escrowId, now);
|
|
1005
|
-
}
|
|
1006
|
-
});
|
|
1007
|
-
hold();
|
|
1008
|
-
return escrowId;
|
|
1009
|
-
}
|
|
1010
|
-
function settleEscrow(db, escrowId, recipientOwner) {
|
|
1011
|
-
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1012
|
-
const settle = db.transaction(() => {
|
|
1013
|
-
const escrow = db.prepare("SELECT id, owner, amount, status, funding_source FROM credit_escrow WHERE id = ?").get(escrowId);
|
|
1014
|
-
if (!escrow) {
|
|
1015
|
-
throw new AgentBnBError(`Escrow not found: ${escrowId}`, "ESCROW_NOT_FOUND");
|
|
1016
|
-
}
|
|
1017
|
-
if (escrow.status !== "held") {
|
|
1018
|
-
throw new AgentBnBError(
|
|
1019
|
-
`Escrow ${escrowId} is already ${escrow.status}`,
|
|
1020
|
-
"ESCROW_ALREADY_SETTLED"
|
|
1021
|
-
);
|
|
1022
|
-
}
|
|
1023
|
-
const feeAmount = Math.floor(escrow.amount * NETWORK_FEE_RATE);
|
|
1024
|
-
const providerAmount = escrow.amount - feeAmount;
|
|
1025
|
-
db.prepare(
|
|
1026
|
-
"INSERT OR IGNORE INTO credit_balances (owner, balance, updated_at) VALUES (?, 0, ?)"
|
|
1027
|
-
).run(recipientOwner, now);
|
|
1028
|
-
db.prepare(
|
|
1029
|
-
"UPDATE credit_balances SET balance = balance + ?, updated_at = ? WHERE owner = ?"
|
|
1030
|
-
).run(providerAmount, now, recipientOwner);
|
|
1031
|
-
if (feeAmount > 0) {
|
|
1032
|
-
db.prepare(
|
|
1033
|
-
"INSERT OR IGNORE INTO credit_balances (owner, balance, updated_at) VALUES (?, 0, ?)"
|
|
1034
|
-
).run("platform_treasury", now);
|
|
1035
|
-
db.prepare(
|
|
1036
|
-
"UPDATE credit_balances SET balance = balance + ?, updated_at = ? WHERE owner = ?"
|
|
1037
|
-
).run(feeAmount, now, "platform_treasury");
|
|
1038
|
-
db.prepare(
|
|
1039
|
-
"INSERT INTO credit_transactions (id, owner, amount, reason, reference_id, created_at) VALUES (?, ?, ?, ?, ?, ?)"
|
|
1040
|
-
).run(randomUUID4(), "platform_treasury", feeAmount, "network_fee", escrowId, now);
|
|
1041
|
-
}
|
|
1042
|
-
db.prepare(
|
|
1043
|
-
"UPDATE credit_escrow SET status = ?, settled_at = ? WHERE id = ?"
|
|
1044
|
-
).run("settled", now, escrowId);
|
|
1045
|
-
db.prepare(
|
|
1046
|
-
"INSERT INTO credit_transactions (id, owner, amount, reason, reference_id, created_at) VALUES (?, ?, ?, ?, ?, ?)"
|
|
1047
|
-
).run(randomUUID4(), recipientOwner, providerAmount, "settlement", escrowId, now);
|
|
1048
|
-
let providerNum = getProviderNumber(db, recipientOwner);
|
|
1049
|
-
if (providerNum === null) {
|
|
1050
|
-
providerNum = registerProvider(db, recipientOwner);
|
|
1051
|
-
}
|
|
1052
|
-
const bonus = getProviderBonus(providerNum);
|
|
1053
|
-
if (bonus > 1) {
|
|
1054
|
-
const bonusAmount = Math.floor(providerAmount * (bonus - 1));
|
|
1055
|
-
if (bonusAmount > 0) {
|
|
1056
|
-
db.prepare(
|
|
1057
|
-
"INSERT OR IGNORE INTO credit_balances (owner, balance, updated_at) VALUES (?, 0, ?)"
|
|
1058
|
-
).run("platform_treasury", now);
|
|
1059
|
-
db.prepare(
|
|
1060
|
-
"UPDATE credit_balances SET balance = balance + ?, updated_at = ? WHERE owner = ?"
|
|
1061
|
-
).run(bonusAmount, now, recipientOwner);
|
|
1062
|
-
db.prepare(
|
|
1063
|
-
"INSERT INTO credit_transactions (id, owner, amount, reason, reference_id, created_at) VALUES (?, ?, ?, ?, ?, ?)"
|
|
1064
|
-
).run(randomUUID4(), recipientOwner, bonusAmount, "provider_bonus", escrowId, now);
|
|
1065
|
-
}
|
|
1066
|
-
}
|
|
1067
|
-
try {
|
|
1068
|
-
recordSuccessfulHire(db, recipientOwner, escrow.owner);
|
|
1069
|
-
} catch {
|
|
1070
|
-
}
|
|
1071
|
-
});
|
|
1072
|
-
settle();
|
|
1073
|
-
}
|
|
1074
|
-
function releaseEscrow(db, escrowId) {
|
|
1075
|
-
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1076
|
-
const release = db.transaction(() => {
|
|
1077
|
-
const escrow = db.prepare("SELECT id, owner, amount, status, funding_source FROM credit_escrow WHERE id = ?").get(escrowId);
|
|
1078
|
-
if (!escrow) {
|
|
1079
|
-
throw new AgentBnBError(`Escrow not found: ${escrowId}`, "ESCROW_NOT_FOUND");
|
|
1080
|
-
}
|
|
1081
|
-
if (escrow.status !== "held") {
|
|
1082
|
-
throw new AgentBnBError(
|
|
1083
|
-
`Escrow ${escrowId} is already ${escrow.status}`,
|
|
1084
|
-
"ESCROW_ALREADY_SETTLED"
|
|
1085
|
-
);
|
|
1086
|
-
}
|
|
1087
|
-
db.prepare(
|
|
1088
|
-
"UPDATE credit_balances SET balance = balance + ?, updated_at = ? WHERE owner = ?"
|
|
1089
|
-
).run(escrow.amount, now, escrow.owner);
|
|
1090
|
-
db.prepare(
|
|
1091
|
-
"UPDATE credit_escrow SET status = ?, settled_at = ? WHERE id = ?"
|
|
1092
|
-
).run("released", now, escrowId);
|
|
1093
|
-
db.prepare(
|
|
1094
|
-
"INSERT INTO credit_transactions (id, owner, amount, reason, reference_id, created_at) VALUES (?, ?, ?, ?, ?, ?)"
|
|
1095
|
-
).run(randomUUID4(), escrow.owner, escrow.amount, "refund", escrowId, now);
|
|
1096
|
-
});
|
|
1097
|
-
release();
|
|
1098
|
-
}
|
|
1099
|
-
function confirmEscrowDebit(db, escrowId) {
|
|
1100
|
-
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1101
|
-
const confirm = db.transaction(() => {
|
|
1102
|
-
const escrow = db.prepare("SELECT id, owner, amount, status, funding_source FROM credit_escrow WHERE id = ?").get(escrowId);
|
|
1103
|
-
if (!escrow) {
|
|
1104
|
-
throw new AgentBnBError(`Escrow not found: ${escrowId}`, "ESCROW_NOT_FOUND");
|
|
1105
|
-
}
|
|
1106
|
-
if (escrow.status !== "held") {
|
|
1107
|
-
throw new AgentBnBError(
|
|
1108
|
-
`Escrow ${escrowId} is already ${escrow.status}`,
|
|
1109
|
-
"ESCROW_ALREADY_SETTLED"
|
|
1110
|
-
);
|
|
1111
|
-
}
|
|
1112
|
-
db.prepare(
|
|
1113
|
-
"UPDATE credit_escrow SET status = ?, settled_at = ? WHERE id = ?"
|
|
1114
|
-
).run("settled", now, escrowId);
|
|
1115
|
-
db.prepare(
|
|
1116
|
-
"INSERT INTO credit_transactions (id, owner, amount, reason, reference_id, created_at) VALUES (?, ?, ?, ?, ?, ?)"
|
|
1117
|
-
).run(randomUUID4(), escrow.owner, 0, "remote_settlement_confirmed", escrowId, now);
|
|
1118
|
-
});
|
|
1119
|
-
confirm();
|
|
1120
|
-
}
|
|
1121
|
-
|
|
1122
|
-
// src/feedback/reputation.ts
|
|
1123
|
-
var QUALITY_SCORES = {
|
|
1124
|
-
excellent: 1,
|
|
1125
|
-
good: 0.8,
|
|
1126
|
-
acceptable: 0.6,
|
|
1127
|
-
poor: 0.3,
|
|
1128
|
-
failed: 0
|
|
1129
|
-
};
|
|
1130
|
-
var COST_VALUE_SCORES = {
|
|
1131
|
-
great: 1,
|
|
1132
|
-
fair: 0.6,
|
|
1133
|
-
overpriced: 0.2
|
|
1134
|
-
};
|
|
1135
|
-
var DECAY_DAYS = 30;
|
|
1136
|
-
var WEIGHTS = {
|
|
1137
|
-
rating: 0.4,
|
|
1138
|
-
quality: 0.3,
|
|
1139
|
-
would_reuse: 0.2,
|
|
1140
|
-
cost_value: 0.1
|
|
1141
|
-
};
|
|
1142
|
-
function computeReputation(feedbacks) {
|
|
1143
|
-
if (feedbacks.length === 0) return 0.5;
|
|
1144
|
-
const now = Date.now();
|
|
1145
|
-
let weightedSum = 0;
|
|
1146
|
-
let totalWeight = 0;
|
|
1147
|
-
for (const fb of feedbacks) {
|
|
1148
|
-
const feedbackDate = new Date(fb.timestamp).getTime();
|
|
1149
|
-
const ageDays = Math.max(0, (now - feedbackDate) / (1e3 * 60 * 60 * 24));
|
|
1150
|
-
const recencyWeight = Math.exp(-ageDays / DECAY_DAYS);
|
|
1151
|
-
const ratingScore = (fb.rating - 1) / 4;
|
|
1152
|
-
const qualityScore = QUALITY_SCORES[fb.result_quality];
|
|
1153
|
-
const reuseScore = fb.would_reuse ? 1 : 0;
|
|
1154
|
-
const costScore = COST_VALUE_SCORES[fb.cost_value_ratio];
|
|
1155
|
-
const componentScore = WEIGHTS.rating * ratingScore + WEIGHTS.quality * qualityScore + WEIGHTS.would_reuse * reuseScore + WEIGHTS.cost_value * costScore;
|
|
1156
|
-
weightedSum += recencyWeight * componentScore;
|
|
1157
|
-
totalWeight += recencyWeight;
|
|
1158
|
-
}
|
|
1159
|
-
if (totalWeight === 0) return 0.5;
|
|
1160
|
-
const raw = weightedSum / totalWeight;
|
|
1161
|
-
return Math.max(0, Math.min(1, raw));
|
|
1162
|
-
}
|
|
1163
|
-
function getReputationScore(db, agentId) {
|
|
1164
|
-
const feedbacks = getFeedbackForProvider(db, agentId);
|
|
1165
|
-
return computeReputation(feedbacks);
|
|
1166
|
-
}
|
|
1167
|
-
|
|
1168
|
-
// src/registry/matcher.ts
|
|
1169
|
-
var CACHE_MAX_ENTRIES = 100;
|
|
1170
|
-
var CACHE_TTL_MS = 3e4;
|
|
1171
|
-
var dbCaches = /* @__PURE__ */ new WeakMap();
|
|
1172
|
-
function getDbCache(db) {
|
|
1173
|
-
let cache = dbCaches.get(db);
|
|
1174
|
-
if (!cache) {
|
|
1175
|
-
cache = /* @__PURE__ */ new Map();
|
|
1176
|
-
dbCaches.set(db, cache);
|
|
1177
|
-
}
|
|
1178
|
-
return cache;
|
|
1179
|
-
}
|
|
1180
|
-
function cacheKey(query, filters) {
|
|
1181
|
-
return `${query}|${filters.level ?? ""}|${filters.online ?? ""}|${(filters.apis_used ?? []).join(",")}|${filters.min_reputation ?? ""}`;
|
|
1182
|
-
}
|
|
1183
|
-
function evictCache(cache) {
|
|
1184
|
-
const now = Date.now();
|
|
1185
|
-
for (const [key, entry] of cache) {
|
|
1186
|
-
if (entry.expiresAt <= now) cache.delete(key);
|
|
1187
|
-
}
|
|
1188
|
-
while (cache.size > CACHE_MAX_ENTRIES) {
|
|
1189
|
-
const firstKey = cache.keys().next().value;
|
|
1190
|
-
cache.delete(firstKey);
|
|
1191
|
-
}
|
|
1192
|
-
}
|
|
1193
|
-
function searchCards(db, query, filters = {}) {
|
|
1194
|
-
const cache = getDbCache(db);
|
|
1195
|
-
const key = cacheKey(query, filters);
|
|
1196
|
-
const cached = cache.get(key);
|
|
1197
|
-
if (cached && cached.expiresAt > Date.now()) {
|
|
1198
|
-
return cached.results;
|
|
1199
|
-
}
|
|
1200
|
-
const trimmedQuery = query.trim();
|
|
1201
|
-
const exactSkillMatches = findCardsByExactSkillId(db, trimmedQuery, filters);
|
|
1202
|
-
const words = query.trim().split(/\s+/).map((w) => w.replace(/["*^{}():]/g, "")).filter((w) => w.length > 0);
|
|
1203
|
-
if (words.length === 0) {
|
|
1204
|
-
return exactSkillMatches;
|
|
1205
|
-
}
|
|
1206
|
-
const ftsQuery = words.map((w) => `"${w}"`).join(" OR ");
|
|
1207
|
-
const conditions = [];
|
|
1208
|
-
const params = [ftsQuery];
|
|
1209
|
-
if (filters.level !== void 0) {
|
|
1210
|
-
conditions.push(`json_extract(cc.data, '$.level') = ?`);
|
|
1211
|
-
params.push(filters.level);
|
|
1212
|
-
}
|
|
1213
|
-
if (filters.online !== void 0) {
|
|
1214
|
-
conditions.push(`json_extract(cc.data, '$.availability.online') = ?`);
|
|
1215
|
-
params.push(filters.online ? 1 : 0);
|
|
1216
|
-
}
|
|
1217
|
-
const whereClause = conditions.length > 0 ? `AND ${conditions.join(" AND ")}` : "";
|
|
1218
|
-
const sql = `
|
|
1219
|
-
SELECT cc.data
|
|
1220
|
-
FROM capability_cards cc
|
|
1221
|
-
JOIN cards_fts ON cc.rowid = cards_fts.rowid
|
|
1222
|
-
WHERE cards_fts MATCH ?
|
|
1223
|
-
${whereClause}
|
|
1224
|
-
ORDER BY bm25(cards_fts)
|
|
1225
|
-
LIMIT 50
|
|
1226
|
-
`;
|
|
1227
|
-
const stmt = db.prepare(sql);
|
|
1228
|
-
const rows = stmt.all(...params);
|
|
1229
|
-
const results = rows.map((row) => JSON.parse(row.data));
|
|
1230
|
-
const mergedResults = mergeByCardId(exactSkillMatches, results);
|
|
1231
|
-
let filtered = mergedResults;
|
|
1232
|
-
if (filters.apis_used && filters.apis_used.length > 0) {
|
|
1233
|
-
const requiredApis = filters.apis_used;
|
|
1234
|
-
filtered = filtered.filter((card) => {
|
|
1235
|
-
const cardApis = card.metadata?.apis_used ?? [];
|
|
1236
|
-
return requiredApis.every((api) => cardApis.includes(api));
|
|
1237
|
-
});
|
|
1238
|
-
}
|
|
1239
|
-
if (filters.min_reputation !== void 0 && filters.min_reputation > 0) {
|
|
1240
|
-
filtered = applyReputationFilter(db, filtered, filters.min_reputation);
|
|
1241
|
-
}
|
|
1242
|
-
evictCache(cache);
|
|
1243
|
-
cache.set(key, { results: filtered, expiresAt: Date.now() + CACHE_TTL_MS });
|
|
1244
|
-
return filtered;
|
|
1245
|
-
}
|
|
1246
|
-
function mergeByCardId(primary, secondary) {
|
|
1247
|
-
const seen = /* @__PURE__ */ new Set();
|
|
1248
|
-
const merged = [];
|
|
1249
|
-
for (const card of primary) {
|
|
1250
|
-
if (seen.has(card.id)) continue;
|
|
1251
|
-
seen.add(card.id);
|
|
1252
|
-
merged.push(card);
|
|
1253
|
-
}
|
|
1254
|
-
for (const card of secondary) {
|
|
1255
|
-
if (seen.has(card.id)) continue;
|
|
1256
|
-
seen.add(card.id);
|
|
1257
|
-
merged.push(card);
|
|
1258
|
-
}
|
|
1259
|
-
return merged;
|
|
1260
|
-
}
|
|
1261
|
-
function findCardsByExactSkillId(db, query, filters) {
|
|
1262
|
-
if (query.length === 0) return [];
|
|
1263
|
-
const rows = db.prepare("SELECT data FROM capability_cards").all();
|
|
1264
|
-
const cards = rows.map((row) => JSON.parse(row.data));
|
|
1265
|
-
return cards.filter((card) => {
|
|
1266
|
-
if (filters.level !== void 0 && card.level !== filters.level) return false;
|
|
1267
|
-
if (filters.online !== void 0 && card.availability?.online !== filters.online) return false;
|
|
1268
|
-
const asRecord = card;
|
|
1269
|
-
const skills = asRecord["skills"];
|
|
1270
|
-
if (!Array.isArray(skills)) return false;
|
|
1271
|
-
return skills.some((skill) => String(skill["id"] ?? "") === query);
|
|
1272
|
-
});
|
|
1273
|
-
}
|
|
1274
|
-
function filterCards(db, filters) {
|
|
1275
|
-
const conditions = [];
|
|
1276
|
-
const params = [];
|
|
1277
|
-
if (filters.level !== void 0) {
|
|
1278
|
-
conditions.push(`json_extract(data, '$.level') = ?`);
|
|
1279
|
-
params.push(filters.level);
|
|
1280
|
-
}
|
|
1281
|
-
if (filters.online !== void 0) {
|
|
1282
|
-
conditions.push(`json_extract(data, '$.availability.online') = ?`);
|
|
1283
|
-
params.push(filters.online ? 1 : 0);
|
|
1284
|
-
}
|
|
1285
|
-
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
|
|
1286
|
-
const sql = `SELECT data FROM capability_cards ${whereClause}`;
|
|
1287
|
-
const stmt = db.prepare(sql);
|
|
1288
|
-
const rows = stmt.all(...params);
|
|
1289
|
-
let cards = rows.map((row) => JSON.parse(row.data));
|
|
1290
|
-
if (filters.min_reputation !== void 0 && filters.min_reputation > 0) {
|
|
1291
|
-
cards = applyReputationFilter(db, cards, filters.min_reputation);
|
|
1292
|
-
}
|
|
1293
|
-
return cards;
|
|
1294
|
-
}
|
|
1295
|
-
function applyReputationFilter(db, cards, minReputation) {
|
|
1296
|
-
const owners = [...new Set(cards.map((c) => c.owner))];
|
|
1297
|
-
const reputationMap = /* @__PURE__ */ new Map();
|
|
1298
|
-
for (const owner of owners) {
|
|
1299
|
-
reputationMap.set(owner, getReputationScore(db, owner));
|
|
1300
|
-
}
|
|
1301
|
-
return cards.filter((card) => {
|
|
1302
|
-
const score = reputationMap.get(card.owner) ?? 0.5;
|
|
1303
|
-
return score >= minReputation;
|
|
1304
|
-
});
|
|
1305
|
-
}
|
|
1306
|
-
function buildReputationMap(db, owners) {
|
|
1307
|
-
const unique = [...new Set(owners)];
|
|
1308
|
-
const map = /* @__PURE__ */ new Map();
|
|
1309
|
-
for (const owner of unique) {
|
|
1310
|
-
map.set(owner, getReputationScore(db, owner));
|
|
1311
|
-
}
|
|
1312
|
-
return map;
|
|
1313
|
-
}
|
|
1314
|
-
|
|
1315
|
-
// src/cli/remote-registry.ts
|
|
1316
|
-
var RegistryTimeoutError = class extends AgentBnBError {
|
|
1317
|
-
constructor(url) {
|
|
1318
|
-
super(
|
|
1319
|
-
`Registry at ${url} did not respond within 5s. Showing local results only.`,
|
|
1320
|
-
"REGISTRY_TIMEOUT"
|
|
1321
|
-
);
|
|
1322
|
-
this.name = "RegistryTimeoutError";
|
|
1323
|
-
}
|
|
1324
|
-
};
|
|
1325
|
-
var RegistryConnectionError = class extends AgentBnBError {
|
|
1326
|
-
constructor(url) {
|
|
1327
|
-
super(
|
|
1328
|
-
`Cannot reach ${url}. Is the registry running? Showing local results only.`,
|
|
1329
|
-
"REGISTRY_CONNECTION"
|
|
1330
|
-
);
|
|
1331
|
-
this.name = "RegistryConnectionError";
|
|
1332
|
-
}
|
|
1333
|
-
};
|
|
1334
|
-
var RegistryAuthError = class extends AgentBnBError {
|
|
1335
|
-
constructor(url) {
|
|
1336
|
-
super(
|
|
1337
|
-
`Authentication failed for ${url}. Run \`agentbnb config set token <your-token>\`.`,
|
|
1338
|
-
"REGISTRY_AUTH"
|
|
1339
|
-
);
|
|
1340
|
-
this.name = "RegistryAuthError";
|
|
1341
|
-
}
|
|
1342
|
-
};
|
|
1343
|
-
async function fetchRemoteCards(registryUrl, params, timeoutMs = 5e3) {
|
|
1344
|
-
let cardsUrl;
|
|
1345
|
-
try {
|
|
1346
|
-
cardsUrl = new URL("/cards", registryUrl);
|
|
1347
|
-
} catch {
|
|
1348
|
-
throw new AgentBnBError(`Invalid registry URL: ${registryUrl}`, "INVALID_REGISTRY_URL");
|
|
1349
|
-
}
|
|
1350
|
-
const searchParams = new URLSearchParams();
|
|
1351
|
-
if (params.q !== void 0) searchParams.set("q", params.q);
|
|
1352
|
-
if (params.level !== void 0) searchParams.set("level", String(params.level));
|
|
1353
|
-
if (params.online !== void 0) searchParams.set("online", String(params.online));
|
|
1354
|
-
if (params.tag !== void 0) searchParams.set("tag", params.tag);
|
|
1355
|
-
searchParams.set("limit", "100");
|
|
1356
|
-
cardsUrl.search = searchParams.toString();
|
|
1357
|
-
const controller = new AbortController();
|
|
1358
|
-
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
1359
|
-
let response;
|
|
1360
|
-
try {
|
|
1361
|
-
response = await fetch(cardsUrl.toString(), { signal: controller.signal });
|
|
1362
|
-
} catch (err) {
|
|
1363
|
-
clearTimeout(timer);
|
|
1364
|
-
const isTimeout = err instanceof Error && err.name === "AbortError";
|
|
1365
|
-
if (isTimeout) {
|
|
1366
|
-
throw new RegistryTimeoutError(registryUrl);
|
|
1367
|
-
}
|
|
1368
|
-
throw new RegistryConnectionError(registryUrl);
|
|
1369
|
-
} finally {
|
|
1370
|
-
clearTimeout(timer);
|
|
1371
|
-
}
|
|
1372
|
-
if (response.status === 401 || response.status === 403) {
|
|
1373
|
-
throw new RegistryAuthError(registryUrl);
|
|
1374
|
-
}
|
|
1375
|
-
if (!response.ok) {
|
|
1376
|
-
throw new RegistryConnectionError(registryUrl);
|
|
1377
|
-
}
|
|
1378
|
-
const body = await response.json();
|
|
1379
|
-
return body.items;
|
|
1380
|
-
}
|
|
1381
|
-
function mergeResults(localCards, remoteCards, hasQuery) {
|
|
1382
|
-
const taggedLocal = localCards.map((c) => ({ ...c, source: "local" }));
|
|
1383
|
-
const taggedRemote = remoteCards.map((c) => ({ ...c, source: "remote" }));
|
|
1384
|
-
const localIds = new Set(localCards.map((c) => c.id));
|
|
1385
|
-
const dedupedRemote = taggedRemote.filter((c) => !localIds.has(c.id));
|
|
1386
|
-
if (!hasQuery) {
|
|
1387
|
-
return [...taggedLocal, ...dedupedRemote];
|
|
1388
|
-
}
|
|
1389
|
-
const result = [];
|
|
1390
|
-
const maxLen = Math.max(taggedLocal.length, dedupedRemote.length);
|
|
1391
|
-
for (let i = 0; i < maxLen; i++) {
|
|
1392
|
-
if (i < taggedLocal.length) result.push(taggedLocal[i]);
|
|
1393
|
-
if (i < dedupedRemote.length) result.push(dedupedRemote[i]);
|
|
1394
|
-
}
|
|
1395
|
-
return result;
|
|
1396
|
-
}
|
|
1397
|
-
|
|
1398
|
-
// src/gateway/resolve-target-capability.ts
|
|
1399
|
-
function canQueryLocalDb(db) {
|
|
1400
|
-
return Boolean(db) && typeof db.prepare === "function";
|
|
1401
|
-
}
|
|
1402
|
-
function getGatewayUrl(card) {
|
|
1403
|
-
if (typeof card.gateway_url === "string" && card.gateway_url.length > 0) {
|
|
1404
|
-
return card.gateway_url;
|
|
1405
|
-
}
|
|
1406
|
-
const internal = card._internal;
|
|
1407
|
-
const internalGateway = internal?.["gateway_url"];
|
|
1408
|
-
return typeof internalGateway === "string" ? internalGateway : "";
|
|
1409
|
-
}
|
|
1410
|
-
function isOnline(card) {
|
|
1411
|
-
return card.availability?.online !== false;
|
|
1412
|
-
}
|
|
1413
|
-
function scoreSkill(skill, query) {
|
|
1414
|
-
const q = query.toLowerCase();
|
|
1415
|
-
if (skill.id.toLowerCase() === q) return 100;
|
|
1416
|
-
let score = 0;
|
|
1417
|
-
if (skill.id.toLowerCase().includes(q)) score += 40;
|
|
1418
|
-
if (skill.name.toLowerCase().includes(q)) score += 20;
|
|
1419
|
-
if (skill.description.toLowerCase().includes(q)) score += 10;
|
|
1420
|
-
return score;
|
|
1421
|
-
}
|
|
1422
|
-
function pickSkill(card, queryOrId) {
|
|
1423
|
-
const skills = Array.isArray(card.skills) ? card.skills : [];
|
|
1424
|
-
if (skills.length === 0) return void 0;
|
|
1425
|
-
const exact = skills.find((s) => s.id === queryOrId);
|
|
1426
|
-
if (exact) return exact;
|
|
1427
|
-
const scored = skills.map((skill) => ({ skill, score: scoreSkill(skill, queryOrId) })).sort((a, b) => b.score - a.score);
|
|
1428
|
-
if ((scored[0]?.score ?? 0) > 0) return scored[0]?.skill;
|
|
1429
|
-
return skills[0];
|
|
1430
|
-
}
|
|
1431
|
-
function toResolved(card, queryOrId, source) {
|
|
1432
|
-
const skill = pickSkill(card, queryOrId);
|
|
1433
|
-
const gatewayUrl = getGatewayUrl(card);
|
|
1434
|
-
const viaRelay = source === "local" ? false : gatewayUrl.length === 0;
|
|
1435
|
-
const resolvedSource = viaRelay ? "relay" : source;
|
|
1436
|
-
return {
|
|
1437
|
-
cardId: card.id,
|
|
1438
|
-
skillId: skill?.id,
|
|
1439
|
-
owner: card.owner,
|
|
1440
|
-
gateway_url: gatewayUrl,
|
|
1441
|
-
via_relay: viaRelay,
|
|
1442
|
-
credits_per_call: skill?.pricing.credits_per_call ?? card.pricing.credits_per_call,
|
|
1443
|
-
source: resolvedSource
|
|
1444
|
-
};
|
|
1445
|
-
}
|
|
1446
|
-
function findLocalBySkillId(db, skillId, onlineOnly) {
|
|
1447
|
-
const rows = db.prepare("SELECT data FROM capability_cards").all();
|
|
1448
|
-
for (const row of rows) {
|
|
1449
|
-
const card = JSON.parse(row.data);
|
|
1450
|
-
if (onlineOnly && !isOnline(card)) continue;
|
|
1451
|
-
const skills = Array.isArray(card.skills) ? card.skills : [];
|
|
1452
|
-
if (skills.some((s) => s.id === skillId)) {
|
|
1453
|
-
return card;
|
|
1454
|
-
}
|
|
1455
|
-
}
|
|
1456
|
-
return null;
|
|
1457
|
-
}
|
|
1458
|
-
function findRemoteBySkillId(cards, skillId) {
|
|
1459
|
-
for (const card of cards) {
|
|
1460
|
-
const skills = Array.isArray(card.skills) ? card.skills : [];
|
|
1461
|
-
if (skills.some((s) => s.id === skillId)) return card;
|
|
1462
|
-
}
|
|
1463
|
-
return null;
|
|
1464
|
-
}
|
|
1465
|
-
function looksLikeCardId(value) {
|
|
1466
|
-
return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value);
|
|
1467
|
-
}
|
|
1468
|
-
async function resolveTargetCapability(queryOrId, options) {
|
|
1469
|
-
const { registryDb, registryUrl, onlineOnly = true } = options;
|
|
1470
|
-
const needle = queryOrId.trim();
|
|
1471
|
-
if (needle.length === 0) return null;
|
|
1472
|
-
if (canQueryLocalDb(registryDb)) {
|
|
1473
|
-
const byCardId = getCard(registryDb, needle);
|
|
1474
|
-
if (byCardId && (!onlineOnly || isOnline(byCardId))) {
|
|
1475
|
-
return toResolved(byCardId, needle, "local");
|
|
1476
|
-
}
|
|
1477
|
-
const bySkillId = findLocalBySkillId(registryDb, needle, onlineOnly);
|
|
1478
|
-
if (bySkillId) {
|
|
1479
|
-
return toResolved(bySkillId, needle, "local");
|
|
1480
|
-
}
|
|
1481
|
-
const localMatches = searchCards(registryDb, needle, { online: onlineOnly ? true : void 0 });
|
|
1482
|
-
if (localMatches.length > 0) {
|
|
1483
|
-
return toResolved(localMatches[0], needle, "local");
|
|
1484
|
-
}
|
|
1485
|
-
}
|
|
1486
|
-
if (!registryUrl) return null;
|
|
1487
|
-
if (looksLikeCardId(needle)) {
|
|
1488
|
-
try {
|
|
1489
|
-
const cardResp = await fetch(`${registryUrl.replace(/\/$/, "")}/cards/${encodeURIComponent(needle)}`);
|
|
1490
|
-
if (cardResp.ok) {
|
|
1491
|
-
const remoteCard = await cardResp.json();
|
|
1492
|
-
if (!onlineOnly || isOnline(remoteCard)) {
|
|
1493
|
-
return toResolved(remoteCard, needle, "remote");
|
|
1494
|
-
}
|
|
1495
|
-
}
|
|
1496
|
-
} catch {
|
|
1497
|
-
}
|
|
1498
|
-
}
|
|
1499
|
-
try {
|
|
1500
|
-
const remoteMatches = await fetchRemoteCards(registryUrl, {
|
|
1501
|
-
q: needle,
|
|
1502
|
-
...onlineOnly ? { online: true } : {}
|
|
1503
|
-
});
|
|
1504
|
-
if (remoteMatches.length > 0) {
|
|
1505
|
-
const exactSkill = findRemoteBySkillId(remoteMatches, needle);
|
|
1506
|
-
if (exactSkill) return toResolved(exactSkill, needle, "remote");
|
|
1507
|
-
return toResolved(remoteMatches[0], needle, "remote");
|
|
1508
|
-
}
|
|
1509
|
-
} catch {
|
|
1510
|
-
}
|
|
1511
|
-
try {
|
|
1512
|
-
const onlineCards = await fetchRemoteCards(registryUrl, {
|
|
1513
|
-
...onlineOnly ? { online: true } : {}
|
|
1514
|
-
});
|
|
1515
|
-
const exactSkill = findRemoteBySkillId(onlineCards, needle);
|
|
1516
|
-
if (exactSkill) return toResolved(exactSkill, needle, "relay");
|
|
1517
|
-
const tokens = needle.toLowerCase().split(/\s+/).filter((t) => t.length > 0);
|
|
1518
|
-
const fuzzy = onlineCards.find((card) => {
|
|
1519
|
-
const text = [
|
|
1520
|
-
card.name,
|
|
1521
|
-
card.description,
|
|
1522
|
-
...Array.isArray(card.skills) ? card.skills.map((s) => `${s.id} ${s.name} ${s.description}`) : []
|
|
1523
|
-
].join(" ").toLowerCase();
|
|
1524
|
-
return tokens.some((token) => text.includes(token));
|
|
1525
|
-
});
|
|
1526
|
-
if (fuzzy) return toResolved(fuzzy, needle, "relay");
|
|
1527
|
-
} catch {
|
|
1528
|
-
}
|
|
1529
|
-
return null;
|
|
1530
|
-
}
|
|
1531
|
-
|
|
1532
|
-
export {
|
|
1533
|
-
insertRequestLog,
|
|
1534
|
-
getSkillRequestCount,
|
|
1535
|
-
getActivityFeed,
|
|
1536
|
-
getRequestLog,
|
|
1537
|
-
insertFeedback,
|
|
1538
|
-
getFeedbackForSkill,
|
|
1539
|
-
getFeedbackForProvider,
|
|
1540
|
-
insertEvolution,
|
|
1541
|
-
getLatestEvolution,
|
|
1542
|
-
getEvolutionHistory,
|
|
1543
|
-
openDatabase,
|
|
1544
|
-
insertCard,
|
|
1545
|
-
getCard,
|
|
1546
|
-
updateCard,
|
|
1547
|
-
updateReputation,
|
|
1548
|
-
updateSkillAvailability,
|
|
1549
|
-
updateSkillIdleRate,
|
|
1550
|
-
listCards,
|
|
1551
|
-
getCardsByCapabilityType,
|
|
1552
|
-
getCardsBySkillCapability,
|
|
1553
|
-
lookupAgent,
|
|
1554
|
-
openCreditDb,
|
|
1555
|
-
bootstrapAgent,
|
|
1556
|
-
getBalance,
|
|
1557
|
-
getTransactions,
|
|
1558
|
-
recordEarning,
|
|
1559
|
-
migrateOwner,
|
|
1560
|
-
NETWORK_FEE_RATE,
|
|
1561
|
-
holdEscrow,
|
|
1562
|
-
settleEscrow,
|
|
1563
|
-
releaseEscrow,
|
|
1564
|
-
confirmEscrowDebit,
|
|
1565
|
-
computeReputation,
|
|
1566
|
-
searchCards,
|
|
1567
|
-
filterCards,
|
|
1568
|
-
buildReputationMap,
|
|
1569
|
-
fetchRemoteCards,
|
|
1570
|
-
mergeResults,
|
|
1571
|
-
resolveTargetCapability
|
|
1572
|
-
};
|