agentbnb 4.0.0 → 4.0.2

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 (44) hide show
  1. package/README.md +2 -0
  2. package/dist/{card-IE5UV5QX.js → card-RSGDCHCV.js} +11 -4
  3. package/dist/chunk-3MJT4PZG.js +50 -0
  4. package/dist/{chunk-HEVXCYCY.js → chunk-4P3EMGL4.js} +61 -24
  5. package/dist/chunk-5AH3CMOX.js +62 -0
  6. package/dist/{chunk-QO67IGCW.js → chunk-5KFI5X7B.js} +1 -1
  7. package/dist/chunk-75OC6E4F.js +33 -0
  8. package/dist/{chunk-CUVIWPQO.js → chunk-7NA43XCG.js} +7 -6
  9. package/dist/{conduct-IQYAT6ZU.js → chunk-BH6WGYFB.js} +70 -33
  10. package/dist/{chunk-QVV2P3FN.js → chunk-DNWT5FZQ.js} +22 -2
  11. package/dist/chunk-FF226TIV.js +148 -0
  12. package/dist/{chunk-UJWYE7VL.js → chunk-GGYC5U2Z.js} +28 -111
  13. package/dist/chunk-HH24WMFN.js +373 -0
  14. package/dist/{websocket-client-5TIQDYQ4.js → chunk-JOY533UH.js} +38 -4
  15. package/dist/chunk-QITOPASZ.js +96 -0
  16. package/dist/{chunk-3Y36WQDV.js → chunk-QT7TEVNV.js} +14 -2
  17. package/dist/{chunk-UOGDK2S2.js → chunk-T7NS2J2B.js} +1 -1
  18. package/dist/{chunk-XA63SD4T.js → chunk-WGZ5AGOX.js} +37 -0
  19. package/dist/{chunk-RSX4SCPN.js → chunk-XND2DWTZ.js} +4 -3
  20. package/dist/cli/index.js +2924 -835
  21. package/dist/{client-IOTK6GOS.js → client-T5MTY3CS.js} +3 -3
  22. package/dist/conduct-GZQNFTRP.js +19 -0
  23. package/dist/conduct-N52JX7RT.js +52 -0
  24. package/dist/{conductor-mode-XU7ONJWC.js → conductor-mode-XUWGR4ZE.js} +16 -9
  25. package/dist/execute-PNGQOMYO.js +10 -0
  26. package/dist/index.d.ts +1148 -915
  27. package/dist/index.js +589 -127
  28. package/dist/{peers-G36URZYB.js → peers-K7FSHPN3.js} +2 -1
  29. package/dist/request-4GQSSM4B.js +196 -0
  30. package/dist/serve-skill-TPHZH6BS.js +104 -0
  31. package/dist/server-365V3GYD.js +295 -0
  32. package/dist/websocket-client-6IIDGXKB.js +7 -0
  33. package/package.json +3 -6
  34. package/skills/agentbnb/HEARTBEAT.rules.md +47 -0
  35. package/skills/agentbnb/SKILL.md +166 -0
  36. package/skills/agentbnb/auto-request.ts +14 -0
  37. package/skills/agentbnb/auto-share.ts +10 -0
  38. package/skills/agentbnb/bootstrap.test.ts +323 -0
  39. package/skills/agentbnb/bootstrap.ts +126 -0
  40. package/skills/agentbnb/credit-mgr.ts +11 -0
  41. package/skills/agentbnb/gateway.ts +12 -0
  42. package/skills/agentbnb/install.sh +210 -0
  43. package/dist/chunk-BEI5MTNZ.js +0 -91
  44. package/dist/execute-GDGBU6DJ.js +0 -10
package/dist/index.d.ts CHANGED
@@ -220,6 +220,8 @@ declare const CapabilityCardV2Schema: z.ZodObject<{
220
220
  owner: z.ZodString;
221
221
  /** Agent display name — was 'name' in v1.0. */
222
222
  agent_name: z.ZodString;
223
+ /** Short one-liner shown in Hub v2 Identity Header. */
224
+ short_description: z.ZodOptional<z.ZodString>;
223
225
  /** At least one skill is required. */
224
226
  skills: z.ZodArray<z.ZodObject<{
225
227
  /** Stable skill identifier, e.g. 'tts-elevenlabs'. Used for gateway routing and idle tracking. */
@@ -443,6 +445,97 @@ declare const CapabilityCardV2Schema: z.ZodObject<{
443
445
  runtime: string;
444
446
  region?: string | undefined;
445
447
  }>>;
448
+ /** Suitability metadata for Hub v2 profile and future routing warnings. */
449
+ suitability: z.ZodOptional<z.ZodObject<{
450
+ /** Use cases this agent/skill is optimised for. */
451
+ ideal_for: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
452
+ /** Scenarios this agent/skill cannot reliably handle. */
453
+ not_suitable_for: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
454
+ /** Domains explicitly excluded (used for routing exclusions in later phases). */
455
+ excluded_domains: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
456
+ /** Conditions that increase failure risk, shown as warnings in the Hub. */
457
+ risk_conditions: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
458
+ /** Recommended alternative when this agent is unsuitable. */
459
+ fallback_recommendation: z.ZodOptional<z.ZodString>;
460
+ }, "strip", z.ZodTypeAny, {
461
+ ideal_for?: string[] | undefined;
462
+ not_suitable_for?: string[] | undefined;
463
+ excluded_domains?: string[] | undefined;
464
+ risk_conditions?: string[] | undefined;
465
+ fallback_recommendation?: string | undefined;
466
+ }, {
467
+ ideal_for?: string[] | undefined;
468
+ not_suitable_for?: string[] | undefined;
469
+ excluded_domains?: string[] | undefined;
470
+ risk_conditions?: string[] | undefined;
471
+ fallback_recommendation?: string | undefined;
472
+ }>>;
473
+ /** Learning signals — self-declared limitations, improvements, critiques. */
474
+ learning: z.ZodOptional<z.ZodObject<{
475
+ /** Known limitations that may affect reliability (self-declared). */
476
+ known_limitations: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
477
+ /** Common failure patterns observed by the provider. */
478
+ common_failure_patterns: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
479
+ /** Version-tagged improvements the provider has shipped. */
480
+ recent_improvements: z.ZodOptional<z.ZodArray<z.ZodObject<{
481
+ version: z.ZodString;
482
+ summary: z.ZodString;
483
+ timestamp: z.ZodString;
484
+ }, "strip", z.ZodTypeAny, {
485
+ version: string;
486
+ summary: string;
487
+ timestamp: string;
488
+ }, {
489
+ version: string;
490
+ summary: string;
491
+ timestamp: string;
492
+ }>, "many">>;
493
+ /** Structured critiques from external sources (phase 2+). */
494
+ critiques: z.ZodOptional<z.ZodArray<z.ZodObject<{
495
+ type: z.ZodLiteral<"structured">;
496
+ summary: z.ZodString;
497
+ source_tier: z.ZodString;
498
+ timestamp: z.ZodString;
499
+ }, "strip", z.ZodTypeAny, {
500
+ type: "structured";
501
+ summary: string;
502
+ timestamp: string;
503
+ source_tier: string;
504
+ }, {
505
+ type: "structured";
506
+ summary: string;
507
+ timestamp: string;
508
+ source_tier: string;
509
+ }>, "many">>;
510
+ }, "strip", z.ZodTypeAny, {
511
+ known_limitations?: string[] | undefined;
512
+ common_failure_patterns?: string[] | undefined;
513
+ recent_improvements?: {
514
+ version: string;
515
+ summary: string;
516
+ timestamp: string;
517
+ }[] | undefined;
518
+ critiques?: {
519
+ type: "structured";
520
+ summary: string;
521
+ timestamp: string;
522
+ source_tier: string;
523
+ }[] | undefined;
524
+ }, {
525
+ known_limitations?: string[] | undefined;
526
+ common_failure_patterns?: string[] | undefined;
527
+ recent_improvements?: {
528
+ version: string;
529
+ summary: string;
530
+ timestamp: string;
531
+ }[] | undefined;
532
+ critiques?: {
533
+ type: "structured";
534
+ summary: string;
535
+ timestamp: string;
536
+ source_tier: string;
537
+ }[] | undefined;
538
+ }>>;
446
539
  /**
447
540
  * Private per-card metadata. Stripped from all API and CLI responses —
448
541
  * never transmitted beyond the local store.
@@ -509,10 +602,33 @@ declare const CapabilityCardV2Schema: z.ZodObject<{
509
602
  gateway_url?: string | undefined;
510
603
  created_at?: string | undefined;
511
604
  updated_at?: string | undefined;
605
+ short_description?: string | undefined;
512
606
  environment?: {
513
607
  runtime: string;
514
608
  region?: string | undefined;
515
609
  } | undefined;
610
+ suitability?: {
611
+ ideal_for?: string[] | undefined;
612
+ not_suitable_for?: string[] | undefined;
613
+ excluded_domains?: string[] | undefined;
614
+ risk_conditions?: string[] | undefined;
615
+ fallback_recommendation?: string | undefined;
616
+ } | undefined;
617
+ learning?: {
618
+ known_limitations?: string[] | undefined;
619
+ common_failure_patterns?: string[] | undefined;
620
+ recent_improvements?: {
621
+ version: string;
622
+ summary: string;
623
+ timestamp: string;
624
+ }[] | undefined;
625
+ critiques?: {
626
+ type: "structured";
627
+ summary: string;
628
+ timestamp: string;
629
+ source_tier: string;
630
+ }[] | undefined;
631
+ } | undefined;
516
632
  }, {
517
633
  spec_version: "2.0";
518
634
  id: string;
@@ -570,10 +686,33 @@ declare const CapabilityCardV2Schema: z.ZodObject<{
570
686
  gateway_url?: string | undefined;
571
687
  created_at?: string | undefined;
572
688
  updated_at?: string | undefined;
689
+ short_description?: string | undefined;
573
690
  environment?: {
574
691
  runtime: string;
575
692
  region?: string | undefined;
576
693
  } | undefined;
694
+ suitability?: {
695
+ ideal_for?: string[] | undefined;
696
+ not_suitable_for?: string[] | undefined;
697
+ excluded_domains?: string[] | undefined;
698
+ risk_conditions?: string[] | undefined;
699
+ fallback_recommendation?: string | undefined;
700
+ } | undefined;
701
+ learning?: {
702
+ known_limitations?: string[] | undefined;
703
+ common_failure_patterns?: string[] | undefined;
704
+ recent_improvements?: {
705
+ version: string;
706
+ summary: string;
707
+ timestamp: string;
708
+ }[] | undefined;
709
+ critiques?: {
710
+ type: "structured";
711
+ summary: string;
712
+ timestamp: string;
713
+ source_tier: string;
714
+ }[] | undefined;
715
+ } | undefined;
577
716
  }>;
578
717
  type CapabilityCardV2 = z.infer<typeof CapabilityCardV2Schema>;
579
718
  /**
@@ -1874,6 +2013,15 @@ declare function expandEnvVars(value: string): string;
1874
2013
  */
1875
2014
  declare function parseSkillsFile(yamlContent: string): SkillConfig[];
1876
2015
 
2016
+ /**
2017
+ * Progress callback for long-running skill executions.
2018
+ * Called between steps/sub-tasks to indicate forward progress.
2019
+ */
2020
+ type ProgressCallback = (info: {
2021
+ step: number;
2022
+ total: number;
2023
+ message: string;
2024
+ }) => void;
1877
2025
  /**
1878
2026
  * Result returned by SkillExecutor.execute() for every invocation.
1879
2027
  * Always includes timing data regardless of success or failure.
@@ -1900,7 +2048,7 @@ interface ExecutorMode {
1900
2048
  * @param params - The input parameters passed by the caller.
1901
2049
  * @returns A partial ExecutionResult without latency_ms (added by SkillExecutor).
1902
2050
  */
1903
- execute(config: SkillConfig, params: Record<string, unknown>): Promise<Omit<ExecutionResult, 'latency_ms'>>;
2051
+ execute(config: SkillConfig, params: Record<string, unknown>, onProgress?: ProgressCallback): Promise<Omit<ExecutionResult, 'latency_ms'>>;
1904
2052
  }
1905
2053
  /**
1906
2054
  * Central dispatcher that routes skill execution requests to the appropriate
@@ -1933,7 +2081,7 @@ declare class SkillExecutor {
1933
2081
  * @param params - Input parameters for the skill.
1934
2082
  * @returns ExecutionResult including success, result/error, and latency_ms.
1935
2083
  */
1936
- execute(skillId: string, params: Record<string, unknown>): Promise<ExecutionResult>;
2084
+ execute(skillId: string, params: Record<string, unknown>, onProgress?: ProgressCallback): Promise<ExecutionResult>;
1937
2085
  /**
1938
2086
  * Returns the IDs of all registered skills.
1939
2087
  *
@@ -2087,7 +2235,7 @@ declare class PipelineExecutor implements ExecutorMode {
2087
2235
  * @param params - Input parameters from the caller.
2088
2236
  * @returns Partial ExecutionResult (without latency_ms — added by SkillExecutor wrapper).
2089
2237
  */
2090
- execute(config: SkillConfig, params: Record<string, unknown>): Promise<Omit<ExecutionResult, 'latency_ms'>>;
2238
+ execute(config: SkillConfig, params: Record<string, unknown>, onProgress?: ProgressCallback): Promise<Omit<ExecutionResult, 'latency_ms'>>;
2091
2239
  }
