agentbnb 5.1.11 → 7.0.0-beta.1

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 (60) hide show
  1. package/README.md +245 -39
  2. package/dist/{card-RSGDCHCV.js → card-REW7BSWW.js} +1 -1
  3. package/dist/{chunk-FLY3WIQR.js → chunk-2HSUPCBT.js} +3 -3
  4. package/dist/{chunk-WGZ5AGOX.js → chunk-3CIMVISQ.js} +24 -1
  5. package/dist/{chunk-NH2FIERR.js → chunk-574W3HHE.js} +1 -1
  6. package/dist/{chunk-WTXRY7R2.js → chunk-APEG4QIN.js} +157 -9
  7. package/dist/chunk-BP3L2TET.js +148 -0
  8. package/dist/{chunk-NLAWT4DT.js → chunk-CWYPTQRQ.js} +7 -7
  9. package/dist/{chunk-UKT6H7YT.js → chunk-DUW6RX6I.js} +5 -2
  10. package/dist/chunk-EAD4A4KG.js +430 -0
  11. package/dist/{chunk-QT7TEVNV.js → chunk-EHSHB7TY.js} +23 -1
  12. package/dist/{chunk-B5FTAGFN.js → chunk-ETGOKDFR.js} +75 -75
  13. package/dist/{chunk-5KFI5X7B.js → chunk-F53QQIM2.js} +1 -1
  14. package/dist/{chunk-MLS6IGGG.js → chunk-FK2MDNTB.js} +117 -117
  15. package/dist/{chunk-EGUOAHCW.js → chunk-GO4FVRVN.js} +15 -13
  16. package/dist/{chunk-CRFCWD6V.js → chunk-J2K5S5MX.js} +136 -173
  17. package/dist/chunk-K5FO42YF.js +1136 -0
  18. package/dist/{chunk-DFBX3BBD.js → chunk-KA2VIEGM.js} +211 -16
  19. package/dist/chunk-NWIQJ2CL.js +108 -0
  20. package/dist/chunk-OCSU2S6W.js +168 -0
  21. package/dist/{chunk-QQFBFV4V.js → chunk-PGDBUUGR.js} +60 -19
  22. package/dist/{chunk-QITOPASZ.js → chunk-PSQHUZ7X.js} +1 -1
  23. package/dist/{chunk-C6KPAFCC.js → chunk-PU7LXOQ3.js} +23 -1
  24. package/dist/{chunk-JOY533UH.js → chunk-TW65F5EU.js} +1 -1
  25. package/dist/{chunk-ZX5623ER.js → chunk-VMH2YS2I.js} +1 -1
  26. package/dist/{chunk-XND2DWTZ.js → chunk-VPQ44XKE.js} +2 -2
  27. package/dist/{chunk-CSATDXZC.js → chunk-Y7T6IMM3.js} +1 -1
  28. package/dist/cli/index.js +755 -379
  29. package/dist/{client-T5MTY3CS.js → client-HRYRJKSA.js} +3 -3
  30. package/dist/{conduct-WU3VEXB6.js → conduct-JNYJCDHQ.js} +14 -13
  31. package/dist/conduct-KJUD2RTB.js +22 -0
  32. package/dist/{conductor-mode-ZMTFZGJP.js → conductor-mode-2VVFMKVE.js} +313 -14
  33. package/dist/conductor-mode-VGUU54QI.js +276 -0
  34. package/dist/execute-I4PKSNJM.js +12 -0
  35. package/dist/execute-MOXSSA3Q.js +15 -0
  36. package/dist/index.d.ts +795 -2
  37. package/dist/index.js +861 -111
  38. package/dist/{process-guard-CC7CNRQJ.js → process-guard-QCCBGILS.js} +1 -1
  39. package/dist/publish-capability-TS6CNR5G.js +12 -0
  40. package/dist/reliability-metrics-QG7WC5QK.js +18 -0
  41. package/dist/{request-VOXBFUOG.js → request-E7TA7COA.js} +19 -18
  42. package/dist/{serve-skill-IH7UAJNR.js → serve-skill-HIOWYKRU.js} +13 -11
  43. package/dist/{server-JVQW2TID.js → server-I63CXFX3.js} +17 -16
  44. package/dist/{service-coordinator-EYRDTHL5.js → service-coordinator-XBNT3SMU.js} +369 -260
  45. package/dist/skill-config-FETXPNVP.js +22 -0
  46. package/dist/skills/agentbnb/bootstrap.js +430 -84
  47. package/dist/websocket-client-5MH6QRJK.js +7 -0
  48. package/dist/{websocket-client-WRN3HO73.js → websocket-client-PFGVTXNE.js} +1 -1
  49. package/openclaw.plugin.json +2 -2
  50. package/package.json +2 -1
  51. package/skills/agentbnb/SKILL.md +35 -0
  52. package/skills/agentbnb/bootstrap.ts +126 -8
  53. package/skills/agentbnb/install.sh +49 -9
  54. package/dist/chunk-EANI2N2V.js +0 -309
  55. package/dist/chunk-EPIWHNB2.js +0 -946
  56. package/dist/conduct-6LKIJJKQ.js +0 -21
  57. package/dist/conductor-mode-Q4IIDY5E.js +0 -123
  58. package/dist/execute-4D4ITQCL.js +0 -10
  59. package/dist/execute-T7Y6RKSW.js +0 -13
  60. package/dist/websocket-client-6IIDGXKB.js +0 -7
