@zerox1/sdk 0.1.28 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 0x01 Labs
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/dist/index.d.ts CHANGED
@@ -64,6 +64,41 @@ export interface SendFeedbackParams {
64
64
  outcome: 'negative' | 'neutral' | 'positive';
65
65
  role: 'participant' | 'notary';
66
66
  }
67
+ export interface HostingNode {
68
+ node_id: string;
69
+ name: string;
70
+ fee_bps: number;
71
+ api_url: string;
72
+ hosted_count: number;
73
+ first_seen: number;
74
+ last_seen: number;
75
+ }
76
+ export interface HostedRegistration {
77
+ agent_id: string;
78
+ token: string;
79
+ }
80
+ export interface HostedAgentConfig {
81
+ /** Base URL of the host node, e.g. "https://host.example.com". */
82
+ hostApiUrl: string;
83
+ /** Bearer token returned by registerHosted(). */
84
+ token: string;
85
+ }
86
+ export interface OwnerProposal {
87
+ status: 'pending';
88
+ agent_id: string;
89
+ proposed_owner: string;
90
+ proposed_at: number;
91
+ }
92
+ export interface OwnerRecord {
93
+ status: 'claimed';
94
+ agent_id: string;
95
+ owner: string;
96
+ claimed_at: number;
97
+ }
98
+ export interface OwnerUnclaimed {
99
+ status: 'unclaimed';
100
+ }
101
+ export type OwnerStatus = OwnerUnclaimed | OwnerProposal | OwnerRecord;
67
102
  type Handler = (env: InboundEnvelope) => void | Promise<void>;