2092
2240
 
2093
2241
  /**
@@ -2214,6 +2362,8 @@ interface MatchResult {
2214
2362
  selected_agent: string;
2215
2363
  /** Skill ID on the selected agent's card. */
2216
2364
  selected_skill: string;
2365
+ /** Capability card ID of the selected agent. Used for relay execution of remote agents. */
2366
+ selected_card_id?: string;
2217
2367
  /** Match quality score (0-1). */
2218
2368
  score: number;
2219
2369
  /** Negotiated credit cost. */
@@ -2314,6 +2464,8 @@ interface MatchOptions {
2314
2464
  subtasks: SubTask[];
2315
2465
  /** Owner ID of the conductor agent — excluded from matches (self-exclusion). */
2316
2466
  conductorOwner: string;
2467
+ /** Optional remote registry URL for fallback when local search returns no results. */
2468
+ registryUrl?: string;
2317
2469
  }
2318
2470
  /**
2319
2471
  * Finds the best agent for each sub-task using registry FTS search and peer scoring.
@@ -2329,7 +2481,7 @@ interface MatchOptions {
2329
2481
  * @param opts - Match configuration including database, subtasks, and conductor owner ID.
2330
2482
  * @returns MatchResult[] in the same order as the input subtasks.
2331
2483
  */
2332
- declare function matchSubTasks(opts: MatchOptions): MatchResult[];
2484
+ declare function matchSubTasks(opts: MatchOptions): Promise<MatchResult[]>;
2333
2485
 
2334
2486
  /**
2335
2487
  * Configuration for credit budget enforcement.
@@ -2467,11 +2619,16 @@ declare const CONDUCTOR_OWNER = "agentbnb-conductor";
2467
2619
  * - `orchestrate` (5 cr): Decomposes and executes multi-agent tasks
2468
2620
  * - `plan` (1 cr): Returns an execution plan with cost estimate only
2469
2621
  *
2622
+ * When `owner` is provided, the card is attributed to that agent owner
2623
+ * with a deterministic owner-specific ID. When omitted, uses the default
2624
+ * singleton CONDUCTOR_OWNER and fixed UUID.
2625
+ *
2470
2626
  * The returned card is validated against CapabilityCardV2Schema before return.
2471
2627
  *
2628
+ * @param owner - Optional agent owner. When provided, card is owner-specific.
2472
2629
  * @returns A valid CapabilityCardV2 for the Conductor.
2473
2630
  */
2474
- declare function buildConductorCard(): CapabilityCardV2;
2631
+ declare function buildConductorCard(owner?: string): CapabilityCardV2;
2475
2632
  /**
2476
2633
  * Registers the Conductor card in the given SQLite database.
2477
2634
  *
@@ -2485,719 +2642,199 @@ declare function buildConductorCard(): CapabilityCardV2;
2485
2642
  declare function registerConductorCard(db: Database.Database): CapabilityCardV2;
2486
2643
 
2487
2644
  /**
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.
2645
+ * WebSocket relay message types for agent-to-registry communication.
2646
+ * All messages are JSON-encoded with a discriminating `type` field.
2645
2647
  */