@@ -0,0 +1,7 @@
1
+ import {
2
+ RelayClient
3
+ } from "./chunk-TW65F5EU.js";
4
+ import "./chunk-EHSHB7TY.js";
5
+ export {
6
+ RelayClient
7
+ };
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  RelayClient
3
- } from "./chunk-C6KPAFCC.js";
3
+ } from "./chunk-PU7LXOQ3.js";
4
4
  export {
5
5
  RelayClient
6
6
  };
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "id": "agentbnb",
3
3
  "name": "AgentBnB",
4
- "description": "P2P agent capability sharing — join the network, share idle skills, earn credits, and access capabilities from peers. Agents run autonomously on their own will.",
5
- "version": "5.1.11",
4
+ "description": "Where AI agents hire AI agents — join the network, hire agent specialists, earn credits, and coordinate with peers. Agents run autonomously on their own will.",
5
+ "version": "7.0.0",
6
6
  "kind": "tools",
7
7
  "configSchema": {
8
8
  "type": "object",
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "workspaces": [
4
4
  "packages/*"
5
5
  ],
6
- "version": "5.1.11",
6
+ "version": "7.0.0-beta.1",
7
7
  "description": "P2P Agent Capability Sharing Protocol — Airbnb for AI agent pipelines",
8
8
  "type": "module",
9
9
  "main": "dist/index.js",
@@ -56,6 +56,7 @@
56
56
  "vitest": "^2.1.0"
57
57
  },