68
103
  export declare class Zerox1Agent {
69
104
  private proc;
@@ -79,6 +114,59 @@ export declare class Zerox1Agent {
79
114
  * the mesh. The node binary is bundled — no separate install required.
80
115
  */
81
116
  static create(config: Zerox1AgentConfig): Zerox1Agent;
117
+ /**
118
+ * Fetch active hosting nodes from the 0x01 aggregator.
119
+ * These are nodes that offer to relay envelopes for
120
+ * lightweight/serverless agents that cannot run a full node.
121
+ */
122
+ static listHostingNodes(aggregatorUrl?: string): Promise<HostingNode[]>;
123
+ /**
124
+ * Register a new hosted-agent session on a hosting node.
125
+ * The host generates a fresh Ed25519 sub-keypair; your
126
+ * agent_id is its public key. Keep the token secret.
127
+ *
128
+ * @param hostApiUrl - Base URL of the selected hosting node.
129
+ * @returns { agent_id, token } — persist both for reconnection.
130
+ */
131
+ static registerHosted(hostApiUrl: string): Promise<HostedRegistration>;
132
+ /**
133
+ * Create a hosted agent that delegates to an existing host node.
134
+ * No binary is spawned — the SDK connects to the host's WebSocket inbox
135
+ * and routes outbound sends through the host.
136
+ *
137
+ * @param config - { hostApiUrl, token } returned from registerHosted().
138
+ */
139
+ static createHosted(config: HostedAgentConfig): HostedAgent;
140
+ /**
141
+ * Propose a human wallet as the owner of this agent.
142
+ *
143
+ * Called by the agent or its operator. The human wallet is notified
144
+ * and can accept via `accept_claim()` in the agent-ownership Solana program,
145
+ * then call `claimOwner()` (or POST /agents/:id/claim-owner) to confirm.
146
+ *
147
+ * Optional — agents without an owner are fully functional on the mesh.
148
+ *
149
+ * @param agentId - Hex-encoded 64-char agent ID.
150
+ * @param proposedOwner - Base58 Solana wallet address of the intended human.
151
+ * @param aggregatorUrl - Aggregator base URL (defaults to mainnet).
152
+ */
153
+ static proposeOwner(agentId: string, proposedOwner: string, aggregatorUrl?: string): Promise<{
154
+ status: string;
155
+ agent_id: string;
156
+ proposed_owner: string;
157
+ }>;
158
+ /**
159
+ * Read the current ownership status of an agent.
160
+ *
161
+ * Possible responses:
162
+ * - `{ status: "unclaimed" }`
163
+ * - `{ status: "pending", proposed_owner: "7XsB...", proposed_at: 123 }`
164
+ * - `{ status: "claimed", owner: "7XsB...", claimed_at: 123 }`
165
+ *
166
+ * @param agentId - Hex-encoded 64-char agent ID.
167
+ * @param aggregatorUrl - Aggregator base URL.
168
+ */
169
+ static getOwner(agentId: string, aggregatorUrl?: string): Promise<OwnerStatus>;
82
170
  private _config;
83
171
  /**
84
172
  * Start the node, wait for it to be ready, connect the inbox stream.
@@ -118,4 +206,46 @@ export declare class Zerox1Agent {
118
206
  encodeBidValue(value: bigint, rest?: Buffer): Buffer;
119
207
  private _connectInbox;
120
208
  }
209
+ /**
210
+ * A hosted agent that delegates signing and routing to a host node.
211
+ * No binary is spawned. Inbound envelopes are streamed via WebSocket;
212
+ * outbound sends go through `POST /hosted/send` on the host.
213
+ *
214
+ * Obtain via `Zerox1Agent.createHosted({ hostApiUrl, token })`.
215
+ */
216
+ export declare class HostedAgent {
217
+ private ws;
218
+ private handlers;
219
+ private _reconnectDelay;
220
+ private _running;
221
+ private readonly baseUrl;
222
+ private readonly token;
223
+ constructor(config: HostedAgentConfig);
224
+ /**
225
+ * Connect to the host node's inbox WebSocket.
226
+ * Resolves once the connection is open.
227
+ */
228
+ start(): Promise<void>;
229
+ /** Disconnect from the host node. */
230
+ disconnect(): void;
231
+ /**
232
+ * Register a handler for a message type.
233
+ * Use `'*'` to catch all inbound message types.
234
+ */
235
+ on(msgType: MsgType | '*', handler: Handler): this;
236
+ /**
237
+ * Send an envelope through the host node.
238
+ * The host signs it with this agent's sub-keypair and broadcasts via libp2p.
239
+ */
240
+ send(params: SendParams): Promise<void>;
241
+ /**
242
+ * Send a FEEDBACK envelope with CBOR-encoded payload.
243
+ * Mirrors `Zerox1Agent.sendFeedback()`.
244
+ */
245
+ sendFeedback(params: SendFeedbackParams): Promise<void>;
246
+ /** Generate a random 16-byte conversation ID as hex. */
247
+ newConversationId(): string;
248
+ private _connect;
249
+ private _dispatch;
250
+ }
121
251
  export {};
package/dist/index.js CHANGED
@@ -36,7 +36,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
36
36
  return (mod && mod.__esModule) ? mod : { "default": mod };
37
37
  };
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.Zerox1Agent = void 0;
39
+ exports.HostedAgent = exports.Zerox1Agent = void 0;
40
40
  const fs = __importStar(require("fs"));
41
41
  const net = __importStar(require("net"));
42
42
  const os = __importStar(require("os"));
@@ -164,6 +164,87 @@ class Zerox1Agent {
164
164
  agent._config = config;
165
165
  return agent;
166
166
  }
167
+ /**
168
+ * Fetch active hosting nodes from the 0x01 aggregator.
169
+ * These are nodes that offer to relay envelopes for
170
+ * lightweight/serverless agents that cannot run a full node.
171
+ */
172
+ static async listHostingNodes(aggregatorUrl = 'https://api.0x01.world') {
173
+ const res = await fetch(`${aggregatorUrl}/hosting/nodes`);
174
+ if (!res.ok)
175
+ throw new Error(`Failed to fetch hosting nodes: HTTP ${res.status}`);
176
+ return res.json();
177
+ }
178
+ /**
179
+ * Register a new hosted-agent session on a hosting node.
180
+ * The host generates a fresh Ed25519 sub-keypair; your
181
+ * agent_id is its public key. Keep the token secret.
182
+ *
183
+ * @param hostApiUrl - Base URL of the selected hosting node.
184
+ * @returns { agent_id, token } — persist both for reconnection.
185
+ */
186
+ static async registerHosted(hostApiUrl) {
187
+ const url = hostApiUrl.replace(/\/$/, '');
188
+ const res = await fetch(`${url}/hosted/register`, { method: 'POST' });
189
+ if (!res.ok) {
190
+ const body = await res.text();
191
+ throw new Error(`registerHosted failed (${res.status}): ${body}`);
192
+ }
193
+ return res.json();
194
+ }
195
+ /**
196
+ * Create a hosted agent that delegates to an existing host node.
197
+ * No binary is spawned — the SDK connects to the host's WebSocket inbox
198
+ * and routes outbound sends through the host.
199
+ *
200
+ * @param config - { hostApiUrl, token } returned from registerHosted().
201
+ */
202
+ static createHosted(config) {
203
+ return new HostedAgent(config);
204
+ }
205
+ // ── Ownership claims ───────────────────────────────────────────────────────
206
+ /**
207
+ * Propose a human wallet as the owner of this agent.
208
+ *
209
+ * Called by the agent or its operator. The human wallet is notified
210
+ * and can accept via `accept_claim()` in the agent-ownership Solana program,
211
+ * then call `claimOwner()` (or POST /agents/:id/claim-owner) to confirm.
212
+ *
213
+ * Optional — agents without an owner are fully functional on the mesh.
214
+ *
215
+ * @param agentId - Hex-encoded 64-char agent ID.
216
+ * @param proposedOwner - Base58 Solana wallet address of the intended human.
217
+ * @param aggregatorUrl - Aggregator base URL (defaults to mainnet).
218
+ */
219
+ static async proposeOwner(agentId, proposedOwner, aggregatorUrl = 'https://api.0x01.world') {
220
+ const res = await fetch(`${aggregatorUrl}/agents/${agentId}/propose-owner`, {
221
+ method: 'POST',
222
+ headers: { 'Content-Type': 'application/json' },
223
+ body: JSON.stringify({ proposed_owner: proposedOwner }),
224
+ });
225
+ if (!res.ok) {
226
+ const err = await res.json().catch(() => ({ error: `HTTP ${res.status}` }));
227
+ throw new Error(`proposeOwner failed: ${err.error ?? res.status}`);
228
+ }
229
+ return res.json();
230
+ }
231
+ /**
232
+ * Read the current ownership status of an agent.
233
+ *
234
+ * Possible responses:
235
+ * - `{ status: "unclaimed" }`
236
+ * - `{ status: "pending", proposed_owner: "7XsB...", proposed_at: 123 }`
237
+ * - `{ status: "claimed", owner: "7XsB...", claimed_at: 123 }`
238
+ *
239
+ * @param agentId - Hex-encoded 64-char agent ID.
240
+ * @param aggregatorUrl - Aggregator base URL.
241
+ */
242
+ static async getOwner(agentId, aggregatorUrl = 'https://api.0x01.world') {
243
+ const res = await fetch(`${aggregatorUrl}/agents/${agentId}/owner`);
244
+ if (!res.ok)
245
+ throw new Error(`getOwner failed: HTTP ${res.status}`);
246
+ return res.json();
247
+ }
167
248
  // ── Lifecycle ─────────────────────────────────────────────────────────────
168
249
  /**
169
250
  * Start the node, wait for it to be ready, connect the inbox stream.
@@ -379,3 +460,153 @@ class Zerox1Agent {
379
460
  }
380
461
  }
381
462
  exports.Zerox1Agent = Zerox1Agent;
463
+ // ============================================================================
464
+ // HostedAgent — lightweight hosted-mode client
465
+ // ============================================================================
466
+ /**
467
+ * A hosted agent that delegates signing and routing to a host node.
468
+ * No binary is spawned. Inbound envelopes are streamed via WebSocket;
469
+ * outbound sends go through `POST /hosted/send` on the host.
470
+ *
471
+ * Obtain via `Zerox1Agent.createHosted({ hostApiUrl, token })`.
472
+ */
473
+ class HostedAgent {
474
+ constructor(config) {
475
+ this.ws = null;
476
+ this.handlers = new Map();
477
+ this._reconnectDelay = 1000;
478
+ this._running = false;
479
+ this.baseUrl = config.hostApiUrl.replace(/\/$/, '');
480
+ this.token = config.token;
481
+ }
482
+ /**
483
+ * Connect to the host node's inbox WebSocket.
484
+ * Resolves once the connection is open.
485
+ */
486
+ async start() {
487
+ this._running = true;
488
+ await this._connect();
489
+ }
490
+ /** Disconnect from the host node. */
491
+ disconnect() {
492
+ this._running = false;
493
+ this.ws?.close();
494
+ this.ws = null;
495
+ }
496
+ /**
497
+ * Register a handler for a message type.
498
+ * Use `'*'` to catch all inbound message types.
499
+ */
500
+ on(msgType, handler) {
501
+ const key = msgType === '*' ? '__all__' : msgType;
502
+ const list = this.handlers.get(key) ?? [];
503
+ list.push(handler);
504
+ this.handlers.set(key, list);
505
+ return this;
506
+ }
507
+ /**
508
+ * Send an envelope through the host node.
509
+ * The host signs it with this agent's sub-keypair and broadcasts via libp2p.
510
+ */
511
+ async send(params) {
512
+ const res = await fetch(`${this.baseUrl}/hosted/send`, {
513
+ method: 'POST',
514
+ headers: {
515
+ 'Content-Type': 'application/json',
516
+ 'Authorization': `Bearer ${this.token}`,
517
+ },
518
+ body: JSON.stringify({
519
+ msg_type: params.msgType,
520
+ recipient: params.recipient ?? null,
521
+ conversation_id: params.conversationId,
522
+ payload_hex: Buffer.from(params.payload).toString('hex'),
523
+ }),
524
+ });
525
+ if (!res.ok && res.status !== 204) {
526
+ const body = await res.text();
527
+ throw new Error(`hosted send failed (${res.status}): ${body}`);
528
+ }
529
+ }
530
+ /**
531
+ * Send a FEEDBACK envelope with CBOR-encoded payload.
532
+ * Mirrors `Zerox1Agent.sendFeedback()`.
533
+ */
534
+ async sendFeedback(params) {
535
+ if (params.score < -100 || params.score > 100)
536
+ throw new RangeError(`score must be in [-100, 100], got ${params.score}`);
537
+ const outcomeMap = { negative: 0, neutral: 1, positive: 2 };
538
+ const roleMap = { participant: 0, notary: 1 };
539
+ const payload = encodeFeedbackCbor(params.conversationId, params.targetAgent, params.score, outcomeMap[params.outcome], false, roleMap[params.role]);
540
+ return this.send({ msgType: 'FEEDBACK', conversationId: params.conversationId, payload });
541
+ }
542
+ /** Generate a random 16-byte conversation ID as hex. */
543
+ newConversationId() {
544
+ const bytes = new Uint8Array(16);
545
+ crypto.getRandomValues(bytes);
546
+ return Buffer.from(bytes).toString('hex');
547
+ }
548
+ // ── Internal ──────────────────────────────────────────────────────────────
549
+ async _connect() {
550
+ const wsUrl = `${this.baseUrl.replace(/^http/, 'ws')}/ws/hosted/inbox`;
551
+ return new Promise((resolve, reject) => {
552
+ const ws = new ws_1.default(wsUrl, {
553
+ headers: { Authorization: `Bearer ${this.token}` },
554
+ });
555
+ this.ws = ws;
556
+ ws.once('open', () => {
557
+ this._reconnectDelay = 1000;
558
+ resolve();
559
+ });
560
+ ws.once('error', reject);
561
+ ws.on('message', (data) => {
562
+ try {
563
+ const raw = JSON.parse(data.toString());
564
+ const env = {
565
+ msgType: raw.msg_type,
566
+ sender: raw.sender,
567
+ recipient: raw.recipient,
568
+ conversationId: raw.conversation_id,
569
+ slot: raw.slot,
570
+ nonce: raw.nonce,
571
+ payloadB64: raw.payload_b64,
572
+ feedback: raw.feedback ? {
573
+ conversationId: raw.feedback.conversation_id,
574
+ targetAgent: raw.feedback.target_agent,
575
+ score: raw.feedback.score,
576
+ outcome: raw.feedback.outcome,
577
+ isDispute: raw.feedback.is_dispute,
578
+ role: raw.feedback.role,
579
+ } : undefined,
580
+ notarizeBid: raw.notarize_bid ? {
581
+ bidType: raw.notarize_bid.bid_type,
582
+ conversationId: raw.notarize_bid.conversation_id,
583
+ opaqueB64: raw.notarize_bid.opaque_b64,
584
+ } : undefined,
585
+ };
586
+ this._dispatch(env);
587
+ }
588
+ catch { /* malformed — ignore */ }
589
+ });
590
+ ws.on('close', () => {
591
+ if (this._running) {
592
+ setTimeout(() => {
593
+ this._reconnectDelay = 1000;
594
+ this._connect().catch(() => { });
595
+ }, this._reconnectDelay);
596
+ this._reconnectDelay = Math.min(this._reconnectDelay * 2, 30000);
597
+ }
598
+ });
599
+ });
600
+ }
601
+ _dispatch(env) {
602
+ const specific = this.handlers.get(env.msgType) ?? [];
603
+ const wildcard = this.handlers.get('__all__') ?? [];
604
+ for (const h of [...specific, ...wildcard]) {
605
+ try {
606
+ void h(env);
607
+ }
608
+ catch { /* handler errors are isolated */ }
609
+ }
610
+ }
611
+ }
612
+ exports.HostedAgent = HostedAgent;
package/package.json CHANGED
@@ -1,7 +1,8 @@
1
1
  {
2
2
  "name": "@zerox1/sdk",
3
- "version": "0.1.28",
3
+ "version": "0.2.1",
4
4
  "description": "0x01 mesh agent SDK — zero-config, binary bundled, works on every platform",
5
+ "license": "MIT",
5
6
  "main": "dist/index.js",
6
7
  "types": "dist/index.d.ts",
7
8
  "scripts": {
@@ -12,10 +13,10 @@
12
13
  "ws": "^8.18.0"
13
14
  },
14
15
  "optionalDependencies": {
15
- "@zerox1/sdk-darwin-arm64": "0.1.28",
16
- "@zerox1/sdk-darwin-x64": "0.1.28",
17
- "@zerox1/sdk-linux-x64": "0.1.28",
18
- "@zerox1/sdk-win32-x64": "0.1.28"
16
+ "@zerox1/sdk-darwin-arm64": "0.2.1",
17
+ "@zerox1/sdk-darwin-x64": "0.2.1",
18
+ "@zerox1/sdk-linux-x64": "0.2.1",
19
+ "@zerox1/sdk-win32-x64": "0.2.1"
19
20
  },
20
21
  "devDependencies": {
21
22
  "@types/node": "^22.0.0",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zerox1/sdk-darwin-arm64",
3
- "version": "0.1.28",
3
+ "version": "0.2.1",
4
4
  "description": "zerox1-node binary for macOS ARM64 (Apple Silicon)",
5
5
  "os": [
6
6
  "darwin"
@@ -8,6 +8,7 @@
8
8
  "cpu": [
9
9
  "arm64"
10
10
  ],
11
+ "license": "MIT",
11
12
  "files": [
12
13
  "bin/"
13
14
  ]
Binary file
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zerox1/sdk-darwin-x64",
3
- "version": "0.1.28",
3
+ "version": "0.2.1",
4
4
  "description": "zerox1-node binary for macOS x64 (Intel)",
5
5
  "os": [
6
6
  "darwin"
@@ -8,6 +8,7 @@
8
8
  "cpu": [
9
9
  "x64"
10
10
  ],
11
+ "license": "MIT",
11
12
  "files": [
12
13
  "bin/"
13
14
  ]
Binary file
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zerox1/sdk-linux-x64",
3
- "version": "0.1.28",
3
+ "version": "0.2.1",
4
4
  "description": "zerox1-node binary for Linux x64",
5
5
  "os": [
6
6
  "linux"
@@ -8,6 +8,7 @@
8
8
  "cpu": [
9
9
  "x64"
10
10
  ],
11
+ "license": "MIT",
11
12
  "files": [
12
13
  "bin/"
13
14
  ]
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zerox1/sdk-win32-x64",
3
- "version": "0.1.28",
3
+ "version": "0.2.1",
4
4
  "description": "zerox1-node binary for Windows x64",
5
5
  "os": [
6
6
  "win32"
@@ -8,6 +8,7 @@
8
8
  "cpu": [
9
9
  "x64"
10
10
  ],
11
+ "license": "MIT",
11
12
  "files": [
12
13
  "bin/"
13
14
  ]
package/src/index.ts CHANGED
@@ -90,6 +90,56 @@ export interface SendFeedbackParams {
90
90
  role: 'participant' | 'notary'
91
91
  }
92
92
 
93
+ // ============================================================================
94
+ // Hosting types
95
+ // ============================================================================
96
+
97
+ export interface HostingNode {
98
+ node_id: string
99
+ name: string
100
+ fee_bps: number
101
+ api_url: string
102
+ hosted_count: number
103
+ first_seen: number
104
+ last_seen: number
105
+ }
106
+
107
+ export interface HostedRegistration {
108
+ agent_id: string
109
+ token: string
110
+ }
111
+
112
+ export interface HostedAgentConfig {
113
+ /** Base URL of the host node, e.g. "https://host.example.com". */
114
+ hostApiUrl: string
115
+ /** Bearer token returned by registerHosted(). */
116
+ token: string
117
+ }
118
+
119
+ // ============================================================================
120
+ // Ownership types
121
+ // ============================================================================
122
+
123
+ export interface OwnerProposal {
124
+ status: 'pending'
125
+ agent_id: string
126
+ proposed_owner: string
127
+ proposed_at: number
128
+ }
129
+
130
+ export interface OwnerRecord {
131
+ status: 'claimed'
132
+ agent_id: string
133
+ owner: string
134
+ claimed_at: number
135
+ }
136
+
137
+ export interface OwnerUnclaimed {
138
+ status: 'unclaimed'
139
+ }
140
+
141
+ export type OwnerStatus = OwnerUnclaimed | OwnerProposal | OwnerRecord
142
+
93
143
  // ============================================================================
94
144
  // CBOR encoding for FEEDBACK payload
95
145
  //
@@ -230,6 +280,100 @@ export class Zerox1Agent {
230
280
  return agent
231
281
  }
232
282
 
283
+ /**
284
+ * Fetch active hosting nodes from the 0x01 aggregator.
285
+ * These are nodes that offer to relay envelopes for
286
+ * lightweight/serverless agents that cannot run a full node.
287
+ */
288
+ static async listHostingNodes(
289
+ aggregatorUrl = 'https://api.0x01.world'
290
+ ): Promise<HostingNode[]> {
291
+ const res = await fetch(`${aggregatorUrl}/hosting/nodes`)
292
+ if (!res.ok) throw new Error(`Failed to fetch hosting nodes: HTTP ${res.status}`)
293
+ return res.json() as Promise<HostingNode[]>
294
+ }
295
+
296
+ /**
297
+ * Register a new hosted-agent session on a hosting node.
298
+ * The host generates a fresh Ed25519 sub-keypair; your
299
+ * agent_id is its public key. Keep the token secret.
300
+ *
301
+ * @param hostApiUrl - Base URL of the selected hosting node.
302
+ * @returns { agent_id, token } — persist both for reconnection.
303
+ */
304
+ static async registerHosted(hostApiUrl: string): Promise<HostedRegistration> {
305
+ const url = hostApiUrl.replace(/\/$/, '')
306
+ const res = await fetch(`${url}/hosted/register`, { method: 'POST' })
307
+ if (!res.ok) {
308
+ const body = await res.text()
309
+ throw new Error(`registerHosted failed (${res.status}): ${body}`)
310
+ }
311
+ return res.json() as Promise<HostedRegistration>
312
+ }
313
+
314
+ /**
315
+ * Create a hosted agent that delegates to an existing host node.
316
+ * No binary is spawned — the SDK connects to the host's WebSocket inbox
317
+ * and routes outbound sends through the host.
318
+ *
319
+ * @param config - { hostApiUrl, token } returned from registerHosted().
320
+ */
321
+ static createHosted(config: HostedAgentConfig): HostedAgent {
322
+ return new HostedAgent(config)
323
+ }
324
+
325
+ // ── Ownership claims ───────────────────────────────────────────────────────
326
+
327
+ /**
328
+ * Propose a human wallet as the owner of this agent.
329
+ *
330
+ * Called by the agent or its operator. The human wallet is notified
331
+ * and can accept via `accept_claim()` in the agent-ownership Solana program,
332
+ * then call `claimOwner()` (or POST /agents/:id/claim-owner) to confirm.
333
+ *
334
+ * Optional — agents without an owner are fully functional on the mesh.
335
+ *
336
+ * @param agentId - Hex-encoded 64-char agent ID.
337
+ * @param proposedOwner - Base58 Solana wallet address of the intended human.
338
+ * @param aggregatorUrl - Aggregator base URL (defaults to mainnet).
339
+ */
340
+ static async proposeOwner(
341
+ agentId: string,
342
+ proposedOwner: string,
343
+ aggregatorUrl = 'https://api.0x01.world',
344
+ ): Promise<{ status: string; agent_id: string; proposed_owner: string }> {
345
+ const res = await fetch(`${aggregatorUrl}/agents/${agentId}/propose-owner`, {
346
+ method: 'POST',
347
+ headers: { 'Content-Type': 'application/json' },
348
+ body: JSON.stringify({ proposed_owner: proposedOwner }),
349
+ })
350
+ if (!res.ok) {
351
+ const err = await res.json().catch(() => ({ error: `HTTP ${res.status}` }))
352
+ throw new Error(`proposeOwner failed: ${(err as { error?: string }).error ?? res.status}`)
353
+ }
354
+ return res.json() as Promise<{ status: string; agent_id: string; proposed_owner: string }>
355
+ }
356
+
357
+ /**
358
+ * Read the current ownership status of an agent.
359
+ *
360
+ * Possible responses:
361
+ * - `{ status: "unclaimed" }`
362
+ * - `{ status: "pending", proposed_owner: "7XsB...", proposed_at: 123 }`
363
+ * - `{ status: "claimed", owner: "7XsB...", claimed_at: 123 }`
364
+ *
365
+ * @param agentId - Hex-encoded 64-char agent ID.
366
+ * @param aggregatorUrl - Aggregator base URL.
367
+ */
368
+ static async getOwner(
369
+ agentId: string,
370
+ aggregatorUrl = 'https://api.0x01.world',
371
+ ): Promise<OwnerStatus> {
372
+ const res = await fetch(`${aggregatorUrl}/agents/${agentId}/owner`)
373
+ if (!res.ok) throw new Error(`getOwner failed: HTTP ${res.status}`)
374
+ return res.json() as Promise<OwnerStatus>
375
+ }
376
+
233
377
  private _config!: Zerox1AgentConfig
234
378
 
235
379
  // ── Lifecycle ─────────────────────────────────────────────────────────────
@@ -480,3 +624,175 @@ export class Zerox1Agent {
480
624
  ws.on('error', () => { /* close event handles reconnect */ })
481
625
  }
482
626
  }
627
+
628
+ // ============================================================================
629
+ // HostedAgent — lightweight hosted-mode client
630
+ // ============================================================================
631
+
632
+ /**
633
+ * A hosted agent that delegates signing and routing to a host node.
634
+ * No binary is spawned. Inbound envelopes are streamed via WebSocket;
635
+ * outbound sends go through `POST /hosted/send` on the host.
636
+ *
637
+ * Obtain via `Zerox1Agent.createHosted({ hostApiUrl, token })`.
638
+ */
639
+ export class HostedAgent {
640
+ private ws: WebSocket | null = null
641
+ private handlers: Map<string, Handler[]> = new Map()
642
+ private _reconnectDelay: number = 1000
643
+ private _running = false
644
+ private readonly baseUrl: string
645
+ private readonly token: string
646
+
647
+ constructor(config: HostedAgentConfig) {
648
+ this.baseUrl = config.hostApiUrl.replace(/\/$/, '')
649
+ this.token = config.token
650
+ }
651
+
652
+ /**
653
+ * Connect to the host node's inbox WebSocket.
654
+ * Resolves once the connection is open.
655
+ */
656
+ async start(): Promise<void> {
657
+ this._running = true
658
+ await this._connect()
659
+ }
660
+
661
+ /** Disconnect from the host node. */
662
+ disconnect(): void {
663
+ this._running = false
664
+ this.ws?.close()
665
+ this.ws = null
666
+ }
667
+
668
+ /**
669
+ * Register a handler for a message type.
670
+ * Use `'*'` to catch all inbound message types.
671
+ */
672
+ on(msgType: MsgType | '*', handler: Handler): this {
673
+ const key = msgType === '*' ? '__all__' : msgType
674
+ const list = this.handlers.get(key) ?? []
675
+ list.push(handler)
676
+ this.handlers.set(key, list)
677
+ return this
678
+ }
679
+
680
+ /**
681
+ * Send an envelope through the host node.
682
+ * The host signs it with this agent's sub-keypair and broadcasts via libp2p.
683
+ */
684
+ async send(params: SendParams): Promise<void> {
685
+ const res = await fetch(`${this.baseUrl}/hosted/send`, {
686
+ method: 'POST',
687
+ headers: {
688
+ 'Content-Type': 'application/json',
689
+ 'Authorization': `Bearer ${this.token}`,
690
+ },
691
+ body: JSON.stringify({
692
+ msg_type: params.msgType,
693
+ recipient: params.recipient ?? null,
694
+ conversation_id: params.conversationId,
695
+ payload_hex: Buffer.from(params.payload).toString('hex'),
696
+ }),
697
+ })
698
+ if (!res.ok && res.status !== 204) {
699
+ const body = await res.text()
700
+ throw new Error(`hosted send failed (${res.status}): ${body}`)
701
+ }
702
+ }
703
+
704
+ /**
705
+ * Send a FEEDBACK envelope with CBOR-encoded payload.
706
+ * Mirrors `Zerox1Agent.sendFeedback()`.
707
+ */
708
+ async sendFeedback(params: SendFeedbackParams): Promise<void> {
709
+ if (params.score < -100 || params.score > 100)
710
+ throw new RangeError(`score must be in [-100, 100], got ${params.score}`)
711
+
712
+ const outcomeMap = { negative: 0, neutral: 1, positive: 2 } as const
713
+ const roleMap = { participant: 0, notary: 1 } as const
714
+
715
+ const payload = encodeFeedbackCbor(
716
+ params.conversationId,
717
+ params.targetAgent,
718
+ params.score,
719
+ outcomeMap[params.outcome],
720
+ false,
721
+ roleMap[params.role],
722
+ )
723
+
724
+ return this.send({ msgType: 'FEEDBACK', conversationId: params.conversationId, payload })
725
+ }
726
+
727
+ /** Generate a random 16-byte conversation ID as hex. */
728
+ newConversationId(): string {
729
+ const bytes = new Uint8Array(16)
730
+ crypto.getRandomValues(bytes)
731
+ return Buffer.from(bytes).toString('hex')
732
+ }
733
+
734
+ // ── Internal ──────────────────────────────────────────────────────────────
735
+
736
+ private async _connect(): Promise<void> {
737
+ const wsUrl = `${this.baseUrl.replace(/^http/, 'ws')}/ws/hosted/inbox`
738
+ return new Promise((resolve, reject) => {
739
+ const ws = new WebSocket(wsUrl, {
740
+ headers: { Authorization: `Bearer ${this.token}` },
741
+ })
742
+ this.ws = ws
743
+
744
+ ws.once('open', () => {
745
+ this._reconnectDelay = 1000
746
+ resolve()
747
+ })
748
+ ws.once('error', reject)
749
+
750
+ ws.on('message', (data) => {
751
+ try {
752
+ const raw = JSON.parse(data.toString())
753
+ const env: InboundEnvelope = {
754
+ msgType: raw.msg_type,
755
+ sender: raw.sender,
756
+ recipient: raw.recipient,
757
+ conversationId: raw.conversation_id,
758
+ slot: raw.slot,
759
+ nonce: raw.nonce,
760
+ payloadB64: raw.payload_b64,
761
+ feedback: raw.feedback ? {
762
+ conversationId: raw.feedback.conversation_id,
763
+ targetAgent: raw.feedback.target_agent,
764
+ score: raw.feedback.score,
765
+ outcome: raw.feedback.outcome,
766
+ isDispute: raw.feedback.is_dispute,
767
+ role: raw.feedback.role,
768
+ } : undefined,
769
+ notarizeBid: raw.notarize_bid ? {
770
+ bidType: raw.notarize_bid.bid_type,
771
+ conversationId: raw.notarize_bid.conversation_id,
772
+ opaqueB64: raw.notarize_bid.opaque_b64,
773
+ } : undefined,
774
+ }
775
+ this._dispatch(env)
776
+ } catch { /* malformed — ignore */ }
777
+ })
778
+
779
+ ws.on('close', () => {
780
+ if (this._running) {
781
+ setTimeout(() => {
782
+ this._reconnectDelay = 1000
783
+ this._connect().catch(() => { })
784
+ }, this._reconnectDelay)
785
+ this._reconnectDelay = Math.min(this._reconnectDelay * 2, 30_000)
786
+ }
787
+ })
788
+ })
789
+ }
790
+
791
+ private _dispatch(env: InboundEnvelope): void {
792
+ const specific = this.handlers.get(env.msgType) ?? []
793
+ const wildcard = this.handlers.get('__all__') ?? []
794
+ for (const h of [...specific, ...wildcard]) {
795
+ try { void h(env) } catch { /* handler errors are isolated */ }
796
+ }
797
+ }
798
+ }