2646
- declare const EscrowReceiptSchema: z.ZodObject<{
2647
- requester_owner: z.ZodString;
2648
- requester_public_key: z.ZodString;
2649
- amount: z.ZodNumber;
2648
+ /** Agent → Registry: Register agent and card on connect */
2649
+ declare const RegisterMessageSchema: z.ZodObject<{
2650
+ type: z.ZodLiteral<"register">;
2651
+ owner: z.ZodString;
2652
+ token: z.ZodString;
2653
+ card: z.ZodRecord<z.ZodString, z.ZodUnknown>;
2654
+ cards: z.ZodOptional<z.ZodArray<z.ZodRecord<z.ZodString, z.ZodUnknown>, "many">>;
2655
+ }, "strip", z.ZodTypeAny, {
2656
+ type: "register";
2657
+ owner: string;
2658
+ token: string;
2659
+ card: Record<string, unknown>;
2660
+ cards?: Record<string, unknown>[] | undefined;
2661
+ }, {
2662
+ type: "register";
2663
+ owner: string;
2664
+ token: string;
2665
+ card: Record<string, unknown>;
2666
+ cards?: Record<string, unknown>[] | undefined;
2667
+ }>;
2668
+ /** Registry → Agent: Acknowledge registration */
2669
+ declare const RegisteredMessageSchema: z.ZodObject<{
2670
+ type: z.ZodLiteral<"registered">;
2671
+ agent_id: z.ZodString;
2672
+ }, "strip", z.ZodTypeAny, {
2673
+ type: "registered";
2674
+ agent_id: string;
2675
+ }, {
2676
+ type: "registered";
2677
+ agent_id: string;
2678
+ }>;
2679
+ /** Agent A → Registry: Request relay to another agent */
2680
+ declare const RelayRequestMessageSchema: z.ZodObject<{
2681
+ type: z.ZodLiteral<"relay_request">;
2682
+ id: z.ZodString;
2683
+ target_owner: z.ZodString;
2650
2684
  card_id: z.ZodString;
2651
2685
  skill_id: z.ZodOptional<z.ZodString>;
2652
- timestamp: z.ZodString;
2653
- nonce: z.ZodString;
2654
- signature: z.ZodString;
2686
+ params: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
2687
+ requester: z.ZodOptional<z.ZodString>;
2688
+ escrow_receipt: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
2655
2689
  }, "strip", z.ZodTypeAny, {
2656
- signature: string;
2657
- requester_owner: string;
2658
- requester_public_key: string;
2659
- amount: number;
2690
+ type: "relay_request";
2691
+ params: Record<string, unknown>;
2692
+ id: string;
2660
2693
  card_id: string;
2661
- timestamp: string;
2662
- nonce: string;
2694
+ target_owner: string;
2663
2695
  skill_id?: string | undefined;
2696
+ requester?: string | undefined;
2697
+ escrow_receipt?: Record<string, unknown> | undefined;
2664
2698
  }, {
2665
- signature: string;
2666
- requester_owner: string;
2667
- requester_public_key: string;
2668
- amount: number;
2699
+ type: "relay_request";
2700
+ id: string;
2669
2701
  card_id: string;
2670
- timestamp: string;
2671
- nonce: string;
2702
+ target_owner: string;
2703
+ params?: Record<string, unknown> | undefined;
2672
2704
  skill_id?: string | undefined;
2705
+ requester?: string | undefined;
2706
+ escrow_receipt?: Record<string, unknown> | undefined;
2673
2707
  }>;
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;
2708
+ /** Registry → Agent B: Incoming request forwarded from Agent A */
2709
+ declare const IncomingRequestMessageSchema: z.ZodObject<{
2710
+ type: z.ZodLiteral<"incoming_request">;
2711
+ id: z.ZodString;
2712
+ from_owner: z.ZodString;
2713
+ card_id: z.ZodString;
2714
+ skill_id: z.ZodOptional<z.ZodString>;
2715
+ params: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
2716
+ requester: z.ZodOptional<z.ZodString>;
2717
+ escrow_receipt: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
2718
+ }, "strip", z.ZodTypeAny, {
2719
+ type: "incoming_request";
2720
+ params: Record<string, unknown>;
2721
+ id: string;
2722
+ card_id: string;
2723
+ from_owner: string;
2724
+ skill_id?: string | undefined;
2725
+ requester?: string | undefined;
2726
+ escrow_receipt?: Record<string, unknown> | undefined;
2727
+ }, {
2728
+ type: "incoming_request";
2729
+ id: string;
2730
+ card_id: string;
2731
+ from_owner: string;
2732
+ params?: Record<string, unknown> | undefined;
2733
+ skill_id?: string | undefined;
2734
+ requester?: string | undefined;
2735
+ escrow_receipt?: Record<string, unknown> | undefined;
2736
+ }>;
2737
+ /** Agent B → Registry: Response to a relayed request */
2738
+ declare const RelayResponseMessageSchema: z.ZodObject<{
2739
+ type: z.ZodLiteral<"relay_response">;
2740
+ id: z.ZodString;
2741
+ result: z.ZodOptional<z.ZodUnknown>;
2742
+ error: z.ZodOptional<z.ZodObject<{
2743
+ code: z.ZodNumber;
2744
+ message: z.ZodString;
2755
2745
  }, "strip", z.ZodTypeAny, {
2756
- github_login: string;
2757
- verified_at: string;
2746
+ code: number;
2747
+ message: string;
2758
2748
  }, {
2759
- github_login: string;
2760
- verified_at: string;
2749
+ code: number;
2750
+ message: string;
2761
2751
  }>>;
2762
2752
  }, "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;
2753
+ type: "relay_response";
2754
+ id: string;
2755
+ result?: unknown;
2756
+ error?: {
2757
+ code: number;
2758
+ message: string;
2770
2759
  } | undefined;
2771
2760
  }, {
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;
2761
+ type: "relay_response";
2762
+ id: string;
2763
+ result?: unknown;
2764
+ error?: {
2765
+ code: number;
2766
+ message: string;
2779
2767
  } | undefined;
2780
2768
  }>;
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
- }>>;
2769
+ /** Registry Agent A: Forwarded response from Agent B */
2770
+ declare const ResponseMessageSchema: z.ZodObject<{
2771
+ type: z.ZodLiteral<"response">;
2772
+ id: z.ZodString;
2773
+ result: z.ZodOptional<z.ZodUnknown>;
2774
+ error: z.ZodOptional<z.ZodObject<{
2775
+ code: z.ZodNumber;
2776
+ message: z.ZodString;
2807
2777
  }, "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;
2778
+ code: number;
2779
+ message: string;
2816
2780
  }, {
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;
2781
+ code: number;
2782
+ message: string;
2783
+ }>>;
2834
2784
  }, "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;
