agentbnb 4.0.0 → 4.0.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 (36) hide show
  1. package/dist/{card-IE5UV5QX.js → card-4XH4AOTE.js} +11 -4
  2. package/dist/chunk-3MJT4PZG.js +50 -0
  3. package/dist/{conduct-IQYAT6ZU.js → chunk-3UKAVIMC.js} +70 -33
  4. package/dist/chunk-5AH3CMOX.js +62 -0
  5. package/dist/{chunk-UJWYE7VL.js → chunk-6K5WUVF3.js} +28 -111
  6. package/dist/chunk-75OC6E4F.js +33 -0
  7. package/dist/{chunk-QO67IGCW.js → chunk-DVAS2443.js} +1 -1
  8. package/dist/{chunk-XA63SD4T.js → chunk-FNKBHBYK.js} +3 -0
  9. package/dist/{websocket-client-5TIQDYQ4.js → chunk-JOY533UH.js} +38 -4
  10. package/dist/{chunk-RSX4SCPN.js → chunk-KJG2UJV5.js} +3 -3
  11. package/dist/chunk-M3G5NR2Z.js +90 -0
  12. package/dist/{chunk-HEVXCYCY.js → chunk-MQKYGY5I.js} +61 -24
  13. package/dist/chunk-ODBGCCEH.js +358 -0
  14. package/dist/{chunk-CUVIWPQO.js → chunk-Q7HRI666.js} +7 -6
  15. package/dist/chunk-QJEOCKVF.js +148 -0
  16. package/dist/{chunk-3Y36WQDV.js → chunk-QT7TEVNV.js} +14 -2
  17. package/dist/{chunk-UOGDK2S2.js → chunk-TLU7ALCZ.js} +1 -1
  18. package/dist/{chunk-QVV2P3FN.js → chunk-XQHN6ITI.js} +1 -1
  19. package/dist/cli/index.js +2665 -845
  20. package/dist/{client-IOTK6GOS.js → client-BTPIFY7E.js} +3 -3
  21. package/dist/conduct-CW62HBPT.js +52 -0
  22. package/dist/conduct-FXLVGKD5.js +19 -0
  23. package/dist/{conductor-mode-XU7ONJWC.js → conductor-mode-3JS4VWCR.js} +16 -9
  24. package/dist/execute-EXOITLHN.js +10 -0
  25. package/dist/index.d.ts +1005 -916
  26. package/dist/index.js +516 -120
  27. package/dist/{peers-G36URZYB.js → peers-K7FSHPN3.js} +2 -1
  28. package/dist/request-CNZ3XIVX.js +196 -0
  29. package/dist/serve-skill-SUOGUM7N.js +104 -0
  30. package/dist/server-2LWHL24P.js +295 -0
  31. package/dist/types-FGBUZ3QV.js +18 -0
  32. package/dist/websocket-client-6IIDGXKB.js +7 -0
  33. package/package.json +1 -1
  34. package/dist/chunk-BEI5MTNZ.js +0 -91
  35. package/dist/cli/index.d.ts +0 -1
  36. package/dist/execute-GDGBU6DJ.js +0 -10
package/dist/index.d.ts CHANGED
@@ -1874,6 +1874,15 @@ declare function expandEnvVars(value: string): string;
1874
1874
  */
1875
1875
  declare function parseSkillsFile(yamlContent: string): SkillConfig[];
1876
1876
 
1877
+ /**
1878
+ * Progress callback for long-running skill executions.
1879
+ * Called between steps/sub-tasks to indicate forward progress.
1880
+ */
1881
+ type ProgressCallback = (info: {
1882
+ step: number;
1883
+ total: number;
1884
+ message: string;
1885
+ }) => void;
1877
1886
  /**
1878
1887
  * Result returned by SkillExecutor.execute() for every invocation.
1879
1888
  * Always includes timing data regardless of success or failure.
@@ -1900,7 +1909,7 @@ interface ExecutorMode {
1900
1909
  * @param params - The input parameters passed by the caller.
1901
1910
  * @returns A partial ExecutionResult without latency_ms (added by SkillExecutor).
1902
1911
  */
1903
- execute(config: SkillConfig, params: Record<string, unknown>): Promise<Omit<ExecutionResult, 'latency_ms'>>;
1912
+ execute(config: SkillConfig, params: Record<string, unknown>, onProgress?: ProgressCallback): Promise<Omit<ExecutionResult, 'latency_ms'>>;
1904
1913
  }
1905
1914
  /**
1906
1915
  * Central dispatcher that routes skill execution requests to the appropriate
@@ -1933,7 +1942,7 @@ declare class SkillExecutor {
1933
1942
  * @param params - Input parameters for the skill.
1934
1943
  * @returns ExecutionResult including success, result/error, and latency_ms.
1935
1944
  */
1936
- execute(skillId: string, params: Record<string, unknown>): Promise<ExecutionResult>;
1945
+ execute(skillId: string, params: Record<string, unknown>, onProgress?: ProgressCallback): Promise<ExecutionResult>;
1937
1946
  /**
1938
1947
  * Returns the IDs of all registered skills.
1939
1948
  *
@@ -2087,7 +2096,7 @@ declare class PipelineExecutor implements ExecutorMode {
2087
2096
  * @param params - Input parameters from the caller.
2088
2097
  * @returns Partial ExecutionResult (without latency_ms — added by SkillExecutor wrapper).
2089
2098
  */
2090
- execute(config: SkillConfig, params: Record<string, unknown>): Promise<Omit<ExecutionResult, 'latency_ms'>>;
2099
+ execute(config: SkillConfig, params: Record<string, unknown>, onProgress?: ProgressCallback): Promise<Omit<ExecutionResult, 'latency_ms'>>;
2091
2100
  }
2092
2101
 
2093
2102
  /**
@@ -2214,6 +2223,8 @@ interface MatchResult {
2214
2223
  selected_agent: string;
2215
2224
  /** Skill ID on the selected agent's card. */
2216
2225
  selected_skill: string;
2226
+ /** Capability card ID of the selected agent. Used for relay execution of remote agents. */
2227
+ selected_card_id?: string;
2217
2228
  /** Match quality score (0-1). */
2218
2229
  score: number;
2219
2230
  /** Negotiated credit cost. */
@@ -2314,6 +2325,8 @@ interface MatchOptions {
2314
2325
  subtasks: SubTask[];
2315
2326
  /** Owner ID of the conductor agent — excluded from matches (self-exclusion). */
2316
2327
  conductorOwner: string;
2328
+ /** Optional remote registry URL for fallback when local search returns no results. */
2329
+ registryUrl?: string;
2317
2330
  }
2318
2331
  /**
2319
2332
  * Finds the best agent for each sub-task using registry FTS search and peer scoring.
@@ -2329,7 +2342,7 @@ interface MatchOptions {
2329
2342
  * @param opts - Match configuration including database, subtasks, and conductor owner ID.
2330
2343
  * @returns MatchResult[] in the same order as the input subtasks.
2331
2344
  */
2332
- declare function matchSubTasks(opts: MatchOptions): MatchResult[];
2345
+ declare function matchSubTasks(opts: MatchOptions): Promise<MatchResult[]>;
2333
2346
 
2334
2347
  /**
2335
2348
  * Configuration for credit budget enforcement.
@@ -2467,11 +2480,16 @@ declare const CONDUCTOR_OWNER = "agentbnb-conductor";
2467
2480
  * - `orchestrate` (5 cr): Decomposes and executes multi-agent tasks
2468
2481
  * - `plan` (1 cr): Returns an execution plan with cost estimate only
2469
2482
  *
2483
+ * When `owner` is provided, the card is attributed to that agent owner
2484
+ * with a deterministic owner-specific ID. When omitted, uses the default
2485
+ * singleton CONDUCTOR_OWNER and fixed UUID.
2486
+ *
2470
2487
  * The returned card is validated against CapabilityCardV2Schema before return.
2471
2488
  *
2489
+ * @param owner - Optional agent owner. When provided, card is owner-specific.
2472
2490
  * @returns A valid CapabilityCardV2 for the Conductor.
2473
2491
  */
2474
- declare function buildConductorCard(): CapabilityCardV2;
2492
+ declare function buildConductorCard(owner?: string): CapabilityCardV2;
2475
2493
  /**
2476
2494
  * Registers the Conductor card in the given SQLite database.
2477
2495
  *
@@ -2485,719 +2503,199 @@ declare function buildConductorCard(): CapabilityCardV2;
2485
2503
  declare function registerConductorCard(db: Database.Database): CapabilityCardV2;
2486
2504
 
2487
2505
  /**
2488
- * PipelineOrchestrator DAG-based remote execution engine for the Conductor.
2489
- *
2490
- * Executes sub-tasks across remote agents via the Gateway client,
2491
- * respecting dependency ordering (parallel waves for independent tasks),
2492
- * output piping between steps, and retry with alternative agents on failure.
2493
- *
2494
- * Budget checking is NOT done here — the caller (ConductorMode) handles that.
2495
- * This module is pure execution.
2496
- */
2497
-
2498
- /**
2499
- * Options for the orchestrate() function.
2500
- */
2501
- interface OrchestrateOptions {
2502
- /** Ordered list of sub-tasks forming a dependency DAG. */
2503
- subtasks: SubTask[];
2504
- /** Match results keyed by subtask ID. */
2505
- matches: Map<string, MatchResult>;
2506
- /** Bearer token for authenticating with remote agents. */
2507
- gatewayToken: string;
2508
- /** Resolves an agent owner to their gateway URL and card ID. */
2509
- resolveAgentUrl: (agentOwner: string) => {
2510
- url: string;
2511
- cardId: string;
2512
- };
2513
- /** Per-task timeout in milliseconds. Default 30000. */
2514
- timeoutMs?: number;
2515
- /** Maximum budget in credits. If set, aborts remaining tasks when exceeded. */
2516
- maxBudget?: number;
2517
- }
2518
- /**
2519
- * Executes a DAG of sub-tasks across remote agents via Gateway.
2520
- *
2521
- * Execution flow:
2522
- * 1. Computes execution waves from dependency graph
2523
- * 2. For each wave, executes all tasks in parallel via Promise.allSettled
2524
- * 3. Before each task, interpolates params against completed step outputs
2525
- * 4. On failure, retries with the first alternative agent from MatchResult
2526
- * 5. Tracks per-task spending and total credits
2527
- * 6. Optionally enforces a maxBudget ceiling
2528
- *
2529
- * @param opts - Orchestration options.
2530
- * @returns Aggregated orchestration result.
2531
- */
2532
- declare function orchestrate(opts: OrchestrateOptions): Promise<OrchestrationResult>;
2533
-
2534
- /**
2535
- * ConductorMode — ExecutorMode implementation for Conductor skills.
2536
- *
2537
- * Chains TaskDecomposer -> CapabilityMatcher -> BudgetController -> PipelineOrchestrator
2538
- * to execute multi-agent orchestration pipelines via the SkillExecutor dispatch system.
2539
- *
2540
- * Supports two conductor skills:
2541
- * - `orchestrate`: Full pipeline — decompose, match, budget check, execute, return results.
2542
- * - `plan`: Planning only — decompose, match, budget check, return plan without executing.
2543
- */
2544
-
2545
- /**
2546
- * Configuration options for ConductorMode.
2547
- */
2548
- interface ConductorModeOptions {
2549
- /** Registry database for card search (FTS5). */
2550
- db: Database.Database;
2551
- /** Credit database for budget checks. */
2552
- creditDb: Database.Database;
2553
- /** Owner ID of the conductor agent — used for self-exclusion in matching. */
2554
- conductorOwner: string;
2555
- /** Bearer token for authenticating with remote agents. */
2556
- gatewayToken: string;
2557
- /** Resolves an agent owner to their gateway URL and card ID. */
2558
- resolveAgentUrl: (owner: string) => {
2559
- url: string;
2560
- cardId: string;
2561
- };
2562
- /** Maximum budget in credits for orchestration runs. Default 100. */
2563
- maxBudget?: number;
2564
- }
2565
- /**
2566
- * ExecutorMode implementation for Conductor skills ('orchestrate' and 'plan').
2567
- *
2568
- * Dispatches through the full Conductor pipeline:
2569
- * 1. TaskDecomposer breaks the task into SubTasks
2570
- * 2. CapabilityMatcher finds agents for each sub-task
2571
- * 3. BudgetController validates cost against limits
2572
- * 4. PipelineOrchestrator executes the DAG (orchestrate only)
2573
- */
2574
- declare class ConductorMode implements ExecutorMode {
2575
- private readonly db;
2576
- private readonly creditDb;
2577
- private readonly conductorOwner;
2578
- private readonly gatewayToken;
2579
- private readonly resolveAgentUrl;
2580
- private readonly maxBudget;
2581
- constructor(opts: ConductorModeOptions);
2582
- /**
2583
- * Execute a conductor skill with the given config and params.
2584
- *
2585
- * @param config - SkillConfig with type 'conductor' and conductor_skill field.
2586
- * @param params - Must include `task` string.
2587
- * @returns Execution result without latency_ms (added by SkillExecutor).
2588
- */
2589
- execute(config: SkillConfig, params: Record<string, unknown>): Promise<Omit<ExecutionResult, 'latency_ms'>>;
2590
- }
2591
-
2592
- /**
2593
- * Ed25519 keypair as raw DER-encoded Buffers.
2594
- */
2595
- interface KeyPair {
2596
- publicKey: Buffer;
2597
- privateKey: Buffer;
2598
- }
2599
- /**
2600
- * Generates a new Ed25519 keypair.
2601
- * Uses Node.js built-in crypto — no external dependencies.
2602
- *
2603
- * @returns Object with publicKey and privateKey as DER-encoded Buffers.
2604
- */
2605
- declare function generateKeyPair(): KeyPair;
2606
- /**
2607
- * Saves an Ed25519 keypair to disk.
2608
- * Private key is written with mode 0o600 (owner read/write only).
2609
- *
2610
- * @param configDir - Directory to write key files into.
2611
- * @param keys - The keypair to persist.
2612
- */
2613
- declare function saveKeyPair(configDir: string, keys: KeyPair): void;
2614
- /**
2615
- * Loads an Ed25519 keypair from disk.
2616
- *
2617
- * @param configDir - Directory containing private.key and public.key files.
2618
- * @returns The loaded keypair.
2619
- * @throws {AgentBnBError} with code 'KEYPAIR_NOT_FOUND' if either key file is missing.
2620
- */
2621
- declare function loadKeyPair(configDir: string): KeyPair;
2622
- /**
2623
- * Signs escrow receipt data with an Ed25519 private key.
2624
- * Data is serialized to canonical JSON (sorted keys) before signing.
2625
- *
2626
- * @param data - The receipt data to sign (all fields except 'signature').
2627
- * @param privateKey - DER-encoded Ed25519 private key.
2628
- * @returns Base64url-encoded signature string.
2629
- */
2630
- declare function signEscrowReceipt(data: Record<string, unknown>, privateKey: Buffer): string;
2631
- /**
2632
- * Verifies an Ed25519 signature over escrow receipt data.
2633
- * Returns false (does not throw) for invalid signatures or wrong keys.
2634
- *
2635
- * @param data - The receipt data that was signed (all fields except 'signature').
2636
- * @param signature - Base64url-encoded signature string.
2637
- * @param publicKey - DER-encoded Ed25519 public key.
2638
- * @returns true if signature is valid, false otherwise.
2639
- */
2640
- declare function verifyEscrowReceipt(data: Record<string, unknown>, signature: string, publicKey: Buffer): boolean;
2641
-
2642
- /**
2643
- * Zod schema for validating EscrowReceipt objects.
2644
- * Used by providers to validate incoming receipts before verification.
2506
+ * WebSocket relay message types for agent-to-registry communication.
2507
+ * All messages are JSON-encoded with a discriminating `type` field.
2645
2508
  */