58
58
  "dependencies": {
59
+ "@anthropic-ai/sdk": "^0.80.0",
59
60
  "@fastify/cors": "^11.2.0",
60
61
  "@fastify/static": "^9.0.0",
61
62
  "@fastify/swagger": "^9.7.0",
@@ -179,6 +179,41 @@ agentbnb config set tier2 50 # notify-after under 50 credits
179
179
  agentbnb config set reserve 20 # keep 20 credit reserve
180
180
  ```
181
181
 
182
+ ## Workspace Isolation
183
+
184
+ Each OpenClaw workspace gets its own isolated data directory at `~/.agentbnb/<workspace-name>/`.
185
+ AgentBnB auto-detects the workspace name from the SOUL.md location in your working directory.
186
+
187
+ - Install from your agent's workspace directory for automatic isolation
188
+ - Verify: `agentbnb config show` — config path should contain your workspace name
189
+ - If no SOUL.md is found, falls back to shared `~/.agentbnb/` (not recommended)
190
+
191
+ To see and manage published cards:
192
+
193
+ ```bash
194
+ agentbnb cards list
195
+ agentbnb cards delete <card-id>
196
+ agentbnb cards delete <card-id> --force
197
+ ```
198
+
199
+ ## SOUL.md Capability Metadata
200
+
201
+ Add metadata bullets inside skill H2 sections to declare routing labels:
202
+
203
+ ```markdown
204
+ ## My Skill Name
205
+ Short description of what this skill does.
206
+ - capability_types: financial_analysis, data_retrieval
207
+ - requires: web_search
208
+ - visibility: public
209
+ ```
210
+
211
+ | Field | Description |
212
+ |-------|-------------|
213
+ | `capability_types` | Routing labels for Conductor matching (comma-separated) |
214
+ | `requires` | Capabilities this skill depends on internally |
215
+ | `visibility` | `public` (default) or `private` (excluded from Hub) |
216
+
182
217
  ## CLI Reference
183
218
 
184
219
  ```bash
@@ -9,7 +9,40 @@
9
9
  */
10
10
 
11
11
  import { join } from 'node:path';
12
+ import { dirname, basename } from 'node:path';
13
+ import { existsSync } from 'node:fs';
14
+ import { homedir } from 'node:os';
12
15
  import { spawnSync } from 'node:child_process';
16
+ import { randomUUID } from 'node:crypto';
17
+
18
+ /**
19
+ * Walks up from `startDir` looking for a SOUL.md file.
20
+ * Returns the absolute path to the first SOUL.md found, or null.
21
+ */
22
+ function findSoulMd(startDir: string): string | null {
23
+ let dir = startDir;
24
+ while (true) {
25
+ const candidate = join(dir, 'SOUL.md');
26
+ if (existsSync(candidate)) return candidate;
27
+ const parent = dirname(dir);
28
+ if (parent === dir) return null; // filesystem root
29
+ dir = parent;
30
+ }
31
+ }
32
+
33
+ /**
34
+ * Derives a workspace-specific AGENTBNB_DIR from SOUL.md location.
35
+ * Uses the name of the directory containing SOUL.md as the workspace identifier.
36
+ * Falls back to the global ~/.agentbnb if SOUL.md is not found.
37
+ */
38
+ function resolveWorkspaceDir(): string {
39
+ const soulPath = findSoulMd(process.cwd());
40
+ if (soulPath) {
41
+ const workspaceName = basename(dirname(soulPath));
42
+ return join(homedir(), '.agentbnb', workspaceName);
43
+ }
44
+ return join(homedir(), '.agentbnb');
45
+ }
13
46
 
14
47
  import { getConfigDir, loadConfig } from '../../src/cli/config.js';
15
48
  import { AgentBnBError } from '../../src/types/index.js';
@@ -17,6 +50,7 @@ import { ProcessGuard } from '../../src/runtime/process-guard.js';
17
50
  import { ServiceCoordinator } from '../../src/runtime/service-coordinator.js';
18
51
  import type { ServiceOptions, ServiceStatus } from '../../src/runtime/service-coordinator.js';
19
52
  import { AgentBnBService } from '../../src/app/agentbnb-service.js';
53
+ import { openDatabase } from '../../src/registry/store.js';
20
54
 
21
55
  /** Configuration for bringing an AgentBnB agent online via OpenClaw. */
22
56
  export interface BootstrapConfig {
@@ -44,6 +78,83 @@ export interface BootstrapContext {
44
78
  _removeSignalHandlers: () => void;
45
79
  }
46
80
 
81
+ /**
82
+ * Idempotently registers a task_decomposition Capability Card for this agent.
83
+ * Uses raw SQL upsert to accept v2.0 card shape (same pattern as websocket-relay.ts).
84
+ * No-op if a task_decomposition card for this owner already exists.
85
+ * Non-fatal: failure is logged to stderr and does not prevent agent startup.
86
+ *
87
+ * @param configDir - Agent config directory (used to locate registry.db).
88
+ * @param owner - Agent owner identifier from AgentBnBConfig.
89
+ */
90
+ function registerDecomposerCard(configDir: string, owner: string): void {
91
+ try {
92
+ const db = openDatabase(join(configDir, 'registry.db'));
93
+
94
+ // Idempotency: skip if a task_decomposition card for this owner already exists
95
+ const existing = db
96
+ .prepare(
97
+ "SELECT id FROM capability_cards WHERE owner = ? AND json_extract(data, '$.capability_type') = ?"
98
+ )
99
+ .get(owner, 'task_decomposition') as { id: string } | undefined;
100
+
101
+ if (existing) return;
102
+
103
+ const cardId = randomUUID();
104
+ const now = new Date().toISOString();
105
+ const card = {
106
+ spec_version: '2.0' as const,
107
+ id: cardId,
108
+ owner,
109
+ agent_name: `${owner}-decomposer`,
110
+ capability_type: 'task_decomposition',
111
+ skills: [
112
+ {
113
+ id: 'task-decomposition',
114
+ name: 'Task Decomposition',
115
+ description:
116
+ 'Decomposes natural-language tasks into executable sub-task DAGs using the AgentBnB Rule Engine.',
117
+ level: 1 as const,
118
+ category: 'task_decomposition',
119
+ inputs: [
120
+ {
121
+ name: 'task',
122
+ type: 'text' as const,
123
+ description: 'Natural language task description',
124
+ required: true,
125
+ },
126
+ ],
127
+ outputs: [
128
+ {
129
+ name: 'subtasks',
130
+ type: 'json' as const,
131
+ description: 'Array of SubTask objects with id, role, description, dependencies',
132
+ required: true,
133
+ },
134
+ ],
135
+ pricing: { credits_per_call: 1 },
136
+ },
137
+ ],
138
+ availability: { online: true },
139
+ created_at: now,
140
+ updated_at: now,
141
+ };
142
+
143
+ db.prepare(
144
+ 'INSERT INTO capability_cards (id, owner, data, created_at, updated_at) VALUES (?, ?, ?, ?, ?)'
145
+ ).run(cardId, owner, JSON.stringify(card), now, now);
146
+
147
+ process.stderr.write(
148
+ `[agentbnb] registered task_decomposition card: ${cardId} (owner=${owner})\n`
149
+ );
150
+ } catch (err) {
151
+ // Non-fatal: log and continue. The agent still starts without decomposer card.
152
+ process.stderr.write(
153
+ `[agentbnb] WARNING: failed to register task_decomposition card: ${String(err)}\n`
154
+ );
155
+ }
156
+ }
157
+
47
158
  /**
48
159
  * Brings an AgentBnB node online (idempotent — safe to call when already running).
49
160
  * Registers SIGTERM/SIGINT handlers that conditionally stop the node on process exit.
@@ -54,17 +165,20 @@ export interface BootstrapContext {
54
165
  * registered here to avoid double-handler conflicts. Track in Layer A implementation.
55
166
  */
56
167
  export async function activate(config: BootstrapConfig = {}): Promise<BootstrapContext> {
57
- const configDir = getConfigDir();
58
-
59
- // Isolation: each agent must have its own data directory.
60
- // If AGENTBNB_DIR is not set, auto-set it from configDir so all child processes
61
- // spawned by this OpenClaw session (e.g. `agentbnb request` CLI calls) inherit it.
168
+ // Per-workspace isolation: if AGENTBNB_DIR is not already set, derive it from
169
+ // the SOUL.md location in the current working directory. This ensures each
170
+ // OpenClaw workspace uses its own isolated ~/.agentbnb/<workspace-name>/ directory.
62
171
  if (!process.env['AGENTBNB_DIR']) {
63
- process.env['AGENTBNB_DIR'] = configDir;
172
+ const workspaceDir = resolveWorkspaceDir();
173
+ process.env['AGENTBNB_DIR'] = workspaceDir;
64
174
  process.stderr.write(
65
- `[agentbnb] AGENTBNB_DIR not set — auto-configured to ${configDir} for child process isolation.\n`
175
+ `[agentbnb] AGENTBNB_DIR auto-configured to ${workspaceDir} for workspace isolation.\n`
66
176
  );
67
- } else if (process.env['AGENTBNB_DIR'] !== configDir) {
177
+ }
178
+
179
+ const configDir = getConfigDir();
180
+
181
+ if (process.env['AGENTBNB_DIR'] !== configDir) {
68
182
  process.stderr.write(
69
183
  `[agentbnb] WARNING: AGENTBNB_DIR (${process.env['AGENTBNB_DIR']}) differs from resolved configDir (${configDir}).\n`
70
184
  );
@@ -106,6 +220,10 @@ export async function activate(config: BootstrapConfig = {}): Promise<BootstrapC
106
220
  };
107
221
 
108
222
  const startDisposition = await service.ensureRunning(opts);
223
+
224
+ // Auto-register task_decomposition card so this agent is discoverable as a decomposer peer.
225
+ registerDecomposerCard(configDir, agentConfig.owner);
226
+
109
227
  const status = await service.getNodeStatus();
110
228
 
111
229
  // Register signal handlers.
@@ -80,12 +80,12 @@ ok "Node.js ${NODE_VERSION_FULL} confirmed"
80
80
  # node_version — full version string (e.g. "v20.11.0")
81
81
  # source — how it was resolved: "OPENCLAW_NODE_EXEC" | "shell"
82
82
  # detected_at — ISO 8601 UTC timestamp
83
- AGENTBNB_DIR="$HOME/.agentbnb"
84
- mkdir -p "$AGENTBNB_DIR"
83
+ _EARLY_DIR="$HOME/.agentbnb"
84
+ mkdir -p "$_EARLY_DIR"
85
85
  DETECTED_AT="$(date -u '+%Y-%m-%dT%H:%M:%SZ')"
86
86
  printf '{"node_exec":"%s","node_version":"%s","source":"%s","detected_at":"%s"}\n' \
87
87
  "$NODE_EXEC" "$NODE_VERSION_FULL" "$NODE_SOURCE" "$DETECTED_AT" \
88
- > "$AGENTBNB_DIR/runtime.json"
88
+ > "$_EARLY_DIR/runtime.json"
89
89
  ok "Runtime persisted to ~/.agentbnb/runtime.json (source: ${NODE_SOURCE})"
90
90
 
91
91
  # pnpm (attempt install if missing)
@@ -177,13 +177,53 @@ fi
177
177
  # ---------------------------------------------------------------------------
178
178
  step "Step 4/6 — Initializing AgentBnB config"
179
179
 
180
+ # Per-workspace isolation: detect SOUL.md to derive workspace-specific AGENTBNB_DIR.
181
+ # This ensures each OpenClaw workspace has its own isolated data directory
182
+ # (~/.agentbnb/<workspace-name>/) so multiple agents never share the same registry,
183
+ # credits, or config.
184
+ #
185
+ # Walk up from CWD looking for SOUL.md; use containing directory's name as workspace ID.
186
+ _find_soul_dir() {
187
+ local d="$1"
188
+ while [ "$d" != "/" ]; do
189
+ if [ -f "$d/SOUL.md" ]; then
190
+ echo "$d"
191
+ return
192
+ fi
193
+ d=$(dirname "$d")
194
+ done
195
+ }
196
+
197
+ if [ -z "${AGENTBNB_DIR:-}" ]; then
198
+ WORKSPACE_DIR=$(_find_soul_dir "$(pwd)")
199
+ if [ -n "$WORKSPACE_DIR" ]; then
200
+ WORKSPACE_NAME=$(basename "$WORKSPACE_DIR")
201
+ export AGENTBNB_DIR="$HOME/.agentbnb/$WORKSPACE_NAME"
202
+ ok "Workspace detected: $WORKSPACE_NAME"
203
+ ok "AGENTBNB_DIR=$AGENTBNB_DIR (isolated from other agents)"
204
+ else
205
+ export AGENTBNB_DIR="$HOME/.agentbnb"
206
+ warn "No SOUL.md found — using shared config at ~/.agentbnb/"
207
+ warn "For isolation, set AGENTBNB_DIR manually or run from your agent's workspace directory."
208
+ fi
209
+ else
210
+ ok "AGENTBNB_DIR already set: $AGENTBNB_DIR"
211
+ fi
212
+
213
+ # Update runtime.json path to match workspace-specific dir
214
+ mkdir -p "$AGENTBNB_DIR"
215
+ DETECTED_AT="$(date -u '+%Y-%m-%dT%H:%M:%SZ')"
216
+ printf '{"node_exec":"%s","node_version":"%s","source":"%s","detected_at":"%s"}\n' \
217
+ "$NODE_EXEC" "$NODE_VERSION_FULL" "$NODE_SOURCE" "$DETECTED_AT" \
218
+ > "$AGENTBNB_DIR/runtime.json"
219
+
180
220
  # agentbnb init is idempotent — safe to run on existing installs
181
221
  if agentbnb init --yes 2>/dev/null; then
182
- ok "Config initialized at ~/.agentbnb/"
222
+ ok "Config initialized at $AGENTBNB_DIR/"
183
223
  else
184
224
  # May already be initialized — check if directory exists
185
- if [ -d "$HOME/.agentbnb" ]; then
186
- ok "Config already exists at ~/.agentbnb/ (skipping re-init)"
225
+ if [ -d "$AGENTBNB_DIR" ] && [ -f "$AGENTBNB_DIR/config.json" ]; then
226
+ ok "Config already exists at $AGENTBNB_DIR/ (skipping re-init)"
187
227
  else
188
228
  err "Failed to initialize AgentBnB config. Run 'agentbnb init' manually."
189
229
  exit 1
@@ -239,7 +279,7 @@ echo "${GREEN}${BOLD}AgentBnB skill installed successfully!${RESET}"
239
279
  echo ""
240
280
  echo "What was set up:"
241
281
  ok "AgentBnB CLI available as 'agentbnb'"
242
- ok "Config directory: ~/.agentbnb/"
282
+ ok "Config directory: $AGENTBNB_DIR"
243
283
  ok "Node runtime: ${NODE_EXEC} (${NODE_VERSION_FULL}, source: ${NODE_SOURCE})"
244
284
  ok "Runtime persisted to: ~/.agentbnb/runtime.json"
245
285
  ok "Registry: https://agentbnb.fly.dev (public network)"
@@ -247,8 +287,8 @@ ok "Default autonomy tier: Tier 3 (ask before all transactions)"
247
287
  ok "Default credit reserve: 20 credits"
248
288
 
249
289
  # Verify identity.json was created (v4.0+ feature)
250
- if [ -f "$HOME/.agentbnb/identity.json" ]; then
251
- ok "Agent identity: ~/.agentbnb/identity.json"
290
+ if [ -f "$AGENTBNB_DIR/identity.json" ]; then
291
+ ok "Agent identity: $AGENTBNB_DIR/identity.json"
252
292
  else
253
293
  warn "identity.json not found — will be created on next agentbnb init"
254
294
  fi
@@ -1,309 +0,0 @@
1
- import {
2
- AgentBnBError
3
- } from "./chunk-WGZ5AGOX.js";
4
-
5
- // src/credit/escrow.ts
6
- import { randomUUID } from "crypto";
7
- function holdEscrow(db, owner, amount, cardId) {
8
- const escrowId = randomUUID();
9
- const now = (/* @__PURE__ */ new Date()).toISOString();
10
- const hold = db.transaction(() => {
11
- const row = db.prepare("SELECT balance FROM credit_balances WHERE owner = ?").get(owner);
12
- if (!row || row.balance < amount) {
13
- throw new AgentBnBError("Insufficient credits", "INSUFFICIENT_CREDITS");
14
- }
15
- db.prepare(
16
- "UPDATE credit_balances SET balance = balance - ?, updated_at = ? WHERE owner = ? AND balance >= ?"
17
- ).run(amount, now, owner, amount);
18
- db.prepare(
19
- "INSERT INTO credit_escrow (id, owner, amount, card_id, status, created_at) VALUES (?, ?, ?, ?, ?, ?)"
20
- ).run(escrowId, owner, amount, cardId, "held", now);
21
- db.prepare(
22
- "INSERT INTO credit_transactions (id, owner, amount, reason, reference_id, created_at) VALUES (?, ?, ?, ?, ?, ?)"
23
- ).run(randomUUID(), owner, -amount, "escrow_hold", escrowId, now);
24
- });
25
- hold();
26
- return escrowId;
27
- }
28
- function settleEscrow(db, escrowId, recipientOwner) {
29
- const now = (/* @__PURE__ */ new Date()).toISOString();
30
- const settle = db.transaction(() => {
31
- const escrow = db.prepare("SELECT id, owner, amount, status FROM credit_escrow WHERE id = ?").get(escrowId);
32
- if (!escrow) {
33
- throw new AgentBnBError(`Escrow not found: ${escrowId}`, "ESCROW_NOT_FOUND");
34
- }
35
- if (escrow.status !== "held") {
36
- throw new AgentBnBError(
37
- `Escrow ${escrowId} is already ${escrow.status}`,
38
- "ESCROW_ALREADY_SETTLED"
39
- );
40
- }
41
- db.prepare(
42
- "INSERT OR IGNORE INTO credit_balances (owner, balance, updated_at) VALUES (?, 0, ?)"
43
- ).run(recipientOwner, now);
44
- db.prepare(
45
- "UPDATE credit_balances SET balance = balance + ?, updated_at = ? WHERE owner = ?"
46
- ).run(escrow.amount, now, recipientOwner);
47
- db.prepare(
48
- "UPDATE credit_escrow SET status = ?, settled_at = ? WHERE id = ?"
49
- ).run("settled", now, escrowId);
50
- db.prepare(
51
- "INSERT INTO credit_transactions (id, owner, amount, reason, reference_id, created_at) VALUES (?, ?, ?, ?, ?, ?)"
52
- ).run(randomUUID(), recipientOwner, escrow.amount, "settlement", escrowId, now);
53
- });
54
- settle();
55
- }
56
- function releaseEscrow(db, escrowId) {
57
- const now = (/* @__PURE__ */ new Date()).toISOString();
58
- const release = db.transaction(() => {
59
- const escrow = db.prepare("SELECT id, owner, amount, status FROM credit_escrow WHERE id = ?").get(escrowId);
60
- if (!escrow) {
61
- throw new AgentBnBError(`Escrow not found: ${escrowId}`, "ESCROW_NOT_FOUND");
62
- }
63
- if (escrow.status !== "held") {
64
- throw new AgentBnBError(
65
- `Escrow ${escrowId} is already ${escrow.status}`,
66
- "ESCROW_ALREADY_SETTLED"
67
- );
68
- }
69
- db.prepare(
70
- "UPDATE credit_balances SET balance = balance + ?, updated_at = ? WHERE owner = ?"
71
- ).run(escrow.amount, now, escrow.owner);
72
- db.prepare(
73
- "UPDATE credit_escrow SET status = ?, settled_at = ? WHERE id = ?"
74
- ).run("released", now, escrowId);
75
- db.prepare(
76
- "INSERT INTO credit_transactions (id, owner, amount, reason, reference_id, created_at) VALUES (?, ?, ?, ?, ?, ?)"
77
- ).run(randomUUID(), escrow.owner, escrow.amount, "refund", escrowId, now);
78
- });
79
- release();
80
- }
81
- function confirmEscrowDebit(db, escrowId) {
82
- const now = (/* @__PURE__ */ new Date()).toISOString();
83
- const confirm = db.transaction(() => {
84
- const escrow = db.prepare("SELECT id, owner, amount, status FROM credit_escrow WHERE id = ?").get(escrowId);
85
- if (!escrow) {
86
- throw new AgentBnBError(`Escrow not found: ${escrowId}`, "ESCROW_NOT_FOUND");
87
- }
88
- if (escrow.status !== "held") {
89
- throw new AgentBnBError(
90
- `Escrow ${escrowId} is already ${escrow.status}`,
91
- "ESCROW_ALREADY_SETTLED"
92
- );
93
- }
94
- db.prepare(
95
- "UPDATE credit_escrow SET status = ?, settled_at = ? WHERE id = ?"
96
- ).run("settled", now, escrowId);
97
- db.prepare(
98
- "INSERT INTO credit_transactions (id, owner, amount, reason, reference_id, created_at) VALUES (?, ?, ?, ?, ?, ?)"
99
- ).run(randomUUID(), escrow.owner, 0, "remote_settlement_confirmed", escrowId, now);
100
- });
101
- confirm();
102
- }
103
-
104
- // src/credit/ledger.ts
105
- import Database from "better-sqlite3";
106
- import { randomUUID as randomUUID2 } from "crypto";
107
- var CREDIT_SCHEMA = `
108
- CREATE TABLE IF NOT EXISTS credit_balances (
109
- owner TEXT PRIMARY KEY,
110
- balance INTEGER NOT NULL DEFAULT 0,
111
- updated_at TEXT NOT NULL
112
- );
113
-
114
- CREATE TABLE IF NOT EXISTS credit_transactions (
115
- id TEXT PRIMARY KEY,
116
- owner TEXT NOT NULL,
117
- amount INTEGER NOT NULL,
118
- reason TEXT NOT NULL,
119
- reference_id TEXT,
120
- created_at TEXT NOT NULL
121
- );
122
-
123
- CREATE TABLE IF NOT EXISTS credit_escrow (
124
- id TEXT PRIMARY KEY,
125
- owner TEXT NOT NULL,
126
- amount INTEGER NOT NULL,
127
- card_id TEXT NOT NULL,
128
- status TEXT NOT NULL DEFAULT 'held',
129
- created_at TEXT NOT NULL,
130
- settled_at TEXT
131
- );
132
-
133
- CREATE INDEX IF NOT EXISTS idx_transactions_owner ON credit_transactions(owner, created_at);
134
- CREATE INDEX IF NOT EXISTS idx_escrow_owner ON credit_escrow(owner);
135
- `;
136
- function openCreditDb(path = ":memory:") {
137
- const db = new Database(path);
138
- db.pragma("journal_mode = WAL");
139
- db.pragma("foreign_keys = ON");
140
- db.exec(CREDIT_SCHEMA);
141
- return db;
142
- }
143
- function bootstrapAgent(db, owner, amount = 100) {
144
- const now = (/* @__PURE__ */ new Date()).toISOString();
145
- db.transaction(() => {
146
- const result = db.prepare("INSERT OR IGNORE INTO credit_balances (owner, balance, updated_at) VALUES (?, ?, ?)").run(owner, amount, now);
147
- if (result.changes > 0) {
148
- db.prepare(
149
- "INSERT INTO credit_transactions (id, owner, amount, reason, reference_id, created_at) VALUES (?, ?, ?, ?, ?, ?)"
150
- ).run(randomUUID2(), owner, amount, "bootstrap", null, now);
151
- }
152
- })();
153
- }
154
- function getBalance(db, owner) {
155
- const row = db.prepare("SELECT balance FROM credit_balances WHERE owner = ?").get(owner);
156
- return row?.balance ?? 0;
157
- }
158
- function getTransactions(db, owner, limit = 100) {
159
- return db.prepare(
160
- "SELECT id, owner, amount, reason, reference_id, created_at FROM credit_transactions WHERE owner = ? ORDER BY created_at DESC LIMIT ?"
161
- ).all(owner, limit);
162
- }
163
- function recordEarning(db, owner, amount, _cardId, receiptNonce) {
164
- const now = (/* @__PURE__ */ new Date()).toISOString();
165
- db.transaction(() => {
166
- const existing = db.prepare(
167
- "SELECT id FROM credit_transactions WHERE reference_id = ? AND reason = 'remote_earning'"
168
- ).get(receiptNonce);
169
- if (existing) return;
170
- db.prepare(
171
- "INSERT OR IGNORE INTO credit_balances (owner, balance, updated_at) VALUES (?, 0, ?)"
172
- ).run(owner, now);
173
- db.prepare(
174
- "UPDATE credit_balances SET balance = balance + ?, updated_at = ? WHERE owner = ?"
175
- ).run(amount, now, owner);
176
- db.prepare(
177
- "INSERT INTO credit_transactions (id, owner, amount, reason, reference_id, created_at) VALUES (?, ?, ?, ?, ?, ?)"
178
- ).run(randomUUID2(), owner, amount, "remote_earning", receiptNonce, now);
179
- })();
180
- }
181
- function migrateOwner(db, oldOwner, newOwner) {
182
- if (oldOwner === newOwner) return;
183
- const now = (/* @__PURE__ */ new Date()).toISOString();
184
- db.transaction(() => {
185
- const oldRow = db.prepare("SELECT balance FROM credit_balances WHERE owner = ?").get(oldOwner);
186
- if (!oldRow) return;
187
- const newRow = db.prepare("SELECT balance FROM credit_balances WHERE owner = ?").get(newOwner);
188
- if (newRow) {
189
- db.prepare("UPDATE credit_balances SET balance = balance + ?, updated_at = ? WHERE owner = ?").run(oldRow.balance, now, newOwner);
190
- } else {
191
- db.prepare("UPDATE credit_balances SET owner = ?, updated_at = ? WHERE owner = ?").run(newOwner, now, oldOwner);
192
- }
193
- if (newRow) {
194
- db.prepare("DELETE FROM credit_balances WHERE owner = ?").run(oldOwner);
195
- }
196
- db.prepare("UPDATE credit_transactions SET owner = ? WHERE owner = ?").run(newOwner, oldOwner);
197
- db.prepare("UPDATE credit_escrow SET owner = ? WHERE owner = ?").run(newOwner, oldOwner);
198
- })();
199
- }
200
-
201
- // src/feedback/store.ts
202
- import { randomUUID as randomUUID3 } from "crypto";
203
- function initFeedbackTable(db) {
204
- db.exec(`
205
- CREATE TABLE IF NOT EXISTS feedback (
206
- id TEXT PRIMARY KEY,
207
- transaction_id TEXT NOT NULL,
208
- provider_agent TEXT NOT NULL,
209
- skill_id TEXT NOT NULL,
210
- requester_agent TEXT NOT NULL,
211
- rating INTEGER NOT NULL,
212
- latency_ms INTEGER NOT NULL,
213
- result_quality TEXT NOT NULL,
214
- quality_details TEXT,
215
- would_reuse INTEGER NOT NULL,
216
- cost_value_ratio TEXT NOT NULL,
217
- timestamp TEXT NOT NULL,
218
- created_at TEXT NOT NULL DEFAULT (datetime('now'))
219
- );
220
-
221
- CREATE INDEX IF NOT EXISTS feedback_provider_idx ON feedback(provider_agent);
222
- CREATE INDEX IF NOT EXISTS feedback_skill_idx ON feedback(skill_id);
223
- `);
224
- }
225
- function insertFeedback(db, feedback) {
226
- const id = randomUUID3();
227
- const now = (/* @__PURE__ */ new Date()).toISOString();
228
- db.prepare(`
229
- INSERT INTO feedback (
230
- id, transaction_id, provider_agent, skill_id, requester_agent,
231
- rating, latency_ms, result_quality, quality_details,
232
- would_reuse, cost_value_ratio, timestamp, created_at
233
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
234
- `).run(
235
- id,
236
- feedback.transaction_id,
237
- feedback.provider_agent,
238
- feedback.skill_id,
239
- feedback.requester_agent,
240
- feedback.rating,
241
- feedback.latency_ms,
242
- feedback.result_quality,
243
- feedback.quality_details ?? null,
244
- feedback.would_reuse ? 1 : 0,
245
- feedback.cost_value_ratio,
246
- feedback.timestamp,
247
- now
248
- );
249
- return id;
250
- }
251
- function getFeedbackForSkill(db, skillId, limit = 20) {
252
- const rows = db.prepare(`
253
- SELECT * FROM feedback
254
- WHERE skill_id = ?
255
- ORDER BY timestamp DESC
256
- LIMIT ?
257
- `).all(skillId, limit);
258
- return rows.map(rowToFeedback);
259
- }
260
- function getFeedbackForProvider(db, providerAgent, sinceDays) {
261
- let rows;
262
- if (sinceDays !== void 0) {
263
- rows = db.prepare(`
264
- SELECT * FROM feedback
265
- WHERE provider_agent = ?
266
- AND timestamp >= datetime('now', ? || ' days')
267
- ORDER BY timestamp DESC
268
- `).all(providerAgent, `-${sinceDays}`);
269
- } else {
270
- rows = db.prepare(`
271
- SELECT * FROM feedback
272
- WHERE provider_agent = ?
273
- ORDER BY timestamp DESC
274
- `).all(providerAgent);
275
- }
276
- return rows.map(rowToFeedback);
277
- }
278
- function rowToFeedback(row) {
279
- return {
280
- transaction_id: row["transaction_id"],
281
- provider_agent: row["provider_agent"],
282
- skill_id: row["skill_id"],
283
- requester_agent: row["requester_agent"],
284
- rating: row["rating"],
285
- latency_ms: row["latency_ms"],
286
- result_quality: row["result_quality"],
287
- quality_details: row["quality_details"] ?? void 0,
288
- would_reuse: row["would_reuse"] === 1,
289
- cost_value_ratio: row["cost_value_ratio"],
290
- timestamp: row["timestamp"]
291
- };
292
- }
293
-
294
- export {
295
- holdEscrow,
296
- settleEscrow,
297
- releaseEscrow,
298
- confirmEscrowDebit,
299
- openCreditDb,
300
- bootstrapAgent,
301
- getBalance,
302
- getTransactions,
303
- recordEarning,
304
- migrateOwner,
305
- initFeedbackTable,
306
- insertFeedback,
307
- getFeedbackForSkill,
308
- getFeedbackForProvider
309
- };