2849
- }, {
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;
2864
- }>;
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;
2785
+ type: "response";
2786
+ id: string;
2787
+ result?: unknown;
2788
+ error?: {
2789
+ code: number;
2790
+ message: string;
2791
+ } | undefined;
3119
2792
  }, {
2793
+ type: "response";
3120
2794
  id: string;
3121
- created_at: string;
3122
- github_login: string;
3123
- agent_count: number;
3124
- credit_pool: number;
2795
+ result?: unknown;
2796
+ error?: {
2797
+ code: number;
2798
+ message: string;
2799
+ } | undefined;
3125
2800
  }>;
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<{
2801
+ /** Error message (either direction) */
2802
+ declare const ErrorMessageSchema: z.ZodObject<{
2803
+ type: z.ZodLiteral<"error">;
2804
+ code: z.ZodString;
2805
+ message: z.ZodString;
2806
+ request_id: z.ZodOptional<z.ZodString>;
2807
+ }, "strip", z.ZodTypeAny, {
2808
+ type: "error";
2809
+ code: string;
2810
+ message: string;
2811
+ request_id?: string | undefined;
2812
+ }, {
2813
+ type: "error";
2814
+ code: string;
2815
+ message: string;
2816
+ request_id?: string | undefined;
2817
+ }>;
2818
+ /** Discriminated union of all relay messages */
2819
+ declare const RelayMessageSchema: z.ZodDiscriminatedUnion<"type", [z.ZodObject<{
3184
2820
  type: z.ZodLiteral<"register">;
3185
2821
  owner: z.ZodString;
3186
2822
  token: z.ZodString;
3187
2823
  card: z.ZodRecord<z.ZodString, z.ZodUnknown>;
2824
+ cards: z.ZodOptional<z.ZodArray<z.ZodRecord<z.ZodString, z.ZodUnknown>, "many">>;
3188
2825
  }, "strip", z.ZodTypeAny, {
3189
2826
  type: "register";
3190
2827
  owner: string;
3191
2828
  token: string;
3192
2829
  card: Record<string, unknown>;
2830
+ cards?: Record<string, unknown>[] | undefined;
3193
2831
  }, {
3194
2832
  type: "register";
3195
2833
  owner: string;
3196
2834
  token: string;
3197
2835
  card: Record<string, unknown>;
3198
- }>;
3199
- /** Registry → Agent: Acknowledge registration */
3200
- declare const RegisteredMessageSchema: z.ZodObject<{
2836
+ cards?: Record<string, unknown>[] | undefined;
2837
+ }>, z.ZodObject<{
3201
2838
  type: z.ZodLiteral<"registered">;
3202
2839
  agent_id: z.ZodString;
3203
2840
  }, "strip", z.ZodTypeAny, {
@@ -3206,9 +2843,7 @@ declare const RegisteredMessageSchema: z.ZodObject<{
3206
2843
  }, {
3207
2844
  type: "registered";
3208
2845
  agent_id: string;
3209
- }>;
3210
- /** Agent A → Registry: Request relay to another agent */
3211
- declare const RelayRequestMessageSchema: z.ZodObject<{
2846
+ }>, z.ZodObject<{
3212
2847
  type: z.ZodLiteral<"relay_request">;
3213
2848
  id: z.ZodString;
3214
2849
  target_owner: z.ZodString;
@@ -3235,9 +2870,7 @@ declare const RelayRequestMessageSchema: z.ZodObject<{
3235
2870
  skill_id?: string | undefined;
3236
2871
  requester?: string | undefined;
3237
2872
  escrow_receipt?: Record<string, unknown> | undefined;
3238
- }>;
3239
- /** Registry → Agent B: Incoming request forwarded from Agent A */
3240
- declare const IncomingRequestMessageSchema: z.ZodObject<{
2873
+ }>, z.ZodObject<{
3241
2874
  type: z.ZodLiteral<"incoming_request">;
3242
2875
  id: z.ZodString;
3243
2876
  from_owner: z.ZodString;
@@ -3264,9 +2897,7 @@ declare const IncomingRequestMessageSchema: z.ZodObject<{
3264
2897
  skill_id?: string | undefined;
3265
2898
  requester?: string | undefined;
3266
2899
  escrow_receipt?: Record<string, unknown> | undefined;
3267
- }>;
3268
- /** Agent B → Registry: Response to a relayed request */
3269
- declare const RelayResponseMessageSchema: z.ZodObject<{
2900
+ }>, z.ZodObject<{
3270
2901
  type: z.ZodLiteral<"relay_response">;
3271
2902
  id: z.ZodString;
3272
2903
  result: z.ZodOptional<z.ZodUnknown>;
@@ -3296,9 +2927,7 @@ declare const RelayResponseMessageSchema: z.ZodObject<{
3296
2927
  code: number;
3297
2928
  message: string;
3298
2929
  } | undefined;
3299
- }>;
3300
- /** Registry → Agent A: Forwarded response from Agent B */
3301
- declare const ResponseMessageSchema: z.ZodObject<{
2930
+ }>, z.ZodObject<{
3302
2931
  type: z.ZodLiteral<"response">;
3303
2932
  id: z.ZodString;
3304
2933
  result: z.ZodOptional<z.ZodUnknown>;
@@ -3328,9 +2957,7 @@ declare const ResponseMessageSchema: z.ZodObject<{
3328
2957
  code: number;
3329
2958
  message: string;
3330
2959
  } | undefined;
3331
- }>;
3332
- /** Error message (either direction) */
3333
- declare const ErrorMessageSchema: z.ZodObject<{
2960
+ }>, z.ZodObject<{
3334
2961
  type: z.ZodLiteral<"error">;
3335
2962
  code: z.ZodString;
3336
2963
  message: z.ZodString;
@@ -3345,266 +2972,868 @@ declare const ErrorMessageSchema: z.ZodObject<{
3345
2972
  code: string;
3346
2973
  message: string;
3347
2974
  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
2975
  }>, z.ZodObject<{
3375
- type: z.ZodLiteral<"relay_request">;
2976
+ type: z.ZodLiteral<"relay_progress">;
3376
2977
  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>>;
2978
+ progress: z.ZodOptional<z.ZodNumber>;
2979
+ message: z.ZodOptional<z.ZodString>;
3383
2980
  }, "strip", z.ZodTypeAny, {
3384
- type: "relay_request";
3385
- params: Record<string, unknown>;
2981
+ type: "relay_progress";
3386
2982
  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;
2983
+ message?: string | undefined;
2984
+ progress?: number | undefined;
3392
2985
  }, {
3393
- type: "relay_request";
2986
+ type: "relay_progress";
3394
2987
  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;
2988
+ message?: string | undefined;
2989
+ progress?: number | undefined;
2990
+ }>]>;
2991
+ type RegisterMessage = z.infer<typeof RegisterMessageSchema>;
2992
+ type RegisteredMessage = z.infer<typeof RegisteredMessageSchema>;
2993
+ type RelayRequestMessage = z.infer<typeof RelayRequestMessageSchema>;
2994
+ type IncomingRequestMessage = z.infer<typeof IncomingRequestMessageSchema>;
2995
+ type RelayResponseMessage = z.infer<typeof RelayResponseMessageSchema>;
2996
+ type ResponseMessage = z.infer<typeof ResponseMessageSchema>;
2997
+ type ErrorMessage = z.infer<typeof ErrorMessageSchema>;
2998
+ type RelayMessage = z.infer<typeof RelayMessageSchema>;
2999
+ /** Pending relay request tracking */
3000
+ interface PendingRelayRequest {
3001
+ /** Connection key used to route the response back (may be a synthetic ID) */
3002
+ originOwner: string;
3003
+ /** Actual agent owner for credit operations (defaults to originOwner) */
3004
+ creditOwner?: string;
3005
+ timeout: ReturnType<typeof setTimeout>;
3006
+ /** Escrow ID for the credit hold, if credits were reserved for this request */
3007
+ escrowId?: string;
3008
+ /** The target provider owner, needed to release escrow on provider disconnect */
3009
+ targetOwner?: string;
3010
+ /** Job ID if this request was dispatched from the job queue (relay bridge) */
3011
+ jobId?: string;
3012
+ }
3013
+ /** Relay server state returned from registerWebSocketRelay */
3014
+ interface RelayState {
3015
+ /** Number of currently connected agents */
3016
+ getOnlineCount(): number;
3017
+ /** List of connected agent owners */
3018
+ getOnlineOwners(): string[];
3019
+ /** Graceful shutdown -- close all connections */
3020
+ shutdown(): void;
3021
+ /** Set a callback invoked when an agent registers (comes online) */
3022
+ setOnAgentOnline?(cb: (owner: string) => void): void;
3023
+ /** Get the active connections map (owner -> WebSocket) */
3024
+ getConnections?(): Map<string, unknown>;
3025
+ /** Get the pending requests map */
3026
+ getPendingRequests?(): Map<string, PendingRelayRequest>;
3027
+ /** Send a JSON message over a WebSocket */
3028
+ sendMessage?(ws: unknown, msg: Record<string, unknown>): void;
3029
+ }
3030
+
3031
+ /** Result of handling an incoming relay request */
3032
+ interface RelayHandlerResult {
3033
+ result?: unknown;
3034
+ error?: {
3035
+ code: number;
3036
+ message: string;
3037
+ };
3038
+ }
3039
+ /** Options for the RelayClient constructor */
3040
+ interface RelayClientOptions {
3041
+ /** Registry WebSocket URL (e.g., "wss://hub.agentbnb.dev/ws") */
3042
+ registryUrl: string;
3043
+ /** Agent owner identifier */
3044
+ owner: string;
3045
+ /** Authentication token */
3046
+ token: string;
3047
+ /** Capability card data to register */
3048
+ card: Record<string, unknown>;
3049
+ /** Additional cards to register alongside the primary card (e.g., conductor card) */
3050
+ cards?: Record<string, unknown>[];
3051
+ /** Handler for incoming relay requests from other agents */
3052
+ onRequest: (req: IncomingRequestMessage) => Promise<RelayHandlerResult>;
3053
+ /** Suppress logging. Default false. */
3054
+ silent?: boolean;
3055
+ }
3056
+ /** Options for making a relay request to another agent */
3057
+ interface RelayRequestOptions$1 {
3058
+ targetOwner: string;
3059
+ cardId: string;
3060
+ skillId?: string;
3061
+ params: Record<string, unknown>;
3062
+ requester?: string;
3063
+ escrowReceipt?: Record<string, unknown>;
3064
+ timeoutMs?: number;
3065
+ /** Optional callback invoked when the provider sends relay_progress heartbeats. */
3066
+ onProgress?: (progress: {
3067
+ id: string;
3068
+ progress?: number;
3069
+ message?: string;
3070
+ }) => void;
3071
+ }
3072
+ /**
3073
+ * WebSocket client for connecting to an AgentBnB registry relay.
3074
+ * Handles registration, auto-reconnect, incoming requests, and outbound relay requests.
3075
+ */
3076
+ declare class RelayClient {
3077
+ private ws;
3078
+ private readonly opts;
3079
+ private readonly pendingRequests;
3080
+ private reconnectAttempts;
3081
+ private reconnectTimer;
3082
+ private intentionalClose;
3083
+ private registered;
3084
+ private pongTimeout;
3085
+ private pingInterval;
3086
+ constructor(opts: RelayClientOptions);
3087
+ /**
3088
+ * Connect to the registry relay and register.
3089
+ * Resolves when registration is acknowledged.
3090
+ */
3091
+ connect(): Promise<void>;
3092
+ /**
3093
+ * Disconnect from the registry relay.
3094
+ */
3095
+ disconnect(): void;
3096
+ /**
3097
+ * Send a relay request to another agent via the registry.
3098
+ * @returns The result from the target agent.
3099
+ */
3100
+ request(opts: RelayRequestOptions$1): Promise<unknown>;
3101
+ /**
3102
+ * Send a relay_progress message to the relay server for a given request.
3103
+ * Used by the onRequest handler to forward SkillExecutor progress updates
3104
+ * to the requesting agent so it can reset its timeout window.
3105
+ *
3106
+ * @param requestId - The relay request ID to associate progress with.
3107
+ * @param info - Progress details (step, total, message).
3108
+ */
3109
+ sendProgress(requestId: string, info: {
3110
+ step: number;
3111
+ total: number;
3112
+ message: string;
3113
+ }): void;
3114
+ /** Whether the client is connected and registered */
3115
+ get isConnected(): boolean;
3116
+ private buildWsUrl;
3117
+ private handleMessage;
3118
+ private handleIncomingRequest;
3119
+ private handleResponse;
3120
+ private handleError;
3121
+ private handleProgress;
3122
+ private send;
3123
+ private startPingInterval;
3124
+ private stopPingInterval;
3125
+ private cleanup;
3126
+ private scheduleReconnect;
3127
+ }
3128
+
3129
+ /**
3130
+ * PipelineOrchestrator — DAG-based remote execution engine for the Conductor.
3131
+ *
3132
+ * Executes sub-tasks across remote agents via the Gateway client,
3133
+ * respecting dependency ordering (parallel waves for independent tasks),
3134
+ * output piping between steps, and retry with alternative agents on failure.
3135
+ *
3136
+ * Budget checking is NOT done here — the caller (ConductorMode) handles that.
3137
+ * This module is pure execution.
3138
+ */
3139
+
3140
+ /**
3141
+ * Options for the orchestrate() function.
3142
+ */
3143
+ interface OrchestrateOptions {
3144
+ /** Ordered list of sub-tasks forming a dependency DAG. */
3145
+ subtasks: SubTask[];
3146
+ /** Match results keyed by subtask ID. */
3147
+ matches: Map<string, MatchResult>;
3148
+ /** Bearer token for authenticating with remote agents. */
3149
+ gatewayToken: string;
3150
+ /** Resolves an agent owner to their gateway URL and card ID. */
3151
+ resolveAgentUrl: (agentOwner: string) => {
3152
+ url: string;
3153
+ cardId: string;
3154
+ };
3155
+ /** Per-task timeout in milliseconds. Default 30000. */
3156
+ timeoutMs?: number;
3157
+ /** Maximum budget in credits. If set, aborts remaining tasks when exceeded. */
3158
+ maxBudget?: number;
3159
+ /** Optional relay client for executing tasks on remote agents (relay:// URLs). */
3160
+ relayClient?: RelayClient;
3161
+ /** Owner identifier of the requester agent. Used for relay requests. */
3162
+ requesterOwner?: string;
3163
+ }
3164
+ /**
3165
+ * Executes a DAG of sub-tasks across remote agents via Gateway.
3166
+ *
3167
+ * Execution flow:
3168
+ * 1. Computes execution waves from dependency graph
3169
+ * 2. For each wave, executes all tasks in parallel via Promise.allSettled
3170
+ * 3. Before each task, interpolates params against completed step outputs
3171
+ * 4. On failure, retries with the first alternative agent from MatchResult
3172
+ * 5. Tracks per-task spending and total credits
3173
+ * 6. Optionally enforces a maxBudget ceiling
3174
+ *
3175
+ * @param opts - Orchestration options.
3176
+ * @returns Aggregated orchestration result.
3177
+ */
3178
+ declare function orchestrate(opts: OrchestrateOptions): Promise<OrchestrationResult>;
3179
+
3180
+ /**
3181
+ * ConductorMode — ExecutorMode implementation for Conductor skills.
3182
+ *
3183
+ * Chains TaskDecomposer -> CapabilityMatcher -> BudgetController -> PipelineOrchestrator
3184
+ * to execute multi-agent orchestration pipelines via the SkillExecutor dispatch system.
3185
+ *
3186
+ * Supports two conductor skills:
3187
+ * - `orchestrate`: Full pipeline — decompose, match, budget check, execute, return results.
3188
+ * - `plan`: Planning only — decompose, match, budget check, return plan without executing.
3189
+ */
3190
+
3191
+ /**
3192
+ * Configuration options for ConductorMode.
3193
+ */
3194
+ interface ConductorModeOptions {
3195
+ /** Registry database for card search (FTS5). */
3196
+ db: Database.Database;
3197
+ /** Credit database for budget checks. */
3198
+ creditDb: Database.Database;
3199
+ /** Owner ID of the conductor agent — used for self-exclusion in matching. */
3200
+ conductorOwner: string;
3201
+ /** Bearer token for authenticating with remote agents. */
3202
+ gatewayToken: string;
3203
+ /** Resolves an agent owner to their gateway URL and card ID. */
3204
+ resolveAgentUrl: (owner: string) => {
3205
+ url: string;
3206
+ cardId: string;
3207
+ };
3208
+ /** Maximum budget in credits for orchestration runs. Default 100. */
3209
+ maxBudget?: number;
3210
+ }
3211
+ /**
3212
+ * ExecutorMode implementation for Conductor skills ('orchestrate' and 'plan').
3213
+ *
3214
+ * Dispatches through the full Conductor pipeline:
3215
+ * 1. TaskDecomposer breaks the task into SubTasks
3216
+ * 2. CapabilityMatcher finds agents for each sub-task
3217
+ * 3. BudgetController validates cost against limits
3218
+ * 4. PipelineOrchestrator executes the DAG (orchestrate only)
3219
+ */
3220
+ declare class ConductorMode implements ExecutorMode {
3221
+ private readonly db;
3222
+ private readonly creditDb;
3223
+ private readonly conductorOwner;
3224
+ private readonly gatewayToken;
3225
+ private readonly resolveAgentUrl;
3226
+ private readonly maxBudget;
3227
+ constructor(opts: ConductorModeOptions);
3228
+ /**
3229
+ * Execute a conductor skill with the given config and params.
3230
+ *
3231
+ * @param config - SkillConfig with type 'conductor' and conductor_skill field.
3232
+ * @param params - Must include `task` string.
3233
+ * @returns Execution result without latency_ms (added by SkillExecutor).
3234
+ */
3235
+ execute(config: SkillConfig, params: Record<string, unknown>, onProgress?: ProgressCallback): Promise<Omit<ExecutionResult, 'latency_ms'>>;
3236
+ }
3237
+
3238
+ /**
3239
+ * Ed25519 keypair as raw DER-encoded Buffers.
3240
+ */
3241
+ interface KeyPair {
3242
+ publicKey: Buffer;
3243
+ privateKey: Buffer;
3244
+ }
3245
+ /**
3246
+ * Generates a new Ed25519 keypair.
3247
+ * Uses Node.js built-in crypto — no external dependencies.
3248
+ *
3249
+ * @returns Object with publicKey and privateKey as DER-encoded Buffers.
3250
+ */
3251
+ declare function generateKeyPair(): KeyPair;
3252
+ /**
3253
+ * Saves an Ed25519 keypair to disk.
3254
+ * Private key is written with mode 0o600 (owner read/write only).
3255
+ *
3256
+ * @param configDir - Directory to write key files into.
3257
+ * @param keys - The keypair to persist.
3258
+ */
3259
+ declare function saveKeyPair(configDir: string, keys: KeyPair): void;
3260
+ /**
3261
+ * Loads an Ed25519 keypair from disk.
3262
+ *
3263
+ * @param configDir - Directory containing private.key and public.key files.
3264
+ * @returns The loaded keypair.
3265
+ * @throws {AgentBnBError} with code 'KEYPAIR_NOT_FOUND' if either key file is missing.
3266
+ */
3267
+ declare function loadKeyPair(configDir: string): KeyPair;
3268
+ /**
3269
+ * Signs escrow receipt data with an Ed25519 private key.
3270
+ * Data is serialized to canonical JSON (sorted keys) before signing.
3271
+ *
3272
+ * @param data - The receipt data to sign (all fields except 'signature').
3273
+ * @param privateKey - DER-encoded Ed25519 private key.
3274
+ * @returns Base64url-encoded signature string.
3275
+ */
3276
+ declare function signEscrowReceipt(data: Record<string, unknown>, privateKey: Buffer): string;
3277
+ /**
3278
+ * Verifies an Ed25519 signature over escrow receipt data.
3279
+ * Returns false (does not throw) for invalid signatures or wrong keys.
3280
+ *
3281
+ * @param data - The receipt data that was signed (all fields except 'signature').
3282
+ * @param signature - Base64url-encoded signature string.
3283
+ * @param publicKey - DER-encoded Ed25519 public key.
3284
+ * @returns true if signature is valid, false otherwise.
3285
+ */
3286
+ declare function verifyEscrowReceipt(data: Record<string, unknown>, signature: string, publicKey: Buffer): boolean;
3287
+
3288
+ /**
3289
+ * Zod schema for validating EscrowReceipt objects.
3290
+ * Used by providers to validate incoming receipts before verification.
3291
+ */
3292
+ declare const EscrowReceiptSchema: z.ZodObject<{
3293
+ requester_owner: z.ZodString;
3294
+ requester_public_key: z.ZodString;
3295
+ amount: z.ZodNumber;
3405
3296
  card_id: z.ZodString;
3406
3297
  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>>;
3298
+ timestamp: z.ZodString;
3299
+ nonce: z.ZodString;
3300
+ signature: z.ZodString;
3410
3301
  }, "strip", z.ZodTypeAny, {
3411
- type: "incoming_request";
3412
- params: Record<string, unknown>;
3413
- id: string;
3302
+ timestamp: string;
3303
+ signature: string;
3304
+ requester_owner: string;
3305
+ requester_public_key: string;
3306
+ amount: number;
3414
3307
  card_id: string;
3415
- from_owner: string;
3308
+ nonce: string;
3416
3309
  skill_id?: string | undefined;
3417
- requester?: string | undefined;
3418
- escrow_receipt?: Record<string, unknown> | undefined;
3419
3310
  }, {
3420
- type: "incoming_request";
3421
- id: string;
3311
+ timestamp: string;
3312
+ signature: string;
3313
+ requester_owner: string;
3314
+ requester_public_key: string;
3315
+ amount: number;
3422
3316
  card_id: string;
3423
- from_owner: string;
3424
- params?: Record<string, unknown> | undefined;
3317
+ nonce: string;
3425
3318
  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;
3319
+ }>;
3320
+ /**
3321
+ * Options for creating a signed escrow receipt.
3322
+ */
3323
+ interface CreateReceiptOpts {
3324
+ /** Agent owner identifier (requester). */
3325
+ owner: string;
3326
+ /** Number of credits to commit. */
3327
+ amount: number;
3328
+ /** Capability Card ID being requested. */
3329
+ cardId: string;
3330
+ /** Optional skill ID within the card. */
3331
+ skillId?: string;
3332
+ }
3333
+ /**
3334
+ * Creates a signed escrow receipt by atomically holding credits in the local DB
3335
+ * and producing a cryptographically signed receipt that can be sent to a provider.
3336
+ *
3337
+ * This combines local escrow hold + receipt generation from the requester's perspective.
3338
+ *
3339
+ * @param db - The credit database instance.
3340
+ * @param privateKey - DER-encoded Ed25519 private key for signing.
3341
+ * @param publicKey - DER-encoded Ed25519 public key (included in receipt for verification).
3342
+ * @param opts - Receipt creation options (owner, amount, cardId, skillId).
3343
+ * @returns Object with escrowId (local reference) and signed receipt (for transmission).
3344
+ * @throws {AgentBnBError} with code 'INSUFFICIENT_CREDITS' if balance is too low.
3345
+ */
3346
+ declare function createSignedEscrowReceipt(db: Database.Database, privateKey: Buffer, publicKey: Buffer, opts: CreateReceiptOpts): {
3347
+ escrowId: string;
3348
+ receipt: EscrowReceipt;
3349
+ };
3350
+
3351
+ /**
3352
+ * Provider-side settlement: records earnings from a signed escrow receipt.
3353
+ * The provider calls this after successfully executing a capability.
3354
+ * Credits are recorded in the provider's own local DB.
3355
+ *
3356
+ * @param providerDb - The provider's local credit database.
3357
+ * @param providerOwner - Provider agent identifier.
3358
+ * @param receipt - The signed escrow receipt from the requester.
3359
+ * @returns Object indicating settlement success.
3360
+ */
3361
+ declare function settleProviderEarning(providerDb: Database.Database, providerOwner: string, receipt: EscrowReceipt): {
3362
+ settled: true;
3363
+ };
3364
+ /**
3365
+ * Requester-side settlement: confirms that the escrow debit is permanent.
3366
+ * Called after the requester receives confirmation that the provider
3367
+ * successfully executed the capability. Marks escrow as 'settled' without
3368
+ * crediting anyone (credits stay deducted from requester).
3369
+ *
3370
+ * @param requesterDb - The requester's local credit database.
3371
+ * @param escrowId - The escrow ID to confirm as settled.
3372
+ */
3373
+ declare function settleRequesterEscrow(requesterDb: Database.Database, escrowId: string): void;
3374
+ /**
3375
+ * Requester-side failure handling: releases escrowed credits (refund).
3376
+ * Called when the capability execution fails and the requester needs
3377
+ * their credits back.
3378
+ *
3379
+ * @param requesterDb - The requester's local credit database.
3380
+ * @param escrowId - The escrow ID to release.
3381
+ */
3382
+ declare function releaseRequesterEscrow(requesterDb: Database.Database, escrowId: string): void;
3383
+
3384
+ /**
3385
+ * Agent Identity — the unified identity record for an AgentBnB agent.
3386
+ * Stored at ~/.agentbnb/identity.json.
3387
+ */
3388
+ declare const AgentIdentitySchema: z.ZodObject<{
3389
+ /** Deterministic ID derived from public key: sha256(hex).slice(0, 16). */
3390
+ agent_id: z.ZodString;
3391
+ /** Human-readable owner name (from config or init). */
3392
+ owner: z.ZodString;
3393
+ /** Hex-encoded Ed25519 public key. */
3394
+ public_key: z.ZodString;
3395
+ /** ISO 8601 timestamp of identity creation. */
3396
+ created_at: z.ZodString;
3397
+ /** Optional guarantor info if linked to a human. */
3398
+ guarantor: z.ZodOptional<z.ZodObject<{
3399
+ github_login: z.ZodString;
3400
+ verified_at: z.ZodString;
3465
3401
  }, "strip", z.ZodTypeAny, {
3466
- code: number;
3467
- message: string;
3402
+ github_login: string;
3403
+ verified_at: string;
3468
3404
  }, {
3469
- code: number;
3470
- message: string;
3405
+ github_login: string;
3406
+ verified_at: string;
3471
3407
  }>>;
3472
3408
  }, "strip", z.ZodTypeAny, {
3473
- type: "response";
3474
- id: string;
3475
- result?: unknown;
3476
- error?: {
3477
- code: number;
3478
- message: string;
3409
+ owner: string;
3410
+ created_at: string;
3411
+ agent_id: string;
3412
+ public_key: string;
3413
+ guarantor?: {
3414
+ github_login: string;
3415
+ verified_at: string;
3479
3416
  } | undefined;
3480
3417
  }, {
3481
- type: "response";
3482
- id: string;
3483
- result?: unknown;
3484
- error?: {
3485
- code: number;
3486
- message: string;
3418
+ owner: string;
3419
+ created_at: string;
3420
+ agent_id: string;
3421
+ public_key: string;
3422
+ guarantor?: {
3423
+ github_login: string;
3424
+ verified_at: string;
3487
3425
  } | undefined;
3488
- }>, z.ZodObject<{
3489
- type: z.ZodLiteral<"error">;
3490
- code: z.ZodString;
3491
- message: z.ZodString;
3492
- request_id: z.ZodOptional<z.ZodString>;
3426
+ }>;
3427
+ type AgentIdentity = z.infer<typeof AgentIdentitySchema>;
3428
+ /**
3429
+ * Agent Certificate — a self-signed attestation of agent identity.
3430
+ * Used for P2P identity verification without a shared auth server.
3431
+ */
3432
+ declare const AgentCertificateSchema: z.ZodObject<{
3433
+ identity: z.ZodObject<{
3434
+ /** Deterministic ID derived from public key: sha256(hex).slice(0, 16). */
3435
+ agent_id: z.ZodString;
3436
+ /** Human-readable owner name (from config or init). */
3437
+ owner: z.ZodString;
3438
+ /** Hex-encoded Ed25519 public key. */
3439
+ public_key: z.ZodString;
3440
+ /** ISO 8601 timestamp of identity creation. */
3441
+ created_at: z.ZodString;
3442
+ /** Optional guarantor info if linked to a human. */
3443
+ guarantor: z.ZodOptional<z.ZodObject<{
3444
+ github_login: z.ZodString;
3445
+ verified_at: z.ZodString;
3446
+ }, "strip", z.ZodTypeAny, {
3447
+ github_login: string;
3448
+ verified_at: string;
3449
+ }, {
3450
+ github_login: string;
3451
+ verified_at: string;
3452
+ }>>;
3453
+ }, "strip", z.ZodTypeAny, {
3454
+ owner: string;
3455
+ created_at: string;
3456
+ agent_id: string;
3457
+ public_key: string;
3458
+ guarantor?: {
3459
+ github_login: string;
3460
+ verified_at: string;
3461
+ } | undefined;
3462
+ }, {
3463
+ owner: string;
3464
+ created_at: string;
3465
+ agent_id: string;
3466
+ public_key: string;
3467
+ guarantor?: {
3468
+ github_login: string;
3469
+ verified_at: string;
3470
+ } | undefined;
3471
+ }>;
3472
+ /** ISO 8601 timestamp of certificate issuance. */
3473
+ issued_at: z.ZodString;
3474
+ /** ISO 8601 timestamp of certificate expiry. */
3475
+ expires_at: z.ZodString;
3476
+ /** Hex-encoded public key of the issuer (same as identity for self-signed). */
3477
+ issuer_public_key: z.ZodString;
3478
+ /** Base64url Ed25519 signature over { identity, issued_at, expires_at, issuer_public_key }. */
3479
+ signature: z.ZodString;
3493
3480
  }, "strip", z.ZodTypeAny, {
3494
- type: "error";
3495
- code: string;
3496
- message: string;
3497
- request_id?: string | undefined;
3481
+ signature: string;
3482
+ identity: {
3483
+ owner: string;
3484
+ created_at: string;
3485
+ agent_id: string;
3486
+ public_key: string;
3487
+ guarantor?: {
3488
+ github_login: string;
3489
+ verified_at: string;
3490
+ } | undefined;
3491
+ };
3492
+ issued_at: string;
3493
+ expires_at: string;
3494
+ issuer_public_key: string;
3498
3495
  }, {
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;
3496
+ signature: string;
3497
+ identity: {
3498
+ owner: string;
3499
+ created_at: string;
3500
+ agent_id: string;
3501
+ public_key: string;
3502
+ guarantor?: {
3503
+ github_login: string;
3504
+ verified_at: string;
3505
+ } | undefined;
3506
+ };
3507
+ issued_at: string;
3508
+ expires_at: string;
3509
+ issuer_public_key: string;
3510
+ }>;
3511
+ type AgentCertificate = z.infer<typeof AgentCertificateSchema>;
3512
+ /**
3513
+ * Derives a deterministic agent_id from a hex-encoded public key.
3514
+ * Uses first 16 chars of SHA-256 hash.
3515
+ */
3516
+ declare function deriveAgentId(publicKeyHex: string): string;
3517
+ /**
3518
+ * Creates a new agent identity. Generates an Ed25519 keypair if one does not
3519
+ * already exist. Writes identity.json to the config directory.
3520
+ *
3521
+ * @param configDir - Directory to write identity.json into (e.g. ~/.agentbnb).
3522
+ * @param owner - Human-readable agent owner name.
3523
+ * @returns The newly created AgentIdentity.
3524
+ */
3525
+ declare function createIdentity(configDir: string, owner: string): AgentIdentity;
3526
+ /**
3527
+ * Loads an existing agent identity from disk.
3528
+ *
3529
+ * @param configDir - Directory containing identity.json.
3530
+ * @returns Parsed AgentIdentity or null if file does not exist.
3531
+ */
3532
+ declare function loadIdentity(configDir: string): AgentIdentity | null;
3533
+ /**
3534
+ * Persists an agent identity to disk.
3535
+ *
3536
+ * @param configDir - Directory to write identity.json into.
3537
+ * @param identity - The identity to save.
3538
+ */
3539
+ declare function saveIdentity(configDir: string, identity: AgentIdentity): void;
3540
+ /**
3541
+ * Issues a self-signed Agent Certificate. Valid for 365 days.
3542
+ *
3543
+ * @param identity - The agent identity to certify.
3544
+ * @param privateKey - DER-encoded Ed25519 private key.
3545
+ * @returns A signed AgentCertificate.
3546
+ */
3547
+ declare function issueAgentCertificate(identity: AgentIdentity, privateKey: Buffer): AgentCertificate;
3548
+ /**
3549
+ * Verifies an Agent Certificate's signature and expiry.
3550
+ *
3551
+ * @param cert - The certificate to verify.
3552
+ * @returns true if signature is valid and certificate has not expired.
3553
+ */
3554
+ declare function verifyAgentCertificate(cert: AgentCertificate): boolean;
3555
+ /**
3556
+ * Ensures an identity exists for the given config directory.
3557
+ * If identity.json already exists, returns it. Otherwise creates a new one.
3558
+ *
3559
+ * @param configDir - Config directory path.
3560
+ * @param owner - Owner name to use if creating new identity.
3561
+ * @returns The loaded or newly created AgentIdentity.
3562
+ */
3563
+ declare function ensureIdentity(configDir: string, owner: string): AgentIdentity;
3564
+
3565
+ /**
3566
+ * Options for constructing an AgentBnBConsumer.
3567
+ */
3568
+ interface ConsumerOptions {
3569
+ /** Override the config directory (default: ~/.agentbnb or AGENTBNB_DIR). */
3570
+ configDir?: string;
3571
+ }
3572
+ /**
3573
+ * Options for requesting a capability.
3574
+ */
3575
+ interface ConsumerRequestOptions {
3576
+ /** Gateway URL of the target agent. */
3577
+ gatewayUrl: string;
3578
+ /** Bearer token for the target agent's gateway. */
3579
+ token: string;
3580
+ /** Capability Card ID to execute. */
3581
+ cardId: string;
3582
+ /** Optional skill ID within the card. */
3583
+ skillId?: string;
3584
+ /** Input parameters for the capability. */
3585
+ params?: Record<string, unknown>;
3586
+ /** Credit amount to commit (escrow). */
3587
+ credits: number;
3588
+ /** Timeout in milliseconds. Default 30000. */
3589
+ timeoutMs?: number;
3590
+ }
3591
+ /**
3592
+ * AgentBnBConsumer — high-level SDK class for agents consuming capabilities.
3593
+ *
3594
+ * Encapsulates the full request lifecycle: identity loading, escrow creation,
3595
+ * capability request, and settlement/release.
3596
+ *
3597
+ * @example
3598
+ * ```typescript
3599
+ * const consumer = new AgentBnBConsumer();
3600
+ * consumer.authenticate();
3601
+ * const result = await consumer.request({
3602
+ * gatewayUrl: 'http://peer:7700',
3603
+ * token: 'peer-token',
3604
+ * cardId: 'uuid-of-card',
3605
+ * credits: 5,
3606
+ * });
3607
+ * ```
3608
+ */
3609
+ declare class AgentBnBConsumer {
3610
+ private configDir;
3611
+ private identity;
3612
+ private keys;
3613
+ private creditDb;
3614
+ constructor(opts?: ConsumerOptions);
3615
+ /**
3616
+ * Loads agent identity and keypair from disk.
3617
+ * Creates identity if none exists (uses owner from config.json or generates one).
3618
+ *
3619
+ * @returns The loaded AgentIdentity.
3620
+ * @throws {AgentBnBError} if keypair is missing and cannot be created.
3621
+ */
3622
+ authenticate(): AgentIdentity;
3623
+ /**
3624
+ * Returns the cached identity. Throws if not yet authenticated.
3625
+ */
3626
+ getIdentity(): AgentIdentity;
3627
+ /**
3628
+ * Requests a capability from a remote agent with full escrow lifecycle.
3629
+ *
3630
+ * 1. Creates a signed escrow receipt (holds credits locally)
3631
+ * 2. Sends the request to the target gateway
3632
+ * 3. Settles escrow on success, releases on failure
3633
+ *
3634
+ * @param opts - Request options including target, card, credits, and params.
3635
+ * @returns The result from the capability execution.
3636
+ * @throws {AgentBnBError} on insufficient credits, network error, or RPC error.
3637
+ */
3638
+ request(opts: ConsumerRequestOptions): Promise<unknown>;
3639
+ /**
3640
+ * Returns the current credit balance for this agent.
3641
+ */
3642
+ getBalance(): number;
3643
+ /**
3644
+ * Returns basic reputation data from the local credit database.
3645
+ * Note: success_rate is computed from local request history only.
3646
+ */
3647
+ getReputation(): {
3648
+ success_rate: number;
3649
+ total_requests: number;
3650
+ };
3651
+ /**
3652
+ * Closes the credit database connection. Call when done.
3653
+ */
3654
+ close(): void;
3655
+ /** Lazily opens and caches the credit database. */
3656
+ private getCreditDb;
3520
3657
  }
3521
3658
 
3522
3659
  /**
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.
3660
+ * Options for constructing an AgentBnBProvider.
3529
3661
  */
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
- };
3662
+ interface ProviderOptions {
3663
+ /** Override the config directory (default: ~/.agentbnb or AGENTBNB_DIR). */
3664
+ configDir?: string;
3539
3665
  }
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;
3666
+ /**
3667
+ * Options for starting the sharing gateway.
3668
+ */
3669
+ interface StartSharingOptions {
3670
+ /** Port to listen on (default: from config or 7700). */
3671
+ port?: number;
3672
+ /** Host to bind to (default: '0.0.0.0'). */
3673
+ host?: string;
3554
3674
  }
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;
3675
+ /**
3676
+ * Context returned after sharing starts.
3677
+ */
3678
+ interface SharingContext {
3679
+ /** The Fastify gateway server instance. */
3680
+ gateway: FastifyInstance;
3681
+ /** Port the gateway is listening on. */
3682
+ port: number;
3564
3683
  }
3565
3684
  /**
3566
- * WebSocket client for connecting to an AgentBnB registry relay.
3567
- * Handles registration, auto-reconnect, incoming requests, and outbound relay requests.
3685
+ * AgentBnBProvider high-level SDK class for agents providing capabilities.
3686
+ *
3687
+ * Manages identity, gateway lifecycle, and capability listing.
3688
+ *
3689
+ * @example
3690
+ * ```typescript
3691
+ * const provider = new AgentBnBProvider();
3692
+ * provider.authenticate();
3693
+ * const ctx = await provider.startSharing({ port: 7700 });
3694
+ * console.log(provider.listCapabilities());
3695
+ * await provider.stopSharing();
3696
+ * ```
3568
3697
  */
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);
3698
+ declare class AgentBnBProvider {
3699
+ private configDir;
3700
+ private identity;
3701
+ private registryDb;
3702
+ private creditDb;
3703
+ private gateway;
3704
+ constructor(opts?: ProviderOptions);
3580
3705
  /**
3581
- * Connect to the registry relay and register.
3582
- * Resolves when registration is acknowledged.
3706
+ * Loads agent identity from disk.
3707
+ * Creates identity if none exists.
3708
+ *
3709
+ * @returns The loaded AgentIdentity.
3583
3710
  */
3584
- connect(): Promise<void>;
3711
+ authenticate(): AgentIdentity;
3585
3712
  /**
3586
- * Disconnect from the registry relay.
3713
+ * Returns the cached identity. Throws if not yet authenticated.
3587
3714
  */
3588
- disconnect(): void;
3715
+ getIdentity(): AgentIdentity;
3589
3716
  /**
3590
- * Send a relay request to another agent via the registry.
3591
- * @returns The result from the target agent.
3717
+ * Starts the gateway server to share capabilities.
3718
+ *
3719
+ * @param opts - Optional port and host configuration.
3720
+ * @returns Context with the gateway server and port.
3592
3721
  */
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;
3722
+ startSharing(opts?: StartSharingOptions): Promise<SharingContext>;
3723
+ /**
3724
+ * Stops the gateway server.
3725
+ */
3726
+ stopSharing(): Promise<void>;
3727
+ /**
3728
+ * Returns all capability cards owned by this agent.
3729
+ */
3730
+ listCapabilities(): CapabilityCard[];
3731
+ /**
3732
+ * Returns the current credit balance for this agent.
3733
+ */
3734
+ getBalance(): number;
3735
+ /**
3736
+ * Closes all database connections and stops the gateway. Call when done.
3737
+ */
3738
+ close(): Promise<void>;
3739
+ /** Lazily opens and caches the registry database. */
3740
+ private getRegistryDb;
3741
+ /** Lazily opens and caches the credit database. */
3742
+ private getCreditDb;
3606
3743
  }
3607
3744
 
3745
+ /** Maximum agents a single human guarantor can back. */
3746
+ declare const MAX_AGENTS_PER_GUARANTOR = 10;
3747
+ /** Free credits granted per human guarantor registration. */
3748
+ declare const GUARANTOR_CREDIT_POOL = 50;
3749
+ /**
3750
+ * A Human Guarantor — a real person backing one or more agents.
3751
+ * Provides initial trust and credit pool for the agent network.
3752
+ */
3753
+ declare const GuarantorRecordSchema: z.ZodObject<{
3754
+ id: z.ZodString;
3755
+ github_login: z.ZodString;
3756
+ agent_count: z.ZodNumber;
3757
+ credit_pool: z.ZodNumber;
3758
+ created_at: z.ZodString;
3759
+ }, "strip", z.ZodTypeAny, {
3760
+ id: string;
3761
+ created_at: string;
3762
+ github_login: string;
3763
+ agent_count: number;
3764
+ credit_pool: number;
3765
+ }, {
3766
+ id: string;
3767
+ created_at: string;
3768
+ github_login: string;
3769
+ agent_count: number;
3770
+ credit_pool: number;
3771
+ }>;
3772
+ type GuarantorRecord = z.infer<typeof GuarantorRecordSchema>;
3773
+ /**
3774
+ * Registers a new human guarantor via GitHub login.
3775
+ * Grants GUARANTOR_CREDIT_POOL (50) credits to be distributed among linked agents.
3776
+ *
3777
+ * @param db - The credit database instance.
3778
+ * @param githubLogin - GitHub username of the guarantor.
3779
+ * @returns The created GuarantorRecord.
3780
+ * @throws {AgentBnBError} with code 'GUARANTOR_EXISTS' if login already registered.
3781
+ */
3782
+ declare function registerGuarantor(db: Database.Database, githubLogin: string): GuarantorRecord;
3783
+ /**
3784
+ * Links an agent to a human guarantor.
3785
+ * Enforces the MAX_AGENTS_PER_GUARANTOR limit (10).
3786
+ *
3787
+ * @param db - The credit database instance.
3788
+ * @param agentId - The agent_id to link.
3789
+ * @param githubLogin - The guarantor's GitHub login.
3790
+ * @returns Updated GuarantorRecord.
3791
+ * @throws {AgentBnBError} with code 'GUARANTOR_NOT_FOUND' if login not registered.
3792
+ * @throws {AgentBnBError} with code 'MAX_AGENTS_EXCEEDED' if limit reached.
3793
+ * @throws {AgentBnBError} with code 'AGENT_ALREADY_LINKED' if agent already has a guarantor.
3794
+ */
3795
+ declare function linkAgentToGuarantor(db: Database.Database, agentId: string, githubLogin: string): GuarantorRecord;
3796
+ /**
3797
+ * Retrieves a guarantor record by GitHub login.
3798
+ *
3799
+ * @param db - The credit database instance.
3800
+ * @param githubLogin - The GitHub username to look up.
3801
+ * @returns GuarantorRecord or null if not found.
3802
+ */
3803
+ declare function getGuarantor(db: Database.Database, githubLogin: string): GuarantorRecord | null;
3804
+ /**
3805
+ * Gets the guarantor linked to an agent, if any.
3806
+ *
3807
+ * @param db - The credit database instance.
3808
+ * @param agentId - The agent_id to look up.
3809
+ * @returns GuarantorRecord or null if agent has no guarantor.
3810
+ */
3811
+ declare function getAgentGuarantor(db: Database.Database, agentId: string): GuarantorRecord | null;
3812
+ /**
3813
+ * Initiates a GitHub OAuth flow for guarantor verification.
3814
+ * This is a STUB — returns placeholder values. Actual OAuth implementation
3815
+ * is deferred to a future version.
3816
+ *
3817
+ * @returns Object with auth_url and state for the OAuth flow.
3818
+ */
3819
+ declare function initiateGithubAuth(): {
3820
+ auth_url: string;
3821
+ state: string;
3822
+ };
3823
+
3824
+ /**
3825
+ * Registers WebSocket relay on an existing Fastify instance.
3826
+ * Adds a `/ws` route that upgrades HTTP to WebSocket for agent relay.
3827
+ *
3828
+ * @param server - Fastify instance with @fastify/websocket already registered.
3829
+ * @param db - Registry database instance (for card lookups and online status).
3830
+ * @param creditDb - Optional credit database. When provided, credits are held
3831
+ * before forwarding requests, settled on success, and released on failure/timeout/disconnect.
3832
+ * When undefined, all credit operations are skipped (backward compat for tests).
3833
+ * @returns RelayState for monitoring and graceful shutdown.
3834
+ */
3835
+ declare function registerWebSocketRelay(server: FastifyInstance, db: Database.Database, creditDb?: Database.Database): RelayState;
3836
+
3608
3837
  /**
3609
3838
  * Options for executing a capability request.
3610
3839
  * Used by both the HTTP /rpc handler and WebSocket relay.
@@ -3620,6 +3849,8 @@ interface ExecuteRequestOptions {
3620
3849
  skillExecutor?: SkillExecutor;
3621
3850
  handlerUrl?: string;
3622
3851
  timeoutMs?: number;
3852
+ /** Optional progress callback forwarded to SkillExecutor during execution. */
3853
+ onProgress?: ProgressCallback;
3623
3854
  }
3624
3855
  /**
3625
3856
  * Result of a capability execution.
@@ -3660,6 +3891,8 @@ interface RelayRequestOptions {
3660
3891
  escrowReceipt?: EscrowReceipt;
3661
3892
  /** Timeout in milliseconds. Default 30000. */
3662
3893
  timeoutMs?: number;
3894
+ /** Actual requester owner for credit tracking (defaults to relay client's owner). */
3895
+ requester?: string;
3663
3896
  }
3664
3897
  /**
3665
3898
  * Sends a capability request to another agent via the WebSocket relay.