2646
- declare const EscrowReceiptSchema: z.ZodObject<{
2647
- requester_owner: z.ZodString;
2648
- requester_public_key: z.ZodString;
2649
- amount: z.ZodNumber;
2509
+ /** Agent → Registry: Register agent and card on connect */
2510
+ declare const RegisterMessageSchema: z.ZodObject<{
2511
+ type: z.ZodLiteral<"register">;
2512
+ owner: z.ZodString;
2513
+ token: z.ZodString;
2514
+ card: z.ZodRecord<z.ZodString, z.ZodUnknown>;
2515
+ cards: z.ZodOptional<z.ZodArray<z.ZodRecord<z.ZodString, z.ZodUnknown>, "many">>;
2516
+ }, "strip", z.ZodTypeAny, {
2517
+ type: "register";
2518
+ owner: string;
2519
+ token: string;
2520
+ card: Record<string, unknown>;
2521
+ cards?: Record<string, unknown>[] | undefined;
2522
+ }, {
2523
+ type: "register";
2524
+ owner: string;
2525
+ token: string;
2526
+ card: Record<string, unknown>;
2527
+ cards?: Record<string, unknown>[] | undefined;
2528
+ }>;
2529
+ /** Registry → Agent: Acknowledge registration */
2530
+ declare const RegisteredMessageSchema: z.ZodObject<{
2531
+ type: z.ZodLiteral<"registered">;
2532
+ agent_id: z.ZodString;
2533
+ }, "strip", z.ZodTypeAny, {
2534
+ type: "registered";
2535
+ agent_id: string;
2536
+ }, {
2537
+ type: "registered";
2538
+ agent_id: string;
2539
+ }>;
2540
+ /** Agent A → Registry: Request relay to another agent */
2541
+ declare const RelayRequestMessageSchema: z.ZodObject<{
2542
+ type: z.ZodLiteral<"relay_request">;
2543
+ id: z.ZodString;
2544
+ target_owner: z.ZodString;
2650
2545
  card_id: z.ZodString;
2651
2546
  skill_id: z.ZodOptional<z.ZodString>;
2652
- timestamp: z.ZodString;
2653
- nonce: z.ZodString;
2654
- signature: z.ZodString;
2547
+ params: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
2548
+ requester: z.ZodOptional<z.ZodString>;
2549
+ escrow_receipt: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
2655
2550
  }, "strip", z.ZodTypeAny, {
2656
- signature: string;
2657
- requester_owner: string;
2658
- requester_public_key: string;
2659
- amount: number;
2551
+ type: "relay_request";
2552
+ params: Record<string, unknown>;
2553
+ id: string;
2660
2554
  card_id: string;
2661
- timestamp: string;
2662
- nonce: string;
2555
+ target_owner: string;
2663
2556
  skill_id?: string | undefined;
2557
+ requester?: string | undefined;
2558
+ escrow_receipt?: Record<string, unknown> | undefined;
2664
2559
  }, {
2665
- signature: string;
2666
- requester_owner: string;
2667
- requester_public_key: string;
2668
- amount: number;
2560
+ type: "relay_request";
2561
+ id: string;
2669
2562
  card_id: string;
2670
- timestamp: string;
2671
- nonce: string;
2563
+ target_owner: string;
2564
+ params?: Record<string, unknown> | undefined;
2672
2565
  skill_id?: string | undefined;
2566
+ requester?: string | undefined;
2567
+ escrow_receipt?: Record<string, unknown> | undefined;
2673
2568
  }>;
2674
- /**
2675
- * Options for creating a signed escrow receipt.
2676
- */
2677
- interface CreateReceiptOpts {
2678
- /** Agent owner identifier (requester). */
2679
- owner: string;
2680
- /** Number of credits to commit. */
2681
- amount: number;
2682
- /** Capability Card ID being requested. */
2683
- cardId: string;
2684
- /** Optional skill ID within the card. */
2685
- skillId?: string;
2686
- }
2687
- /**
2688
- * Creates a signed escrow receipt by atomically holding credits in the local DB
2689
- * and producing a cryptographically signed receipt that can be sent to a provider.
2690
- *
2691
- * This combines local escrow hold + receipt generation from the requester's perspective.
2692
- *
2693
- * @param db - The credit database instance.
2694
- * @param privateKey - DER-encoded Ed25519 private key for signing.
2695
- * @param publicKey - DER-encoded Ed25519 public key (included in receipt for verification).
2696
- * @param opts - Receipt creation options (owner, amount, cardId, skillId).
2697
- * @returns Object with escrowId (local reference) and signed receipt (for transmission).
2698
- * @throws {AgentBnBError} with code 'INSUFFICIENT_CREDITS' if balance is too low.
2699
- */
2700
- declare function createSignedEscrowReceipt(db: Database.Database, privateKey: Buffer, publicKey: Buffer, opts: CreateReceiptOpts): {
2701
- escrowId: string;
2702
- receipt: EscrowReceipt;
2703
- };
2704
-
2705
- /**
2706
- * Provider-side settlement: records earnings from a signed escrow receipt.
2707
- * The provider calls this after successfully executing a capability.
2708
- * Credits are recorded in the provider's own local DB.
2709
- *
2710
- * @param providerDb - The provider's local credit database.
2711
- * @param providerOwner - Provider agent identifier.
2712
- * @param receipt - The signed escrow receipt from the requester.
2713
- * @returns Object indicating settlement success.
2714
- */
2715
- declare function settleProviderEarning(providerDb: Database.Database, providerOwner: string, receipt: EscrowReceipt): {
2716
- settled: true;
2717
- };
2718
- /**
2719
- * Requester-side settlement: confirms that the escrow debit is permanent.
2720
- * Called after the requester receives confirmation that the provider
2721
- * successfully executed the capability. Marks escrow as 'settled' without
2722
- * crediting anyone (credits stay deducted from requester).
2723
- *
2724
- * @param requesterDb - The requester's local credit database.
2725
- * @param escrowId - The escrow ID to confirm as settled.
2726
- */
2727
- declare function settleRequesterEscrow(requesterDb: Database.Database, escrowId: string): void;
2728
- /**
2729
- * Requester-side failure handling: releases escrowed credits (refund).
2730
- * Called when the capability execution fails and the requester needs
2731
- * their credits back.
2732
- *
2733
- * @param requesterDb - The requester's local credit database.
2734
- * @param escrowId - The escrow ID to release.
2735
- */
2736
- declare function releaseRequesterEscrow(requesterDb: Database.Database, escrowId: string): void;
2737
-
2738
- /**
2739
- * Agent Identity — the unified identity record for an AgentBnB agent.
2740
- * Stored at ~/.agentbnb/identity.json.
2741
- */
2742
- declare const AgentIdentitySchema: z.ZodObject<{
2743
- /** Deterministic ID derived from public key: sha256(hex).slice(0, 16). */
2744
- agent_id: z.ZodString;
2745
- /** Human-readable owner name (from config or init). */
2746
- owner: z.ZodString;
2747
- /** Hex-encoded Ed25519 public key. */
2748
- public_key: z.ZodString;
2749
- /** ISO 8601 timestamp of identity creation. */
2750
- created_at: z.ZodString;
2751
- /** Optional guarantor info if linked to a human. */
2752
- guarantor: z.ZodOptional<z.ZodObject<{
2753
- github_login: z.ZodString;
2754
- verified_at: z.ZodString;
2569
+ /** Registry → Agent B: Incoming request forwarded from Agent A */
2570
+ declare const IncomingRequestMessageSchema: z.ZodObject<{
2571
+ type: z.ZodLiteral<"incoming_request">;
2572
+ id: z.ZodString;
2573
+ from_owner: z.ZodString;
2574
+ card_id: z.ZodString;
2575
+ skill_id: z.ZodOptional<z.ZodString>;
2576
+ params: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
2577
+ requester: z.ZodOptional<z.ZodString>;
2578
+ escrow_receipt: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
2579
+ }, "strip", z.ZodTypeAny, {
2580
+ type: "incoming_request";
2581
+ params: Record<string, unknown>;
2582
+ id: string;
2583
+ card_id: string;
2584
+ from_owner: string;
2585
+ skill_id?: string | undefined;
2586
+ requester?: string | undefined;
2587
+ escrow_receipt?: Record<string, unknown> | undefined;
2588
+ }, {
2589
+ type: "incoming_request";
2590
+ id: string;
2591
+ card_id: string;
2592
+ from_owner: string;
2593
+ params?: Record<string, unknown> | undefined;
2594
+ skill_id?: string | undefined;
2595
+ requester?: string | undefined;
2596
+ escrow_receipt?: Record<string, unknown> | undefined;
2597
+ }>;
2598
+ /** Agent B → Registry: Response to a relayed request */
2599
+ declare const RelayResponseMessageSchema: z.ZodObject<{
2600
+ type: z.ZodLiteral<"relay_response">;
2601
+ id: z.ZodString;
2602
+ result: z.ZodOptional<z.ZodUnknown>;
2603
+ error: z.ZodOptional<z.ZodObject<{
2604
+ code: z.ZodNumber;
2605
+ message: z.ZodString;
2755
2606
  }, "strip", z.ZodTypeAny, {
2756
- github_login: string;
2757
- verified_at: string;
2607
+ code: number;
2608
+ message: string;
2758
2609
  }, {
2759
- github_login: string;
2760
- verified_at: string;
2610
+ code: number;
2611
+ message: string;
2761
2612
  }>>;
2762
2613
  }, "strip", z.ZodTypeAny, {
2763
- owner: string;
2764
- created_at: string;
2765
- agent_id: string;
2766
- public_key: string;
2767
- guarantor?: {
2768
- github_login: string;
2769
- verified_at: string;
2614
+ type: "relay_response";
2615
+ id: string;
2616
+ result?: unknown;
2617
+ error?: {
2618
+ code: number;
2619
+ message: string;
2770
2620
  } | undefined;
2771
2621
  }, {
2772
- owner: string;
2773
- created_at: string;
2774
- agent_id: string;
2775
- public_key: string;
2776
- guarantor?: {
2777
- github_login: string;
2778
- verified_at: string;
2622
+ type: "relay_response";
2623
+ id: string;
2624
+ result?: unknown;
2625
+ error?: {
2626
+ code: number;
2627
+ message: string;
2779
2628
  } | undefined;
2780
2629
  }>;
2781
- type AgentIdentity = z.infer<typeof AgentIdentitySchema>;
2782
- /**
2783
- * Agent Certificate — a self-signed attestation of agent identity.
2784
- * Used for P2P identity verification without a shared auth server.
2785
- */
2786
- declare const AgentCertificateSchema: z.ZodObject<{
2787
- identity: z.ZodObject<{
2788
- /** Deterministic ID derived from public key: sha256(hex).slice(0, 16). */
2789
- agent_id: z.ZodString;
2790
- /** Human-readable owner name (from config or init). */
2791
- owner: z.ZodString;
2792
- /** Hex-encoded Ed25519 public key. */
2793
- public_key: z.ZodString;
2794
- /** ISO 8601 timestamp of identity creation. */
2795
- created_at: z.ZodString;
2796
- /** Optional guarantor info if linked to a human. */
2797
- guarantor: z.ZodOptional<z.ZodObject<{
2798
- github_login: z.ZodString;
2799
- verified_at: z.ZodString;
2800
- }, "strip", z.ZodTypeAny, {
2801
- github_login: string;
2802
- verified_at: string;
2803
- }, {
2804
- github_login: string;
2805
- verified_at: string;
2806
- }>>;
2630
+ /** Registry Agent A: Forwarded response from Agent B */
2631
+ declare const ResponseMessageSchema: z.ZodObject<{
2632
+ type: z.ZodLiteral<"response">;
2633
+ id: z.ZodString;
2634
+ result: z.ZodOptional<z.ZodUnknown>;
2635
+ error: z.ZodOptional<z.ZodObject<{
2636
+ code: z.ZodNumber;
2637
+ message: z.ZodString;
2807
2638
  }, "strip", z.ZodTypeAny, {
2808
- owner: string;
2809
- created_at: string;
2810
- agent_id: string;
2811
- public_key: string;
2812
- guarantor?: {
2813
- github_login: string;
2814
- verified_at: string;
2815
- } | undefined;
2639
+ code: number;
2640
+ message: string;
2816
2641
  }, {
2817
- owner: string;
2818
- created_at: string;
2819
- agent_id: string;
2820
- public_key: string;
2821
- guarantor?: {
2822
- github_login: string;
2823
- verified_at: string;
2824
- } | undefined;
2825
- }>;
2826
- /** ISO 8601 timestamp of certificate issuance. */
2827
- issued_at: z.ZodString;
2828
- /** ISO 8601 timestamp of certificate expiry. */
2829
- expires_at: z.ZodString;
2830
- /** Hex-encoded public key of the issuer (same as identity for self-signed). */
2831
- issuer_public_key: z.ZodString;
2832
- /** Base64url Ed25519 signature over { identity, issued_at, expires_at, issuer_public_key }. */
2833
- signature: z.ZodString;
2642
+ code: number;
2643
+ message: string;
2644
+ }>>;
2834
2645
  }, "strip", z.ZodTypeAny, {
2835
- signature: string;
2836
- identity: {
2837
- owner: string;
2838
- created_at: string;
2839
- agent_id: string;
2840
- public_key: string;
2841
- guarantor?: {
2842
- github_login: string;
2843
- verified_at: string;
2844
- } | undefined;
2845
- };
2846
- issued_at: string;
2847
- expires_at: string;
2848
- issuer_public_key: string;
2646
+ type: "response";
2647
+ id: string;
2648
+ result?: unknown;
2649
+ error?: {
2650
+ code: number;
2651
+ message: string;
2652
+ } | undefined;
2849
2653
  }, {
2850
- signature: string;
2851
- identity: {
2852
- owner: string;
2853
- created_at: string;
2854
- agent_id: string;
2855
- public_key: string;
2856
- guarantor?: {
2857
- github_login: string;
2858
- verified_at: string;
2859
- } | undefined;
2860
- };
2861
- issued_at: string;
2862
- expires_at: string;
2863
- issuer_public_key: string;
2654
+ type: "response";
2655
+ id: string;
2656
+ result?: unknown;
2657
+ error?: {
2658
+ code: number;
2659
+ message: string;
2660
+ } | undefined;
2864
2661
  }>;
2865
- type AgentCertificate = z.infer<typeof AgentCertificateSchema>;
2866
- /**
2867
- * Derives a deterministic agent_id from a hex-encoded public key.
2868
- * Uses first 16 chars of SHA-256 hash.
2869
- */
2870
- declare function deriveAgentId(publicKeyHex: string): string;
2871
- /**
2872
- * Creates a new agent identity. Generates an Ed25519 keypair if one does not
2873
- * already exist. Writes identity.json to the config directory.
2874
- *
2875
- * @param configDir - Directory to write identity.json into (e.g. ~/.agentbnb).
2876
- * @param owner - Human-readable agent owner name.
2877
- * @returns The newly created AgentIdentity.
2878
- */
2879
- declare function createIdentity(configDir: string, owner: string): AgentIdentity;
2880
- /**
2881
- * Loads an existing agent identity from disk.
2882
- *
2883
- * @param configDir - Directory containing identity.json.
2884
- * @returns Parsed AgentIdentity or null if file does not exist.
2885
- */
2886
- declare function loadIdentity(configDir: string): AgentIdentity | null;
2887
- /**
2888
- * Persists an agent identity to disk.
2889
- *
2890
- * @param configDir - Directory to write identity.json into.
2891
- * @param identity - The identity to save.
2892
- */
2893
- declare function saveIdentity(configDir: string, identity: AgentIdentity): void;
2894
- /**
2895
- * Issues a self-signed Agent Certificate. Valid for 365 days.
2896
- *
2897
- * @param identity - The agent identity to certify.
2898
- * @param privateKey - DER-encoded Ed25519 private key.
2899
- * @returns A signed AgentCertificate.
2900
- */
2901
- declare function issueAgentCertificate(identity: AgentIdentity, privateKey: Buffer): AgentCertificate;
2902
- /**
2903
- * Verifies an Agent Certificate's signature and expiry.
2904
- *
2905
- * @param cert - The certificate to verify.
2906
- * @returns true if signature is valid and certificate has not expired.
2907
- */
2908
- declare function verifyAgentCertificate(cert: AgentCertificate): boolean;
2909
- /**
2910
- * Ensures an identity exists for the given config directory.
2911
- * If identity.json already exists, returns it. Otherwise creates a new one.
2912
- *
2913
- * @param configDir - Config directory path.
2914
- * @param owner - Owner name to use if creating new identity.
2915
- * @returns The loaded or newly created AgentIdentity.
2916
- */
2917
- declare function ensureIdentity(configDir: string, owner: string): AgentIdentity;
2918
-
2919
- /**
2920
- * Options for constructing an AgentBnBConsumer.
2921
- */
2922
- interface ConsumerOptions {
2923
- /** Override the config directory (default: ~/.agentbnb or AGENTBNB_DIR). */
2924
- configDir?: string;
2925
- }
2926
- /**
2927
- * Options for requesting a capability.
2928
- */
2929
- interface ConsumerRequestOptions {
2930
- /** Gateway URL of the target agent. */
2931
- gatewayUrl: string;
2932
- /** Bearer token for the target agent's gateway. */
2933
- token: string;
2934
- /** Capability Card ID to execute. */
2935
- cardId: string;
2936
- /** Optional skill ID within the card. */
2937
- skillId?: string;
2938
- /** Input parameters for the capability. */
2939
- params?: Record<string, unknown>;
2940
- /** Credit amount to commit (escrow). */
2941
- credits: number;
2942
- /** Timeout in milliseconds. Default 30000. */
2943
- timeoutMs?: number;
2944
- }
2945
- /**
2946
- * AgentBnBConsumer — high-level SDK class for agents consuming capabilities.
2947
- *
2948
- * Encapsulates the full request lifecycle: identity loading, escrow creation,
2949
- * capability request, and settlement/release.
2950
- *
2951
- * @example
2952
- * ```typescript
2953
- * const consumer = new AgentBnBConsumer();
2954
- * consumer.authenticate();
2955
- * const result = await consumer.request({
2956
- * gatewayUrl: 'http://peer:7700',
2957
- * token: 'peer-token',
2958
- * cardId: 'uuid-of-card',
2959
- * credits: 5,
2960
- * });
2961
- * ```
2962
- */
2963
- declare class AgentBnBConsumer {
2964
- private configDir;
2965
- private identity;
2966
- private keys;
2967
- private creditDb;
2968
- constructor(opts?: ConsumerOptions);
2969
- /**
2970
- * Loads agent identity and keypair from disk.
2971
- * Creates identity if none exists (uses owner from config.json or generates one).
2972
- *
2973
- * @returns The loaded AgentIdentity.
2974
- * @throws {AgentBnBError} if keypair is missing and cannot be created.
2975
- */
2976
- authenticate(): AgentIdentity;
2977
- /**
2978
- * Returns the cached identity. Throws if not yet authenticated.
2979
- */
2980
- getIdentity(): AgentIdentity;
2981
- /**
2982
- * Requests a capability from a remote agent with full escrow lifecycle.
2983
- *
2984
- * 1. Creates a signed escrow receipt (holds credits locally)
2985
- * 2. Sends the request to the target gateway
2986
- * 3. Settles escrow on success, releases on failure
2987
- *
2988
- * @param opts - Request options including target, card, credits, and params.
2989
- * @returns The result from the capability execution.
2990
- * @throws {AgentBnBError} on insufficient credits, network error, or RPC error.
2991
- */
2992
- request(opts: ConsumerRequestOptions): Promise<unknown>;
2993
- /**
2994
- * Returns the current credit balance for this agent.
2995
- */
2996
- getBalance(): number;
2997
- /**
2998
- * Returns basic reputation data from the local credit database.
2999
- * Note: success_rate is computed from local request history only.
3000
- */
3001
- getReputation(): {
3002
- success_rate: number;
3003
- total_requests: number;
3004
- };
3005
- /**
3006
- * Closes the credit database connection. Call when done.
3007
- */
3008
- close(): void;
3009
- /** Lazily opens and caches the credit database. */
3010
- private getCreditDb;
3011
- }
3012
-
3013
- /**
3014
- * Options for constructing an AgentBnBProvider.
3015
- */
3016
- interface ProviderOptions {
3017
- /** Override the config directory (default: ~/.agentbnb or AGENTBNB_DIR). */
3018
- configDir?: string;
3019
- }
3020
- /**
3021
- * Options for starting the sharing gateway.
3022
- */
3023
- interface StartSharingOptions {
3024
- /** Port to listen on (default: from config or 7700). */
3025
- port?: number;
3026
- /** Host to bind to (default: '0.0.0.0'). */
3027
- host?: string;
3028
- }
3029
- /**
3030
- * Context returned after sharing starts.
3031
- */
3032
- interface SharingContext {
3033
- /** The Fastify gateway server instance. */
3034
- gateway: FastifyInstance;
3035
- /** Port the gateway is listening on. */
3036
- port: number;
3037
- }
3038
- /**
3039
- * AgentBnBProvider — high-level SDK class for agents providing capabilities.
3040
- *
3041
- * Manages identity, gateway lifecycle, and capability listing.
3042
- *
3043
- * @example
3044
- * ```typescript
3045
- * const provider = new AgentBnBProvider();
3046
- * provider.authenticate();
3047
- * const ctx = await provider.startSharing({ port: 7700 });
3048
- * console.log(provider.listCapabilities());
3049
- * await provider.stopSharing();
3050
- * ```
3051
- */
3052
- declare class AgentBnBProvider {
3053
- private configDir;
3054
- private identity;
3055
- private registryDb;
3056
- private creditDb;
3057
- private gateway;
3058
- constructor(opts?: ProviderOptions);
3059
- /**
3060
- * Loads agent identity from disk.
3061
- * Creates identity if none exists.
3062
- *
3063
- * @returns The loaded AgentIdentity.
3064
- */
3065
- authenticate(): AgentIdentity;
3066
- /**
3067
- * Returns the cached identity. Throws if not yet authenticated.
3068
- */
3069
- getIdentity(): AgentIdentity;
3070
- /**
3071
- * Starts the gateway server to share capabilities.
3072
- *
3073
- * @param opts - Optional port and host configuration.
3074
- * @returns Context with the gateway server and port.
3075
- */
3076
- startSharing(opts?: StartSharingOptions): Promise<SharingContext>;
3077
- /**
3078
- * Stops the gateway server.
3079
- */
3080
- stopSharing(): Promise<void>;
3081
- /**
3082
- * Returns all capability cards owned by this agent.
3083
- */
3084
- listCapabilities(): CapabilityCard[];
3085
- /**
3086
- * Returns the current credit balance for this agent.
3087
- */
3088
- getBalance(): number;
3089
- /**
3090
- * Closes all database connections and stops the gateway. Call when done.
3091
- */
3092
- close(): Promise<void>;
3093
- /** Lazily opens and caches the registry database. */
3094
- private getRegistryDb;
3095
- /** Lazily opens and caches the credit database. */
3096
- private getCreditDb;
3097
- }
3098
-
3099
- /** Maximum agents a single human guarantor can back. */
3100
- declare const MAX_AGENTS_PER_GUARANTOR = 10;
3101
- /** Free credits granted per human guarantor registration. */
3102
- declare const GUARANTOR_CREDIT_POOL = 50;
3103
- /**
3104
- * A Human Guarantor — a real person backing one or more agents.
3105
- * Provides initial trust and credit pool for the agent network.
3106
- */
3107
- declare const GuarantorRecordSchema: z.ZodObject<{
3108
- id: z.ZodString;
3109
- github_login: z.ZodString;
3110
- agent_count: z.ZodNumber;
3111
- credit_pool: z.ZodNumber;
3112
- created_at: z.ZodString;
3113
- }, "strip", z.ZodTypeAny, {
3114
- id: string;
3115
- created_at: string;
3116
- github_login: string;
3117
- agent_count: number;
3118
- credit_pool: number;
3119
- }, {
3120
- id: string;
3121
- created_at: string;
3122
- github_login: string;
3123
- agent_count: number;
3124
- credit_pool: number;
3125
- }>;
3126
- type GuarantorRecord = z.infer<typeof GuarantorRecordSchema>;
3127
- /**
3128
- * Registers a new human guarantor via GitHub login.
3129
- * Grants GUARANTOR_CREDIT_POOL (50) credits to be distributed among linked agents.
3130
- *
3131
- * @param db - The credit database instance.
3132
- * @param githubLogin - GitHub username of the guarantor.
3133
- * @returns The created GuarantorRecord.
3134
- * @throws {AgentBnBError} with code 'GUARANTOR_EXISTS' if login already registered.
3135
- */
3136
- declare function registerGuarantor(db: Database.Database, githubLogin: string): GuarantorRecord;
3137
- /**
3138
- * Links an agent to a human guarantor.
3139
- * Enforces the MAX_AGENTS_PER_GUARANTOR limit (10).
3140
- *
3141
- * @param db - The credit database instance.
3142
- * @param agentId - The agent_id to link.
3143
- * @param githubLogin - The guarantor's GitHub login.
3144
- * @returns Updated GuarantorRecord.
3145
- * @throws {AgentBnBError} with code 'GUARANTOR_NOT_FOUND' if login not registered.
3146
- * @throws {AgentBnBError} with code 'MAX_AGENTS_EXCEEDED' if limit reached.
3147
- * @throws {AgentBnBError} with code 'AGENT_ALREADY_LINKED' if agent already has a guarantor.
3148
- */
3149
- declare function linkAgentToGuarantor(db: Database.Database, agentId: string, githubLogin: string): GuarantorRecord;
3150
- /**
3151
- * Retrieves a guarantor record by GitHub login.
3152
- *
3153
- * @param db - The credit database instance.
3154
- * @param githubLogin - The GitHub username to look up.
3155
- * @returns GuarantorRecord or null if not found.
3156
- */
3157
- declare function getGuarantor(db: Database.Database, githubLogin: string): GuarantorRecord | null;
3158
- /**
3159
- * Gets the guarantor linked to an agent, if any.
3160
- *
3161
- * @param db - The credit database instance.
3162
- * @param agentId - The agent_id to look up.
3163
- * @returns GuarantorRecord or null if agent has no guarantor.
3164
- */
3165
- declare function getAgentGuarantor(db: Database.Database, agentId: string): GuarantorRecord | null;
3166
- /**
3167
- * Initiates a GitHub OAuth flow for guarantor verification.
3168
- * This is a STUB — returns placeholder values. Actual OAuth implementation
3169
- * is deferred to a future version.
3170
- *
3171
- * @returns Object with auth_url and state for the OAuth flow.
3172
- */
3173
- declare function initiateGithubAuth(): {
3174
- auth_url: string;
3175
- state: string;
3176
- };
3177
-
3178
- /**
3179
- * WebSocket relay message types for agent-to-registry communication.
3180
- * All messages are JSON-encoded with a discriminating `type` field.
3181
- */
3182
- /** Agent → Registry: Register agent and card on connect */
3183
- declare const RegisterMessageSchema: z.ZodObject<{
2662
+ /** Error message (either direction) */
2663
+ declare const ErrorMessageSchema: z.ZodObject<{
2664
+ type: z.ZodLiteral<"error">;
2665
+ code: z.ZodString;
2666
+ message: z.ZodString;
2667
+ request_id: z.ZodOptional<z.ZodString>;
2668
+ }, "strip", z.ZodTypeAny, {
2669
+ type: "error";
2670
+ code: string;
2671
+ message: string;
2672
+ request_id?: string | undefined;
2673
+ }, {
2674
+ type: "error";
2675
+ code: string;
2676
+ message: string;
2677
+ request_id?: string | undefined;
2678
+ }>;
2679
+ /** Discriminated union of all relay messages */
2680
+ declare const RelayMessageSchema: z.ZodDiscriminatedUnion<"type", [z.ZodObject<{
3184
2681
  type: z.ZodLiteral<"register">;
3185
2682
  owner: z.ZodString;
3186
2683
  token: z.ZodString;
3187
2684
  card: z.ZodRecord<z.ZodString, z.ZodUnknown>;
2685
+ cards: z.ZodOptional<z.ZodArray<z.ZodRecord<z.ZodString, z.ZodUnknown>, "many">>;
3188
2686
  }, "strip", z.ZodTypeAny, {
3189
2687
  type: "register";
3190
2688
  owner: string;
3191
2689
  token: string;
3192
2690
  card: Record<string, unknown>;
2691
+ cards?: Record<string, unknown>[] | undefined;
3193
2692
  }, {
3194
2693
  type: "register";
3195
2694
  owner: string;
3196
2695
  token: string;
3197
2696
  card: Record<string, unknown>;
3198
- }>;
3199
- /** Registry → Agent: Acknowledge registration */
3200
- declare const RegisteredMessageSchema: z.ZodObject<{
2697
+ cards?: Record<string, unknown>[] | undefined;
2698
+ }>, z.ZodObject<{
3201
2699
  type: z.ZodLiteral<"registered">;
3202
2700
  agent_id: z.ZodString;
3203
2701
  }, "strip", z.ZodTypeAny, {
@@ -3206,9 +2704,7 @@ declare const RegisteredMessageSchema: z.ZodObject<{
3206
2704
  }, {
3207
2705
  type: "registered";
3208
2706
  agent_id: string;
3209
- }>;
3210
- /** Agent A → Registry: Request relay to another agent */
3211
- declare const RelayRequestMessageSchema: z.ZodObject<{
2707
+ }>, z.ZodObject<{
3212
2708
  type: z.ZodLiteral<"relay_request">;
3213
2709
  id: z.ZodString;
3214
2710
  target_owner: z.ZodString;
@@ -3235,9 +2731,7 @@ declare const RelayRequestMessageSchema: z.ZodObject<{
3235
2731
  skill_id?: string | undefined;
3236
2732
  requester?: string | undefined;
3237
2733
  escrow_receipt?: Record<string, unknown> | undefined;
3238
- }>;
3239
- /** Registry → Agent B: Incoming request forwarded from Agent A */
3240
- declare const IncomingRequestMessageSchema: z.ZodObject<{
2734
+ }>, z.ZodObject<{
3241
2735
  type: z.ZodLiteral<"incoming_request">;
3242
2736
  id: z.ZodString;
3243
2737
  from_owner: z.ZodString;
@@ -3264,9 +2758,7 @@ declare const IncomingRequestMessageSchema: z.ZodObject<{
3264
2758
  skill_id?: string | undefined;
3265
2759
  requester?: string | undefined;
3266
2760
  escrow_receipt?: Record<string, unknown> | undefined;
3267
- }>;
3268
- /** Agent B → Registry: Response to a relayed request */
3269
- declare const RelayResponseMessageSchema: z.ZodObject<{
2761
+ }>, z.ZodObject<{
3270
2762
  type: z.ZodLiteral<"relay_response">;
3271
2763
  id: z.ZodString;
3272
2764
  result: z.ZodOptional<z.ZodUnknown>;
@@ -3296,9 +2788,7 @@ declare const RelayResponseMessageSchema: z.ZodObject<{
3296
2788
  code: number;
3297
2789
  message: string;
3298
2790
  } | undefined;
3299
- }>;
3300
- /** Registry → Agent A: Forwarded response from Agent B */
3301
- declare const ResponseMessageSchema: z.ZodObject<{
2791
+ }>, z.ZodObject<{
3302
2792
  type: z.ZodLiteral<"response">;
3303
2793
  id: z.ZodString;
3304
2794
  result: z.ZodOptional<z.ZodUnknown>;
@@ -3328,9 +2818,7 @@ declare const ResponseMessageSchema: z.ZodObject<{
3328
2818
  code: number;
3329
2819
  message: string;
3330
2820
  } | undefined;
3331
- }>;
3332
- /** Error message (either direction) */
3333
- declare const ErrorMessageSchema: z.ZodObject<{
2821
+ }>, z.ZodObject<{
3334
2822
  type: z.ZodLiteral<"error">;
3335
2823
  code: z.ZodString;
3336
2824
  message: z.ZodString;
@@ -3345,266 +2833,865 @@ declare const ErrorMessageSchema: z.ZodObject<{
3345
2833
  code: string;
3346
2834
  message: string;
3347
2835
  request_id?: string | undefined;
3348
- }>;
3349
- /** Discriminated union of all relay messages */
3350
- declare const RelayMessageSchema: z.ZodDiscriminatedUnion<"type", [z.ZodObject<{
3351
- type: z.ZodLiteral<"register">;
3352
- owner: z.ZodString;
3353
- token: z.ZodString;
3354
- card: z.ZodRecord<z.ZodString, z.ZodUnknown>;
3355
- }, "strip", z.ZodTypeAny, {
3356
- type: "register";
3357
- owner: string;
3358
- token: string;
3359
- card: Record<string, unknown>;
3360
- }, {
3361
- type: "register";
3362
- owner: string;
3363
- token: string;
3364
- card: Record<string, unknown>;
3365
- }>, z.ZodObject<{
3366
- type: z.ZodLiteral<"registered">;
3367
- agent_id: z.ZodString;
3368
- }, "strip", z.ZodTypeAny, {
3369
- type: "registered";
3370
- agent_id: string;
3371
- }, {
3372
- type: "registered";
3373
- agent_id: string;
3374
2836
  }>, z.ZodObject<{
3375
- type: z.ZodLiteral<"relay_request">;
2837
+ type: z.ZodLiteral<"relay_progress">;
3376
2838
  id: z.ZodString;
3377
- target_owner: z.ZodString;
3378
- card_id: z.ZodString;
3379
- skill_id: z.ZodOptional<z.ZodString>;
3380
- params: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
3381
- requester: z.ZodOptional<z.ZodString>;
3382
- escrow_receipt: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
2839
+ progress: z.ZodOptional<z.ZodNumber>;
2840
+ message: z.ZodOptional<z.ZodString>;
3383
2841
  }, "strip", z.ZodTypeAny, {
3384
- type: "relay_request";
3385
- params: Record<string, unknown>;
2842
+ type: "relay_progress";
3386
2843
  id: string;
3387
- card_id: string;
3388
- target_owner: string;
3389
- skill_id?: string | undefined;
3390
- requester?: string | undefined;
3391
- escrow_receipt?: Record<string, unknown> | undefined;
2844
+ message?: string | undefined;
2845
+ progress?: number | undefined;
3392
2846
  }, {
3393
- type: "relay_request";
2847
+ type: "relay_progress";
3394
2848
  id: string;
3395
- card_id: string;
3396
- target_owner: string;
3397
- params?: Record<string, unknown> | undefined;
3398
- skill_id?: string | undefined;
3399
- requester?: string | undefined;
3400
- escrow_receipt?: Record<string, unknown> | undefined;
3401
- }>, z.ZodObject<{
3402
- type: z.ZodLiteral<"incoming_request">;
3403
- id: z.ZodString;
3404
- from_owner: z.ZodString;
2849
+ message?: string | undefined;
2850
+ progress?: number | undefined;
2851
+ }>]>;
2852
+ type RegisterMessage = z.infer<typeof RegisterMessageSchema>;
2853
+ type RegisteredMessage = z.infer<typeof RegisteredMessageSchema>;
2854
+ type RelayRequestMessage = z.infer<typeof RelayRequestMessageSchema>;
2855
+ type IncomingRequestMessage = z.infer<typeof IncomingRequestMessageSchema>;
2856
+ type RelayResponseMessage = z.infer<typeof RelayResponseMessageSchema>;
2857
+ type ResponseMessage = z.infer<typeof ResponseMessageSchema>;
2858
+ type ErrorMessage = z.infer<typeof ErrorMessageSchema>;
2859
+ type RelayMessage = z.infer<typeof RelayMessageSchema>;
2860
+ /** Pending relay request tracking */
2861
+ interface PendingRelayRequest {
2862
+ originOwner: string;
2863
+ timeout: ReturnType<typeof setTimeout>;
2864
+ /** Escrow ID for the credit hold, if credits were reserved for this request */
2865
+ escrowId?: string;
2866
+ /** The target provider owner, needed to release escrow on provider disconnect */
2867
+ targetOwner?: string;
2868
+ /** Job ID if this request was dispatched from the job queue (relay bridge) */
2869
+ jobId?: string;
2870
+ }
2871
+ /** Relay server state returned from registerWebSocketRelay */
2872
+ interface RelayState {
2873
+ /** Number of currently connected agents */
2874
+ getOnlineCount(): number;
2875
+ /** List of connected agent owners */
2876
+ getOnlineOwners(): string[];
2877
+ /** Graceful shutdown -- close all connections */
2878
+ shutdown(): void;
2879
+ /** Set a callback invoked when an agent registers (comes online) */
2880
+ setOnAgentOnline?(cb: (owner: string) => void): void;
2881
+ /** Get the active connections map (owner -> WebSocket) */
2882
+ getConnections?(): Map<string, unknown>;
2883
+ /** Get the pending requests map */
2884
+ getPendingRequests?(): Map<string, PendingRelayRequest>;
2885
+ /** Send a JSON message over a WebSocket */
2886
+ sendMessage?(ws: unknown, msg: Record<string, unknown>): void;
2887
+ }
2888
+
2889
+ /** Result of handling an incoming relay request */
2890
+ interface RelayHandlerResult {
2891
+ result?: unknown;
2892
+ error?: {
2893
+ code: number;
2894
+ message: string;
2895
+ };
2896
+ }
2897
+ /** Options for the RelayClient constructor */
2898
+ interface RelayClientOptions {
2899
+ /** Registry WebSocket URL (e.g., "wss://hub.agentbnb.dev/ws") */
2900
+ registryUrl: string;
2901
+ /** Agent owner identifier */
2902
+ owner: string;
2903
+ /** Authentication token */
2904
+ token: string;
2905
+ /** Capability card data to register */
2906
+ card: Record<string, unknown>;
2907
+ /** Additional cards to register alongside the primary card (e.g., conductor card) */
2908
+ cards?: Record<string, unknown>[];
2909
+ /** Handler for incoming relay requests from other agents */
2910
+ onRequest: (req: IncomingRequestMessage) => Promise<RelayHandlerResult>;
2911
+ /** Suppress logging. Default false. */
2912
+ silent?: boolean;
2913
+ }
2914
+ /** Options for making a relay request to another agent */
2915
+ interface RelayRequestOptions$1 {
2916
+ targetOwner: string;
2917
+ cardId: string;
2918
+ skillId?: string;
2919
+ params: Record<string, unknown>;
2920
+ requester?: string;
2921
+ escrowReceipt?: Record<string, unknown>;
2922
+ timeoutMs?: number;
2923
+ /** Optional callback invoked when the provider sends relay_progress heartbeats. */
2924
+ onProgress?: (progress: {
2925
+ id: string;
2926
+ progress?: number;
2927
+ message?: string;
2928
+ }) => void;
2929
+ }
2930
+ /**
2931
+ * WebSocket client for connecting to an AgentBnB registry relay.
2932
+ * Handles registration, auto-reconnect, incoming requests, and outbound relay requests.
2933
+ */
2934
+ declare class RelayClient {
2935
+ private ws;
2936
+ private readonly opts;
2937
+ private readonly pendingRequests;
2938
+ private reconnectAttempts;
2939
+ private reconnectTimer;
2940
+ private intentionalClose;
2941
+ private registered;
2942
+ private pongTimeout;
2943
+ private pingInterval;
2944
+ constructor(opts: RelayClientOptions);
2945
+ /**
2946
+ * Connect to the registry relay and register.
2947
+ * Resolves when registration is acknowledged.
2948
+ */
2949
+ connect(): Promise<void>;
2950
+ /**
2951
+ * Disconnect from the registry relay.
2952
+ */
2953
+ disconnect(): void;
2954
+ /**
2955
+ * Send a relay request to another agent via the registry.
2956
+ * @returns The result from the target agent.
2957
+ */
2958
+ request(opts: RelayRequestOptions$1): Promise<unknown>;
2959
+ /**
2960
+ * Send a relay_progress message to the relay server for a given request.
2961
+ * Used by the onRequest handler to forward SkillExecutor progress updates
2962
+ * to the requesting agent so it can reset its timeout window.
2963
+ *
2964
+ * @param requestId - The relay request ID to associate progress with.
2965
+ * @param info - Progress details (step, total, message).
2966
+ */
2967
+ sendProgress(requestId: string, info: {
2968
+ step: number;
2969
+ total: number;
2970
+ message: string;
2971
+ }): void;
2972
+ /** Whether the client is connected and registered */
2973
+ get isConnected(): boolean;
2974
+ private buildWsUrl;
2975
+ private handleMessage;
2976
+ private handleIncomingRequest;
2977
+ private handleResponse;
2978
+ private handleError;
2979
+ private handleProgress;
2980
+ private send;
2981
+ private startPingInterval;
2982
+ private stopPingInterval;
2983
+ private cleanup;
2984
+ private scheduleReconnect;
2985
+ }
2986
+
2987
+ /**
2988
+ * PipelineOrchestrator — DAG-based remote execution engine for the Conductor.
2989
+ *
2990
+ * Executes sub-tasks across remote agents via the Gateway client,
2991
+ * respecting dependency ordering (parallel waves for independent tasks),
2992
+ * output piping between steps, and retry with alternative agents on failure.
2993
+ *
2994
+ * Budget checking is NOT done here — the caller (ConductorMode) handles that.
2995
+ * This module is pure execution.
2996
+ */
2997
+
2998
+ /**
2999
+ * Options for the orchestrate() function.
3000
+ */
3001
+ interface OrchestrateOptions {
3002
+ /** Ordered list of sub-tasks forming a dependency DAG. */
3003
+ subtasks: SubTask[];
3004
+ /** Match results keyed by subtask ID. */
3005
+ matches: Map<string, MatchResult>;
3006
+ /** Bearer token for authenticating with remote agents. */
3007
+ gatewayToken: string;
3008
+ /** Resolves an agent owner to their gateway URL and card ID. */
3009
+ resolveAgentUrl: (agentOwner: string) => {
3010
+ url: string;
3011
+ cardId: string;
3012
+ };
3013
+ /** Per-task timeout in milliseconds. Default 30000. */
3014
+ timeoutMs?: number;
3015
+ /** Maximum budget in credits. If set, aborts remaining tasks when exceeded. */
3016
+ maxBudget?: number;
3017
+ /** Optional relay client for executing tasks on remote agents (relay:// URLs). */
3018
+ relayClient?: RelayClient;
3019
+ /** Owner identifier of the requester agent. Used for relay requests. */
3020
+ requesterOwner?: string;
3021
+ }
3022
+ /**
3023
+ * Executes a DAG of sub-tasks across remote agents via Gateway.
3024
+ *
3025
+ * Execution flow:
3026
+ * 1. Computes execution waves from dependency graph
3027
+ * 2. For each wave, executes all tasks in parallel via Promise.allSettled
3028
+ * 3. Before each task, interpolates params against completed step outputs
3029
+ * 4. On failure, retries with the first alternative agent from MatchResult
3030
+ * 5. Tracks per-task spending and total credits
3031
+ * 6. Optionally enforces a maxBudget ceiling
3032
+ *
3033
+ * @param opts - Orchestration options.
3034
+ * @returns Aggregated orchestration result.
3035
+ */
3036
+ declare function orchestrate(opts: OrchestrateOptions): Promise<OrchestrationResult>;
3037
+
3038
+ /**
3039
+ * ConductorMode — ExecutorMode implementation for Conductor skills.
3040
+ *
3041
+ * Chains TaskDecomposer -> CapabilityMatcher -> BudgetController -> PipelineOrchestrator
3042
+ * to execute multi-agent orchestration pipelines via the SkillExecutor dispatch system.
3043
+ *
3044
+ * Supports two conductor skills:
3045
+ * - `orchestrate`: Full pipeline — decompose, match, budget check, execute, return results.
3046
+ * - `plan`: Planning only — decompose, match, budget check, return plan without executing.
3047
+ */
3048
+
3049
+ /**
3050
+ * Configuration options for ConductorMode.
3051
+ */
3052
+ interface ConductorModeOptions {
3053
+ /** Registry database for card search (FTS5). */
3054
+ db: Database.Database;
3055
+ /** Credit database for budget checks. */
3056
+ creditDb: Database.Database;
3057
+ /** Owner ID of the conductor agent — used for self-exclusion in matching. */
3058
+ conductorOwner: string;
3059
+ /** Bearer token for authenticating with remote agents. */
3060
+ gatewayToken: string;
3061
+ /** Resolves an agent owner to their gateway URL and card ID. */
3062
+ resolveAgentUrl: (owner: string) => {
3063
+ url: string;
3064
+ cardId: string;
3065
+ };
3066
+ /** Maximum budget in credits for orchestration runs. Default 100. */
3067
+ maxBudget?: number;
3068
+ }
3069
+ /**
3070
+ * ExecutorMode implementation for Conductor skills ('orchestrate' and 'plan').
3071
+ *
3072
+ * Dispatches through the full Conductor pipeline:
3073
+ * 1. TaskDecomposer breaks the task into SubTasks
3074
+ * 2. CapabilityMatcher finds agents for each sub-task
3075
+ * 3. BudgetController validates cost against limits
3076
+ * 4. PipelineOrchestrator executes the DAG (orchestrate only)
3077
+ */
3078
+ declare class ConductorMode implements ExecutorMode {
3079
+ private readonly db;
3080
+ private readonly creditDb;
3081
+ private readonly conductorOwner;
3082
+ private readonly gatewayToken;
3083
+ private readonly resolveAgentUrl;
3084
+ private readonly maxBudget;
3085
+ constructor(opts: ConductorModeOptions);
3086
+ /**
3087
+ * Execute a conductor skill with the given config and params.
3088
+ *
3089
+ * @param config - SkillConfig with type 'conductor' and conductor_skill field.
3090
+ * @param params - Must include `task` string.
3091
+ * @returns Execution result without latency_ms (added by SkillExecutor).
3092
+ */
3093
+ execute(config: SkillConfig, params: Record<string, unknown>, onProgress?: ProgressCallback): Promise<Omit<ExecutionResult, 'latency_ms'>>;
3094
+ }
3095
+
3096
+ /**
3097
+ * Ed25519 keypair as raw DER-encoded Buffers.
3098
+ */
3099
+ interface KeyPair {
3100
+ publicKey: Buffer;
3101
+ privateKey: Buffer;
3102
+ }
3103
+ /**
3104
+ * Generates a new Ed25519 keypair.
3105
+ * Uses Node.js built-in crypto — no external dependencies.
3106
+ *
3107
+ * @returns Object with publicKey and privateKey as DER-encoded Buffers.
3108
+ */
3109
+ declare function generateKeyPair(): KeyPair;
3110
+ /**
3111
+ * Saves an Ed25519 keypair to disk.
3112
+ * Private key is written with mode 0o600 (owner read/write only).
3113
+ *
3114
+ * @param configDir - Directory to write key files into.
3115
+ * @param keys - The keypair to persist.
3116
+ */
3117
+ declare function saveKeyPair(configDir: string, keys: KeyPair): void;
3118
+ /**
3119
+ * Loads an Ed25519 keypair from disk.
3120
+ *
3121
+ * @param configDir - Directory containing private.key and public.key files.
3122
+ * @returns The loaded keypair.
3123
+ * @throws {AgentBnBError} with code 'KEYPAIR_NOT_FOUND' if either key file is missing.
3124
+ */
3125
+ declare function loadKeyPair(configDir: string): KeyPair;
3126
+ /**
3127
+ * Signs escrow receipt data with an Ed25519 private key.
3128
+ * Data is serialized to canonical JSON (sorted keys) before signing.
3129
+ *
3130
+ * @param data - The receipt data to sign (all fields except 'signature').
3131
+ * @param privateKey - DER-encoded Ed25519 private key.
3132
+ * @returns Base64url-encoded signature string.
3133
+ */
3134
+ declare function signEscrowReceipt(data: Record<string, unknown>, privateKey: Buffer): string;
3135
+ /**
3136
+ * Verifies an Ed25519 signature over escrow receipt data.
3137
+ * Returns false (does not throw) for invalid signatures or wrong keys.
3138
+ *
3139
+ * @param data - The receipt data that was signed (all fields except 'signature').
3140
+ * @param signature - Base64url-encoded signature string.
3141
+ * @param publicKey - DER-encoded Ed25519 public key.
3142
+ * @returns true if signature is valid, false otherwise.
3143
+ */
3144
+ declare function verifyEscrowReceipt(data: Record<string, unknown>, signature: string, publicKey: Buffer): boolean;
3145
+
3146
+ /**
3147
+ * Zod schema for validating EscrowReceipt objects.
3148
+ * Used by providers to validate incoming receipts before verification.
3149
+ */
3150
+ declare const EscrowReceiptSchema: z.ZodObject<{
3151
+ requester_owner: z.ZodString;
3152
+ requester_public_key: z.ZodString;
3153
+ amount: z.ZodNumber;
3405
3154
  card_id: z.ZodString;
3406
3155
  skill_id: z.ZodOptional<z.ZodString>;
3407
- params: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
3408
- requester: z.ZodOptional<z.ZodString>;
3409
- escrow_receipt: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
3156
+ timestamp: z.ZodString;
3157
+ nonce: z.ZodString;
3158
+ signature: z.ZodString;
3410
3159
  }, "strip", z.ZodTypeAny, {
3411
- type: "incoming_request";
3412
- params: Record<string, unknown>;
3413
- id: string;
3160
+ signature: string;
3161
+ requester_owner: string;
3162
+ requester_public_key: string;
3163
+ amount: number;
3414
3164
  card_id: string;
3415
- from_owner: string;
3165
+ timestamp: string;
3166
+ nonce: string;
3416
3167
  skill_id?: string | undefined;
3417
- requester?: string | undefined;
3418
- escrow_receipt?: Record<string, unknown> | undefined;
3419
3168
  }, {
3420
- type: "incoming_request";
3421
- id: string;
3169
+ signature: string;
3170
+ requester_owner: string;
3171
+ requester_public_key: string;
3172
+ amount: number;
3422
3173
  card_id: string;
3423
- from_owner: string;
3424
- params?: Record<string, unknown> | undefined;
3174
+ timestamp: string;
3175
+ nonce: string;
3425
3176
  skill_id?: string | undefined;
3426
- requester?: string | undefined;
3427
- escrow_receipt?: Record<string, unknown> | undefined;
3428
- }>, z.ZodObject<{
3429
- type: z.ZodLiteral<"relay_response">;
3430
- id: z.ZodString;
3431
- result: z.ZodOptional<z.ZodUnknown>;
3432
- error: z.ZodOptional<z.ZodObject<{
3433
- code: z.ZodNumber;
3434
- message: z.ZodString;
3435
- }, "strip", z.ZodTypeAny, {
3436
- code: number;
3437
- message: string;
3438
- }, {
3439
- code: number;
3440
- message: string;
3441
- }>>;
3442
- }, "strip", z.ZodTypeAny, {
3443
- type: "relay_response";
3444
- id: string;
3445
- result?: unknown;
3446
- error?: {
3447
- code: number;
3448
- message: string;
3449
- } | undefined;
3450
- }, {
3451
- type: "relay_response";
3452
- id: string;
3453
- result?: unknown;
3454
- error?: {
3455
- code: number;
3456
- message: string;
3457
- } | undefined;
3458
- }>, z.ZodObject<{
3459
- type: z.ZodLiteral<"response">;
3460
- id: z.ZodString;
3461
- result: z.ZodOptional<z.ZodUnknown>;
3462
- error: z.ZodOptional<z.ZodObject<{
3463
- code: z.ZodNumber;
3464
- message: z.ZodString;
3177
+ }>;
3178
+ /**
3179
+ * Options for creating a signed escrow receipt.
3180
+ */
3181
+ interface CreateReceiptOpts {
3182
+ /** Agent owner identifier (requester). */
3183
+ owner: string;
3184
+ /** Number of credits to commit. */
3185
+ amount: number;
3186
+ /** Capability Card ID being requested. */
3187
+ cardId: string;
3188
+ /** Optional skill ID within the card. */
3189
+ skillId?: string;
3190
+ }
3191
+ /**
3192
+ * Creates a signed escrow receipt by atomically holding credits in the local DB
3193
+ * and producing a cryptographically signed receipt that can be sent to a provider.
3194
+ *
3195
+ * This combines local escrow hold + receipt generation from the requester's perspective.
3196
+ *
3197
+ * @param db - The credit database instance.
3198
+ * @param privateKey - DER-encoded Ed25519 private key for signing.
3199
+ * @param publicKey - DER-encoded Ed25519 public key (included in receipt for verification).
3200
+ * @param opts - Receipt creation options (owner, amount, cardId, skillId).
3201
+ * @returns Object with escrowId (local reference) and signed receipt (for transmission).
3202
+ * @throws {AgentBnBError} with code 'INSUFFICIENT_CREDITS' if balance is too low.
3203
+ */
3204
+ declare function createSignedEscrowReceipt(db: Database.Database, privateKey: Buffer, publicKey: Buffer, opts: CreateReceiptOpts): {
3205
+ escrowId: string;
3206
+ receipt: EscrowReceipt;
3207
+ };
3208
+
3209
+ /**
3210
+ * Provider-side settlement: records earnings from a signed escrow receipt.
3211
+ * The provider calls this after successfully executing a capability.
3212
+ * Credits are recorded in the provider's own local DB.
3213
+ *
3214
+ * @param providerDb - The provider's local credit database.
3215
+ * @param providerOwner - Provider agent identifier.
3216
+ * @param receipt - The signed escrow receipt from the requester.
3217
+ * @returns Object indicating settlement success.
3218
+ */
3219
+ declare function settleProviderEarning(providerDb: Database.Database, providerOwner: string, receipt: EscrowReceipt): {
3220
+ settled: true;
3221
+ };
3222
+ /**
3223
+ * Requester-side settlement: confirms that the escrow debit is permanent.
3224
+ * Called after the requester receives confirmation that the provider
3225
+ * successfully executed the capability. Marks escrow as 'settled' without
3226
+ * crediting anyone (credits stay deducted from requester).
3227
+ *
3228
+ * @param requesterDb - The requester's local credit database.
3229
+ * @param escrowId - The escrow ID to confirm as settled.
3230
+ */
3231
+ declare function settleRequesterEscrow(requesterDb: Database.Database, escrowId: string): void;
3232
+ /**
3233
+ * Requester-side failure handling: releases escrowed credits (refund).
3234
+ * Called when the capability execution fails and the requester needs
3235
+ * their credits back.
3236
+ *
3237
+ * @param requesterDb - The requester's local credit database.
3238
+ * @param escrowId - The escrow ID to release.
3239
+ */
3240
+ declare function releaseRequesterEscrow(requesterDb: Database.Database, escrowId: string): void;
3241
+
3242
+ /**
3243
+ * Agent Identity — the unified identity record for an AgentBnB agent.
3244
+ * Stored at ~/.agentbnb/identity.json.
3245
+ */
3246
+ declare const AgentIdentitySchema: z.ZodObject<{
3247
+ /** Deterministic ID derived from public key: sha256(hex).slice(0, 16). */
3248
+ agent_id: z.ZodString;
3249
+ /** Human-readable owner name (from config or init). */
3250
+ owner: z.ZodString;
3251
+ /** Hex-encoded Ed25519 public key. */
3252
+ public_key: z.ZodString;
3253
+ /** ISO 8601 timestamp of identity creation. */
3254
+ created_at: z.ZodString;
3255
+ /** Optional guarantor info if linked to a human. */
3256
+ guarantor: z.ZodOptional<z.ZodObject<{
3257
+ github_login: z.ZodString;
3258
+ verified_at: z.ZodString;
3465
3259
  }, "strip", z.ZodTypeAny, {
3466
- code: number;
3467
- message: string;
3260
+ github_login: string;
3261
+ verified_at: string;
3468
3262
  }, {
3469
- code: number;
3470
- message: string;
3263
+ github_login: string;
3264
+ verified_at: string;
3471
3265
  }>>;
3472
3266
  }, "strip", z.ZodTypeAny, {
3473
- type: "response";
3474
- id: string;
3475
- result?: unknown;
3476
- error?: {
3477
- code: number;
3478
- message: string;
3267
+ owner: string;
3268
+ created_at: string;
3269
+ agent_id: string;
3270
+ public_key: string;
3271
+ guarantor?: {
3272
+ github_login: string;
3273
+ verified_at: string;
3479
3274
  } | undefined;
3480
3275
  }, {
3481
- type: "response";
3482
- id: string;
3483
- result?: unknown;
3484
- error?: {
3485
- code: number;
3486
- message: string;
3276
+ owner: string;
3277
+ created_at: string;
3278
+ agent_id: string;
3279
+ public_key: string;
3280
+ guarantor?: {
3281
+ github_login: string;
3282
+ verified_at: string;
3487
3283
  } | undefined;
3488
- }>, z.ZodObject<{
3489
- type: z.ZodLiteral<"error">;
3490
- code: z.ZodString;
3491
- message: z.ZodString;
3492
- request_id: z.ZodOptional<z.ZodString>;
3284
+ }>;
3285
+ type AgentIdentity = z.infer<typeof AgentIdentitySchema>;
3286
+ /**
3287
+ * Agent Certificate — a self-signed attestation of agent identity.
3288
+ * Used for P2P identity verification without a shared auth server.
3289
+ */
3290
+ declare const AgentCertificateSchema: z.ZodObject<{
3291
+ identity: z.ZodObject<{
3292
+ /** Deterministic ID derived from public key: sha256(hex).slice(0, 16). */
3293
+ agent_id: z.ZodString;
3294
+ /** Human-readable owner name (from config or init). */
3295
+ owner: z.ZodString;
3296
+ /** Hex-encoded Ed25519 public key. */
3297
+ public_key: z.ZodString;
3298
+ /** ISO 8601 timestamp of identity creation. */
3299
+ created_at: z.ZodString;
3300
+ /** Optional guarantor info if linked to a human. */
3301
+ guarantor: z.ZodOptional<z.ZodObject<{
3302
+ github_login: z.ZodString;
3303
+ verified_at: z.ZodString;
3304
+ }, "strip", z.ZodTypeAny, {
3305
+ github_login: string;
3306
+ verified_at: string;
3307
+ }, {
3308
+ github_login: string;
3309
+ verified_at: string;
3310
+ }>>;
3311
+ }, "strip", z.ZodTypeAny, {
3312
+ owner: string;
3313
+ created_at: string;
3314
+ agent_id: string;
3315
+ public_key: string;
3316
+ guarantor?: {
3317
+ github_login: string;
3318
+ verified_at: string;
3319
+ } | undefined;
3320
+ }, {
3321
+ owner: string;
3322
+ created_at: string;
3323
+ agent_id: string;
3324
+ public_key: string;
3325
+ guarantor?: {
3326
+ github_login: string;
3327
+ verified_at: string;
3328
+ } | undefined;
3329
+ }>;
3330
+ /** ISO 8601 timestamp of certificate issuance. */
3331
+ issued_at: z.ZodString;
3332
+ /** ISO 8601 timestamp of certificate expiry. */
3333
+ expires_at: z.ZodString;
3334
+ /** Hex-encoded public key of the issuer (same as identity for self-signed). */
3335
+ issuer_public_key: z.ZodString;
3336
+ /** Base64url Ed25519 signature over { identity, issued_at, expires_at, issuer_public_key }. */
3337
+ signature: z.ZodString;
3493
3338
  }, "strip", z.ZodTypeAny, {
3494
- type: "error";
3495
- code: string;
3496
- message: string;
3497
- request_id?: string | undefined;
3339
+ signature: string;
3340
+ identity: {
3341
+ owner: string;
3342
+ created_at: string;
3343
+ agent_id: string;
3344
+ public_key: string;
3345
+ guarantor?: {
3346
+ github_login: string;
3347
+ verified_at: string;
3348
+ } | undefined;
3349
+ };
3350
+ issued_at: string;
3351
+ expires_at: string;
3352
+ issuer_public_key: string;
3498
3353
  }, {
3499
- type: "error";
3500
- code: string;
3501
- message: string;
3502
- request_id?: string | undefined;
3503
- }>]>;
3504
- type RegisterMessage = z.infer<typeof RegisterMessageSchema>;
3505
- type RegisteredMessage = z.infer<typeof RegisteredMessageSchema>;
3506
- type RelayRequestMessage = z.infer<typeof RelayRequestMessageSchema>;
3507
- type IncomingRequestMessage = z.infer<typeof IncomingRequestMessageSchema>;
3508
- type RelayResponseMessage = z.infer<typeof RelayResponseMessageSchema>;
3509
- type ResponseMessage = z.infer<typeof ResponseMessageSchema>;
3510
- type ErrorMessage = z.infer<typeof ErrorMessageSchema>;
3511
- type RelayMessage = z.infer<typeof RelayMessageSchema>;
3512
- /** Relay server state returned from registerWebSocketRelay */
3513
- interface RelayState {
3514
- /** Number of currently connected agents */
3515
- getOnlineCount(): number;
3516
- /** List of connected agent owners */
3517
- getOnlineOwners(): string[];
3518
- /** Graceful shutdown — close all connections */
3519
- shutdown(): void;
3354
+ signature: string;
3355
+ identity: {
3356
+ owner: string;
3357
+ created_at: string;
3358
+ agent_id: string;
3359
+ public_key: string;
3360
+ guarantor?: {
3361
+ github_login: string;
3362
+ verified_at: string;
3363
+ } | undefined;
3364
+ };
3365
+ issued_at: string;
3366
+ expires_at: string;
3367
+ issuer_public_key: string;
3368
+ }>;
3369
+ type AgentCertificate = z.infer<typeof AgentCertificateSchema>;
3370
+ /**
3371
+ * Derives a deterministic agent_id from a hex-encoded public key.
3372
+ * Uses first 16 chars of SHA-256 hash.
3373
+ */
3374
+ declare function deriveAgentId(publicKeyHex: string): string;
3375
+ /**
3376
+ * Creates a new agent identity. Generates an Ed25519 keypair if one does not
3377
+ * already exist. Writes identity.json to the config directory.
3378
+ *
3379
+ * @param configDir - Directory to write identity.json into (e.g. ~/.agentbnb).
3380
+ * @param owner - Human-readable agent owner name.
3381
+ * @returns The newly created AgentIdentity.
3382
+ */
3383
+ declare function createIdentity(configDir: string, owner: string): AgentIdentity;
3384
+ /**
3385
+ * Loads an existing agent identity from disk.
3386
+ *
3387
+ * @param configDir - Directory containing identity.json.
3388
+ * @returns Parsed AgentIdentity or null if file does not exist.
3389
+ */
3390
+ declare function loadIdentity(configDir: string): AgentIdentity | null;
3391
+ /**
3392
+ * Persists an agent identity to disk.
3393
+ *
3394
+ * @param configDir - Directory to write identity.json into.
3395
+ * @param identity - The identity to save.
3396
+ */
3397
+ declare function saveIdentity(configDir: string, identity: AgentIdentity): void;
3398
+ /**
3399
+ * Issues a self-signed Agent Certificate. Valid for 365 days.
3400
+ *
3401
+ * @param identity - The agent identity to certify.
3402
+ * @param privateKey - DER-encoded Ed25519 private key.
3403
+ * @returns A signed AgentCertificate.
3404
+ */
3405
+ declare function issueAgentCertificate(identity: AgentIdentity, privateKey: Buffer): AgentCertificate;
3406
+ /**
3407
+ * Verifies an Agent Certificate's signature and expiry.
3408
+ *
3409
+ * @param cert - The certificate to verify.
3410
+ * @returns true if signature is valid and certificate has not expired.
3411
+ */
3412
+ declare function verifyAgentCertificate(cert: AgentCertificate): boolean;
3413
+ /**
3414
+ * Ensures an identity exists for the given config directory.
3415
+ * If identity.json already exists, returns it. Otherwise creates a new one.
3416
+ *
3417
+ * @param configDir - Config directory path.
3418
+ * @param owner - Owner name to use if creating new identity.
3419
+ * @returns The loaded or newly created AgentIdentity.
3420
+ */
3421
+ declare function ensureIdentity(configDir: string, owner: string): AgentIdentity;
3422
+
3423
+ /**
3424
+ * Options for constructing an AgentBnBConsumer.
3425
+ */
3426
+ interface ConsumerOptions {
3427
+ /** Override the config directory (default: ~/.agentbnb or AGENTBNB_DIR). */
3428
+ configDir?: string;
3429
+ }
3430
+ /**
3431
+ * Options for requesting a capability.
3432
+ */
3433
+ interface ConsumerRequestOptions {
3434
+ /** Gateway URL of the target agent. */
3435
+ gatewayUrl: string;
3436
+ /** Bearer token for the target agent's gateway. */
3437
+ token: string;
3438
+ /** Capability Card ID to execute. */
3439
+ cardId: string;
3440
+ /** Optional skill ID within the card. */
3441
+ skillId?: string;
3442
+ /** Input parameters for the capability. */
3443
+ params?: Record<string, unknown>;
3444
+ /** Credit amount to commit (escrow). */
3445
+ credits: number;
3446
+ /** Timeout in milliseconds. Default 30000. */
3447
+ timeoutMs?: number;
3448
+ }
3449
+ /**
3450
+ * AgentBnBConsumer — high-level SDK class for agents consuming capabilities.
3451
+ *
3452
+ * Encapsulates the full request lifecycle: identity loading, escrow creation,
3453
+ * capability request, and settlement/release.
3454
+ *
3455
+ * @example
3456
+ * ```typescript
3457
+ * const consumer = new AgentBnBConsumer();
3458
+ * consumer.authenticate();
3459
+ * const result = await consumer.request({
3460
+ * gatewayUrl: 'http://peer:7700',
3461
+ * token: 'peer-token',
3462
+ * cardId: 'uuid-of-card',
3463
+ * credits: 5,
3464
+ * });
3465
+ * ```
3466
+ */
3467
+ declare class AgentBnBConsumer {
3468
+ private configDir;
3469
+ private identity;
3470
+ private keys;
3471
+ private creditDb;
3472
+ constructor(opts?: ConsumerOptions);
3473
+ /**
3474
+ * Loads agent identity and keypair from disk.
3475
+ * Creates identity if none exists (uses owner from config.json or generates one).
3476
+ *
3477
+ * @returns The loaded AgentIdentity.
3478
+ * @throws {AgentBnBError} if keypair is missing and cannot be created.
3479
+ */
3480
+ authenticate(): AgentIdentity;
3481
+ /**
3482
+ * Returns the cached identity. Throws if not yet authenticated.
3483
+ */
3484
+ getIdentity(): AgentIdentity;
3485
+ /**
3486
+ * Requests a capability from a remote agent with full escrow lifecycle.
3487
+ *
3488
+ * 1. Creates a signed escrow receipt (holds credits locally)
3489
+ * 2. Sends the request to the target gateway
3490
+ * 3. Settles escrow on success, releases on failure
3491
+ *
3492
+ * @param opts - Request options including target, card, credits, and params.
3493
+ * @returns The result from the capability execution.
3494
+ * @throws {AgentBnBError} on insufficient credits, network error, or RPC error.
3495
+ */
3496
+ request(opts: ConsumerRequestOptions): Promise<unknown>;
3497
+ /**
3498
+ * Returns the current credit balance for this agent.
3499
+ */
3500
+ getBalance(): number;
3501
+ /**
3502
+ * Returns basic reputation data from the local credit database.
3503
+ * Note: success_rate is computed from local request history only.
3504
+ */
3505
+ getReputation(): {
3506
+ success_rate: number;
3507
+ total_requests: number;
3508
+ };
3509
+ /**
3510
+ * Closes the credit database connection. Call when done.
3511
+ */
3512
+ close(): void;
3513
+ /** Lazily opens and caches the credit database. */
3514
+ private getCreditDb;
3520
3515
  }
3521
3516
 
3522
3517
  /**
3523
- * Registers WebSocket relay on an existing Fastify instance.
3524
- * Adds a `/ws` route that upgrades HTTP to WebSocket for agent relay.
3525
- *
3526
- * @param server - Fastify instance with @fastify/websocket already registered.
3527
- * @param db - Registry database instance.
3528
- * @returns RelayState for monitoring and graceful shutdown.
3518
+ * Options for constructing an AgentBnBProvider.
3529
3519
  */
3530
- declare function registerWebSocketRelay(server: FastifyInstance, db: Database.Database): RelayState;
3531
-
3532
- /** Result of handling an incoming relay request */
3533
- interface RelayHandlerResult {
3534
- result?: unknown;
3535
- error?: {
3536
- code: number;
3537
- message: string;
3538
- };
3520
+ interface ProviderOptions {
3521
+ /** Override the config directory (default: ~/.agentbnb or AGENTBNB_DIR). */
3522
+ configDir?: string;
3539
3523
  }
3540
- /** Options for the RelayClient constructor */
3541
- interface RelayClientOptions {
3542
- /** Registry WebSocket URL (e.g., "wss://hub.agentbnb.dev/ws") */
3543
- registryUrl: string;
3544
- /** Agent owner identifier */
3545
- owner: string;
3546
- /** Authentication token */
3547
- token: string;
3548
- /** Capability card data to register */
3549
- card: Record<string, unknown>;
3550
- /** Handler for incoming relay requests from other agents */
3551
- onRequest: (req: IncomingRequestMessage) => Promise<RelayHandlerResult>;
3552
- /** Suppress logging. Default false. */
3553
- silent?: boolean;
3524
+ /**
3525
+ * Options for starting the sharing gateway.
3526
+ */
3527
+ interface StartSharingOptions {
3528
+ /** Port to listen on (default: from config or 7700). */
3529
+ port?: number;
3530
+ /** Host to bind to (default: '0.0.0.0'). */
3531
+ host?: string;
3554
3532
  }
3555
- /** Options for making a relay request to another agent */
3556
- interface RelayRequestOptions$1 {
3557
- targetOwner: string;
3558
- cardId: string;
3559
- skillId?: string;
3560
- params: Record<string, unknown>;
3561
- requester?: string;
3562
- escrowReceipt?: Record<string, unknown>;
3563
- timeoutMs?: number;
3533
+ /**
3534
+ * Context returned after sharing starts.
3535
+ */
3536
+ interface SharingContext {
3537
+ /** The Fastify gateway server instance. */
3538
+ gateway: FastifyInstance;
3539
+ /** Port the gateway is listening on. */
3540
+ port: number;
3564
3541
  }
3565
3542
  /**
3566
- * WebSocket client for connecting to an AgentBnB registry relay.
3567
- * Handles registration, auto-reconnect, incoming requests, and outbound relay requests.
3543
+ * AgentBnBProvider high-level SDK class for agents providing capabilities.
3544
+ *
3545
+ * Manages identity, gateway lifecycle, and capability listing.
3546
+ *
3547
+ * @example
3548
+ * ```typescript
3549
+ * const provider = new AgentBnBProvider();
3550
+ * provider.authenticate();
3551
+ * const ctx = await provider.startSharing({ port: 7700 });
3552
+ * console.log(provider.listCapabilities());
3553
+ * await provider.stopSharing();
3554
+ * ```
3568
3555
  */
3569
- declare class RelayClient {
3570
- private ws;
3571
- private readonly opts;
3572
- private readonly pendingRequests;
3573
- private reconnectAttempts;
3574
- private reconnectTimer;
3575
- private intentionalClose;
3576
- private registered;
3577
- private pongTimeout;
3578
- private pingInterval;
3579
- constructor(opts: RelayClientOptions);
3556
+ declare class AgentBnBProvider {
3557
+ private configDir;
3558
+ private identity;
3559
+ private registryDb;
3560
+ private creditDb;
3561
+ private gateway;
3562
+ constructor(opts?: ProviderOptions);
3580
3563
  /**
3581
- * Connect to the registry relay and register.
3582
- * Resolves when registration is acknowledged.
3564
+ * Loads agent identity from disk.
3565
+ * Creates identity if none exists.
3566
+ *
3567
+ * @returns The loaded AgentIdentity.
3583
3568
  */
3584
- connect(): Promise<void>;
3569
+ authenticate(): AgentIdentity;
3585
3570
  /**
3586
- * Disconnect from the registry relay.
3571
+ * Returns the cached identity. Throws if not yet authenticated.
3587
3572
  */
3588
- disconnect(): void;
3573
+ getIdentity(): AgentIdentity;
3589
3574
  /**
3590
- * Send a relay request to another agent via the registry.
3591
- * @returns The result from the target agent.
3575
+ * Starts the gateway server to share capabilities.
3576
+ *
3577
+ * @param opts - Optional port and host configuration.
3578
+ * @returns Context with the gateway server and port.
3592
3579
  */
3593
- request(opts: RelayRequestOptions$1): Promise<unknown>;
3594
- /** Whether the client is connected and registered */
3595
- get isConnected(): boolean;
3596
- private buildWsUrl;
3597
- private handleMessage;
3598
- private handleIncomingRequest;
3599
- private handleResponse;
3600
- private handleError;
3601
- private send;
3602
- private startPingInterval;
3603
- private stopPingInterval;
3604
- private cleanup;
3605
- private scheduleReconnect;
3580
+ startSharing(opts?: StartSharingOptions): Promise<SharingContext>;
3581
+ /**
3582
+ * Stops the gateway server.
3583
+ */
3584
+ stopSharing(): Promise<void>;
3585
+ /**
3586
+ * Returns all capability cards owned by this agent.
3587
+ */
3588
+ listCapabilities(): CapabilityCard[];
3589
+ /**
3590
+ * Returns the current credit balance for this agent.
3591
+ */
3592
+ getBalance(): number;
3593
+ /**
3594
+ * Closes all database connections and stops the gateway. Call when done.
3595
+ */
3596
+ close(): Promise<void>;
3597
+ /** Lazily opens and caches the registry database. */
3598
+ private getRegistryDb;
3599
+ /** Lazily opens and caches the credit database. */
3600
+ private getCreditDb;
3606
3601
  }
3607
3602
 
3603
+ /** Maximum agents a single human guarantor can back. */
3604
+ declare const MAX_AGENTS_PER_GUARANTOR = 10;
3605
+ /** Free credits granted per human guarantor registration. */
3606
+ declare const GUARANTOR_CREDIT_POOL = 50;
3607
+ /**
3608
+ * A Human Guarantor — a real person backing one or more agents.
3609
+ * Provides initial trust and credit pool for the agent network.
3610
+ */
3611
+ declare const GuarantorRecordSchema: z.ZodObject<{
3612
+ id: z.ZodString;
3613
+ github_login: z.ZodString;
3614
+ agent_count: z.ZodNumber;
3615
+ credit_pool: z.ZodNumber;
3616
+ created_at: z.ZodString;
3617
+ }, "strip", z.ZodTypeAny, {
3618
+ id: string;
3619
+ created_at: string;
3620
+ github_login: string;
3621
+ agent_count: number;
3622
+ credit_pool: number;
3623
+ }, {
3624
+ id: string;
3625
+ created_at: string;
3626
+ github_login: string;
3627
+ agent_count: number;
3628
+ credit_pool: number;
3629
+ }>;
3630
+ type GuarantorRecord = z.infer<typeof GuarantorRecordSchema>;
3631
+ /**
3632
+ * Registers a new human guarantor via GitHub login.
3633
+ * Grants GUARANTOR_CREDIT_POOL (50) credits to be distributed among linked agents.
3634
+ *
3635
+ * @param db - The credit database instance.
3636
+ * @param githubLogin - GitHub username of the guarantor.
3637
+ * @returns The created GuarantorRecord.
3638
+ * @throws {AgentBnBError} with code 'GUARANTOR_EXISTS' if login already registered.
3639
+ */
3640
+ declare function registerGuarantor(db: Database.Database, githubLogin: string): GuarantorRecord;
3641
+ /**
3642
+ * Links an agent to a human guarantor.
3643
+ * Enforces the MAX_AGENTS_PER_GUARANTOR limit (10).
3644
+ *
3645
+ * @param db - The credit database instance.
3646
+ * @param agentId - The agent_id to link.
3647
+ * @param githubLogin - The guarantor's GitHub login.
3648
+ * @returns Updated GuarantorRecord.
3649
+ * @throws {AgentBnBError} with code 'GUARANTOR_NOT_FOUND' if login not registered.
3650
+ * @throws {AgentBnBError} with code 'MAX_AGENTS_EXCEEDED' if limit reached.
3651
+ * @throws {AgentBnBError} with code 'AGENT_ALREADY_LINKED' if agent already has a guarantor.
3652
+ */
3653
+ declare function linkAgentToGuarantor(db: Database.Database, agentId: string, githubLogin: string): GuarantorRecord;
3654
+ /**
3655
+ * Retrieves a guarantor record by GitHub login.
3656
+ *
3657
+ * @param db - The credit database instance.
3658
+ * @param githubLogin - The GitHub username to look up.
3659
+ * @returns GuarantorRecord or null if not found.
3660
+ */
3661
+ declare function getGuarantor(db: Database.Database, githubLogin: string): GuarantorRecord | null;
3662
+ /**
3663
+ * Gets the guarantor linked to an agent, if any.
3664
+ *
3665
+ * @param db - The credit database instance.
3666
+ * @param agentId - The agent_id to look up.
3667
+ * @returns GuarantorRecord or null if agent has no guarantor.
3668
+ */
3669
+ declare function getAgentGuarantor(db: Database.Database, agentId: string): GuarantorRecord | null;
3670
+ /**
3671
+ * Initiates a GitHub OAuth flow for guarantor verification.
3672
+ * This is a STUB — returns placeholder values. Actual OAuth implementation
3673
+ * is deferred to a future version.
3674
+ *
3675
+ * @returns Object with auth_url and state for the OAuth flow.
3676
+ */
3677
+ declare function initiateGithubAuth(): {
3678
+ auth_url: string;
3679
+ state: string;
3680
+ };
3681
+
3682
+ /**
3683
+ * Registers WebSocket relay on an existing Fastify instance.
3684
+ * Adds a `/ws` route that upgrades HTTP to WebSocket for agent relay.
3685
+ *
3686
+ * @param server - Fastify instance with @fastify/websocket already registered.
3687
+ * @param db - Registry database instance (for card lookups and online status).
3688
+ * @param creditDb - Optional credit database. When provided, credits are held
3689
+ * before forwarding requests, settled on success, and released on failure/timeout/disconnect.
3690
+ * When undefined, all credit operations are skipped (backward compat for tests).
3691
+ * @returns RelayState for monitoring and graceful shutdown.
3692
+ */
3693
+ declare function registerWebSocketRelay(server: FastifyInstance, db: Database.Database, creditDb?: Database.Database): RelayState;
3694
+
3608
3695
  /**
3609
3696
  * Options for executing a capability request.
3610
3697
  * Used by both the HTTP /rpc handler and WebSocket relay.
@@ -3620,6 +3707,8 @@ interface ExecuteRequestOptions {
3620
3707
  skillExecutor?: SkillExecutor;
3621
3708
  handlerUrl?: string;
3622
3709
  timeoutMs?: number;
3710
+ /** Optional progress callback forwarded to SkillExecutor during execution. */
3711
+ onProgress?: ProgressCallback;
3623
3712
  }
3624
3713
  /**
3625
3714
  * Result of a capability execution.