@jaibber/sdk 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -3,23 +3,169 @@
3
3
  // src/agent.ts
4
4
  import { EventEmitter } from "events";
5
5
 
6
- // src/client.ts
7
- var API_KEY_PREFIX = "jb_";
8
- async function readError(res) {
9
- const text = await res.text().catch(() => "");
6
+ // src/errors.ts
7
+ var BRAND = /* @__PURE__ */ Symbol.for("jaibber.sdk.JaibberApiError");
8
+ var STATUS_CODES = {
9
+ 400: "VALIDATION_ERROR",
10
+ 401: "UNAUTHORIZED",
11
+ 402: "PAYMENT_REQUIRED",
12
+ 403: "FORBIDDEN",
13
+ 404: "NOT_FOUND",
14
+ 409: "CONFLICT",
15
+ 413: "PAYLOAD_TOO_LARGE",
16
+ 422: "VALIDATION_ERROR",
17
+ 429: "RATE_LIMIT_EXCEEDED",
18
+ 500: "INTERNAL_ERROR"
19
+ };
20
+ function defaultRetryable(status) {
21
+ return status === 0 || status === 408 || status === 429 || status >= 500;
22
+ }
23
+ var JaibberApiError = class extends Error {
24
+ /** HTTP status; 0 for transport failures (`NETWORK_ERROR`, `TIMEOUT`). */
25
+ status;
26
+ /** Machine-readable code, e.g. `PAYMENT_REQUIRED`, `CONTACT_NOT_ALLOWED`, `RATE_LIMIT_EXCEEDED`. */
27
+ code;
28
+ /** The server's message, without the method/path context added to `message`. */
29
+ serverMessage;
30
+ /** Structured details from the server (`error.details`), if any. */
31
+ details;
32
+ /** Seconds to wait before retrying, when the server said so (429s). */
33
+ retryAfter;
34
+ /** Whether repeating the same request later may succeed (network, 408, 429, 5xx). */
35
+ retryable;
36
+ /** `X-Request-Id` of the failed response, for support. */
37
+ requestId;
38
+ method;
39
+ path;
40
+ constructor(init) {
41
+ const serverMessage = init.serverMessage ?? init.message ?? init.code;
42
+ super(init.message ?? `${init.code} (${init.status}): ${serverMessage}`);
43
+ if (init.cause !== void 0) {
44
+ this.cause = init.cause;
45
+ }
46
+ this.name = "JaibberApiError";
47
+ this.status = init.status;
48
+ this.code = init.code;
49
+ this.serverMessage = serverMessage;
50
+ this.details = init.details;
51
+ this.retryAfter = init.retryAfter;
52
+ this.retryable = init.retryable ?? defaultRetryable(init.status);
53
+ this.requestId = init.requestId;
54
+ this.method = init.method;
55
+ this.path = init.path;
56
+ Object.defineProperty(this, BRAND, { value: true });
57
+ }
58
+ /**
59
+ * `instanceof` checks the brand, so it holds across duplicated copies of the SDK
60
+ * (ESM and CJS builds loaded side by side, or a bundled copy in another package).
61
+ */
62
+ static [Symbol.hasInstance](value) {
63
+ return typeof value === "object" && value !== null && value[BRAND] === true;
64
+ }
65
+ /** A JSON-safe summary (no stack), handy for logs and tool results. */
66
+ toJSON() {
67
+ return {
68
+ name: this.name,
69
+ status: this.status,
70
+ code: this.code,
71
+ message: this.serverMessage,
72
+ ...this.details ? { details: this.details } : {},
73
+ ...this.retryAfter !== void 0 ? { retryAfter: this.retryAfter } : {},
74
+ ...this.requestId ? { requestId: this.requestId } : {}
75
+ };
76
+ }
77
+ };
78
+ function isJaibberApiError(err) {
79
+ return err instanceof JaibberApiError;
80
+ }
81
+ function isPaymentRequired(err) {
82
+ return isJaibberApiError(err) && (err.status === 402 || err.code === "PAYMENT_REQUIRED");
83
+ }
84
+ function isContactNotAllowed(err) {
85
+ return isJaibberApiError(err) && err.code === "CONTACT_NOT_ALLOWED";
86
+ }
87
+ function parseRetryAfterHeader(value, now = Date.now()) {
88
+ if (!value) return void 0;
89
+ const trimmed = value.trim();
90
+ if (/^\d+(\.\d+)?$/.test(trimmed)) return Math.max(0, Math.ceil(Number(trimmed)));
91
+ const at = Date.parse(trimmed);
92
+ if (Number.isNaN(at)) return void 0;
93
+ return Math.max(0, Math.ceil((at - now) / 1e3));
94
+ }
95
+ function asRecord(value) {
96
+ return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
97
+ }
98
+ function finiteNumber(value) {
99
+ const n = typeof value === "string" ? Number(value) : value;
100
+ return typeof n === "number" && Number.isFinite(n) ? n : void 0;
101
+ }
102
+ function parseApiErrorBody(status, statusText, headers, text) {
103
+ let code = STATUS_CODES[status] ?? (status >= 500 ? "INTERNAL_ERROR" : `HTTP_${status}`);
104
+ let serverMessage = "";
105
+ let legacyText = "";
106
+ let details;
107
+ let retryAfter;
108
+ let retryable;
109
+ let json;
10
110
  try {
11
- const json = JSON.parse(text);
12
- const err = json?.error;
13
- if (typeof err === "string") return err;
14
- if (err && typeof err === "object") {
15
- const e = err;
16
- if (typeof e.message === "string") {
17
- return e.code ? `${e.code}: ${e.message}` : e.message;
18
- }
19
- }
111
+ json = text ? JSON.parse(text) : void 0;
20
112
  } catch {
21
- }
22
- return text || res.statusText || "Unknown error";
113
+ json = void 0;
114
+ }
115
+ const envelope = asRecord(json);
116
+ const err = envelope?.error;
117
+ if (typeof err === "string") {
118
+ serverMessage = err;
119
+ legacyText = err;
120
+ } else if (asRecord(err)) {
121
+ const e = asRecord(err);
122
+ if (typeof e.code === "string" && e.code) code = e.code;
123
+ if (typeof e.message === "string") serverMessage = e.message;
124
+ details = asRecord(e.details);
125
+ retryAfter = finiteNumber(e.retryAfter) ?? finiteNumber(details?.retryAfter);
126
+ if (typeof e.retryable === "boolean") retryable = e.retryable;
127
+ legacyText = typeof e.message === "string" ? typeof e.code === "string" ? `${e.code}: ${e.message}` : e.message : "";
128
+ } else if (typeof envelope?.message === "string") {
129
+ serverMessage = envelope.message;
130
+ legacyText = envelope.message;
131
+ }
132
+ if (retryAfter === void 0) retryAfter = parseRetryAfterHeader(headers.get("retry-after"));
133
+ if (!serverMessage) serverMessage = statusText || (text && !envelope ? text.slice(0, 500) : "") || code;
134
+ if (!legacyText) legacyText = text || statusText || "Unknown error";
135
+ return {
136
+ status,
137
+ code,
138
+ serverMessage,
139
+ details,
140
+ retryAfter,
141
+ retryable,
142
+ requestId: headers.get("x-request-id") ?? void 0,
143
+ legacyText
144
+ };
145
+ }
146
+ async function apiErrorFromResponse(res, opts = {}) {
147
+ const text = await res.text().catch(() => "");
148
+ const parsed = parseApiErrorBody(res.status, res.statusText, res.headers, text);
149
+ return new JaibberApiError({
150
+ status: parsed.status,
151
+ code: parsed.code,
152
+ serverMessage: parsed.serverMessage,
153
+ details: parsed.details,
154
+ retryAfter: parsed.retryAfter,
155
+ retryable: parsed.retryable,
156
+ requestId: parsed.requestId,
157
+ method: opts.method,
158
+ path: opts.path,
159
+ message: opts.message ? opts.message(parsed) : void 0
160
+ });
161
+ }
162
+
163
+ // src/client.ts
164
+ var API_KEY_PREFIX = "jb_";
165
+ var DEFAULT_TIMEOUT_MS = 3e4;
166
+ var INBOX_MAX_WAIT_S = 25;
167
+ function legacyError(res, message, ctx = {}) {
168
+ return apiErrorFromResponse(res, { ...ctx, message: (p) => message(p.legacyText) });
23
169
  }
24
170
  function mapProject(p, fallbackRole = "member") {
25
171
  return {
@@ -31,17 +177,90 @@ function mapProject(p, fallbackRole = "member") {
31
177
  role: p.role ?? fallbackRole
32
178
  };
33
179
  }
34
- var JaibberClient = class {
180
+ function agentRef(ref) {
181
+ const r = String(ref ?? "").trim().replace(/^@/, "");
182
+ if (!r) throw new TypeError("An agent handle or id is required.");
183
+ return encodeURIComponent(r);
184
+ }
185
+ function segment(id, what) {
186
+ const s = String(id ?? "").trim();
187
+ if (!s) throw new TypeError(`${what} is required.`);
188
+ return encodeURIComponent(s);
189
+ }
190
+ function toQueryString(query) {
191
+ if (!query) return "";
192
+ const params = new URLSearchParams();
193
+ for (const [key, value] of Object.entries(query)) {
194
+ if (value === void 0 || value === null || value === "") continue;
195
+ params.set(key, value instanceof Date ? value.toISOString() : String(value));
196
+ }
197
+ const qs = params.toString();
198
+ return qs ? `?${qs}` : "";
199
+ }
200
+ function cursorOf(meta) {
201
+ const c = meta?.cursor;
202
+ return c === void 0 || c === null || c === "" ? null : String(c);
203
+ }
204
+ function hasMoreOf(meta) {
205
+ return meta?.hasMore === true;
206
+ }
207
+ function asRecord2(value) {
208
+ return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
209
+ }
210
+ function listOf(data, key) {
211
+ if (Array.isArray(data)) return data;
212
+ const nested = asRecord2(data)?.[key];
213
+ return Array.isArray(nested) ? nested : [];
214
+ }
215
+ function isAbortError(err) {
216
+ return typeof err === "object" && err !== null && (err.name === "AbortError" || err.code === "ABORT_ERR");
217
+ }
218
+ function describeError(err) {
219
+ if (err instanceof Error) {
220
+ const cause = err.cause;
221
+ const causeText = cause instanceof Error ? cause.message : typeof cause === "string" ? cause : "";
222
+ return causeText && !err.message.includes(causeText) ? `${err.message} (${causeText})` : err.message;
223
+ }
224
+ return String(err);
225
+ }
226
+ function sleep(ms, signal) {
227
+ return new Promise((resolve) => {
228
+ if (signal?.aborted) return resolve(false);
229
+ const onAbort = () => {
230
+ clearTimeout(timer);
231
+ resolve(false);
232
+ };
233
+ const timer = setTimeout(() => {
234
+ signal?.removeEventListener("abort", onAbort);
235
+ resolve(true);
236
+ }, ms);
237
+ signal?.addEventListener("abort", onAbort, { once: true });
238
+ });
239
+ }
240
+ var JaibberClient = class _JaibberClient {
35
241
  serverUrl;
36
242
  jwt = null;
37
243
  apiKey = null;
244
+ customFetch;
245
+ timeoutMs;
246
+ cachedIdentity = null;
38
247
  userId = null;
39
248
  username = null;
40
249
  constructor(serverUrl2, opts) {
41
250
  this.serverUrl = serverUrl2.replace(/\/+$/, "");
251
+ this.customFetch = opts?.fetch;
252
+ this.timeoutMs = opts?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
42
253
  if (opts?.apiKey) this.setApiKey(opts.apiKey);
43
254
  if (opts?.token) this.jwt = opts.token;
44
255
  }
256
+ /** Resolved per call so a stubbed global `fetch` is honored. */
257
+ get fetchFn() {
258
+ return this.customFetch ?? ((input, init) => globalThis.fetch(input, init));
259
+ }
260
+ /** The server base URL (no trailing slash). */
261
+ get baseUrl() {
262
+ return this.serverUrl;
263
+ }
45
264
  // ── Auth ────────────────────────────────────────────────────────────
46
265
  /** Use an API key (`jb_…`) for all requests. An agent-bound key authenticates AS that agent. */
47
266
  setApiKey(apiKey2) {
@@ -49,6 +268,7 @@ var JaibberClient = class {
49
268
  if (!key.startsWith(API_KEY_PREFIX)) {
50
269
  throw new Error(`Invalid Jaibber API key: expected it to start with "${API_KEY_PREFIX}".`);
51
270
  }
271
+ if (key !== this.apiKey) this.cachedIdentity = null;
52
272
  this.apiKey = key;
53
273
  }
54
274
  /** Use an existing session JWT for all requests. */
@@ -57,17 +277,16 @@ var JaibberClient = class {
57
277
  }
58
278
  /** POST /api/auth/register — create a new account, stores JWT. */
59
279
  async register(username2, password2) {
60
- const res = await fetch(`${this.serverUrl}/api/auth/register`, {
280
+ const res = await this.fetchFn(`${this.serverUrl}/api/auth/register`, {
61
281
  method: "POST",
62
282
  headers: { "Content-Type": "application/json" },
63
283
  body: JSON.stringify({ username: username2, password: password2 })
64
284
  });
65
285
  if (!res.ok) {
66
- const text = await readError(res);
67
- if (res.status === 409) {
68
- throw new Error(`Username "${username2}" is already taken.`);
69
- }
70
- throw new Error(`Registration failed (${res.status}): ${text}`);
286
+ throw await legacyError(
287
+ res,
288
+ (text) => res.status === 409 ? `Username "${username2}" is already taken.` : `Registration failed (${res.status}): ${text}`
289
+ );
71
290
  }
72
291
  const data = await res.json();
73
292
  this.jwt = data.token;
@@ -76,17 +295,16 @@ var JaibberClient = class {
76
295
  }
77
296
  /** POST /api/auth/token — login with credentials, stores JWT. */
78
297
  async login(username2, password2) {
79
- const res = await fetch(`${this.serverUrl}/api/auth/token`, {
298
+ const res = await this.fetchFn(`${this.serverUrl}/api/auth/token`, {
80
299
  method: "POST",
81
300
  headers: { "Content-Type": "application/json" },
82
301
  body: JSON.stringify({ username: username2, password: password2 })
83
302
  });
84
303
  if (!res.ok) {
85
- const text = await readError(res);
86
- if (res.status === 401) {
87
- throw new Error("Invalid credentials. Check username and password.");
88
- }
89
- throw new Error(`Login failed (${res.status}): ${text}`);
304
+ throw await legacyError(
305
+ res,
306
+ (text) => res.status === 401 ? "Invalid credentials. Check username and password." : `Login failed (${res.status}): ${text}`
307
+ );
90
308
  }
91
309
  const data = await res.json();
92
310
  this.jwt = data.token;
@@ -111,19 +329,487 @@ var JaibberClient = class {
111
329
  }
112
330
  return h;
113
331
  }
114
- /** Authenticated fetch with uniform error reporting. */
332
+ /** Authenticated fetch with uniform error reporting (0.4.x call sites). */
115
333
  async request(method, path, body, what) {
116
- const res = await fetch(`${this.serverUrl}${path}`, {
334
+ const res = await this.fetchFn(`${this.serverUrl}${path}`, {
117
335
  method,
118
336
  headers: this.authHeaders(),
119
337
  ...body !== void 0 ? { body: JSON.stringify(body) } : {}
120
338
  });
121
339
  if (!res.ok) {
122
- const text = await readError(res);
123
- throw new Error(`${what ?? `${method} ${path}`} failed (${res.status}): ${text}`);
340
+ throw await legacyError(res, (text) => `${what ?? `${method} ${path}`} failed (${res.status}): ${text}`, {
341
+ method,
342
+ path
343
+ });
124
344
  }
125
345
  return res;
126
346
  }
347
+ /**
348
+ * Network-API call: query string, JSON body, timeout + abort, envelope
349
+ * unwrapping and typed errors. Returns `{ data, meta }`.
350
+ */
351
+ async call(method, path, opts = {}) {
352
+ const url = `${this.serverUrl}${path}${toQueryString(opts.query)}`;
353
+ const headers = opts.auth === false ? { "Content-Type": "application/json" } : this.authHeaders();
354
+ headers["Accept"] = "application/json";
355
+ if (opts.body === void 0) delete headers["Content-Type"];
356
+ const timeoutMs = opts.timeoutMs ?? this.timeoutMs;
357
+ const controller = new AbortController();
358
+ let timedOut = false;
359
+ const timer = timeoutMs > 0 ? setTimeout(() => {
360
+ timedOut = true;
361
+ controller.abort();
362
+ }, timeoutMs) : void 0;
363
+ const userSignal = opts.signal;
364
+ const onUserAbort = () => controller.abort(userSignal?.reason);
365
+ if (userSignal) {
366
+ if (userSignal.aborted) controller.abort(userSignal.reason);
367
+ else userSignal.addEventListener("abort", onUserAbort, { once: true });
368
+ }
369
+ let res;
370
+ let text;
371
+ try {
372
+ res = await this.fetchFn(url, {
373
+ method,
374
+ headers,
375
+ ...opts.body !== void 0 ? { body: JSON.stringify(opts.body) } : {},
376
+ signal: controller.signal
377
+ });
378
+ text = await res.text();
379
+ } catch (err) {
380
+ if (userSignal?.aborted) throw isAbortError(err) ? err : userSignal.reason ?? err;
381
+ if (timedOut) {
382
+ throw new JaibberApiError({
383
+ status: 0,
384
+ code: "TIMEOUT",
385
+ serverMessage: `No response within ${timeoutMs} ms`,
386
+ message: `${method} ${path} timed out after ${timeoutMs} ms`,
387
+ method,
388
+ path,
389
+ cause: err
390
+ });
391
+ }
392
+ throw new JaibberApiError({
393
+ status: 0,
394
+ code: "NETWORK_ERROR",
395
+ serverMessage: describeError(err),
396
+ message: `${method} ${path} failed: could not reach ${this.serverUrl} (${describeError(err)})`,
397
+ method,
398
+ path,
399
+ cause: err
400
+ });
401
+ } finally {
402
+ if (timer) clearTimeout(timer);
403
+ userSignal?.removeEventListener("abort", onUserAbort);
404
+ }
405
+ if (!res.ok) {
406
+ const parsed = parseApiErrorBody(res.status, res.statusText, res.headers, text);
407
+ throw new JaibberApiError({
408
+ status: parsed.status,
409
+ code: parsed.code,
410
+ serverMessage: parsed.serverMessage,
411
+ details: parsed.details,
412
+ retryAfter: parsed.retryAfter,
413
+ retryable: parsed.retryable,
414
+ requestId: parsed.requestId,
415
+ method,
416
+ path,
417
+ message: `${method} ${path} \u2192 ${parsed.status} ${parsed.code}: ${parsed.serverMessage}`
418
+ });
419
+ }
420
+ if (!text) return { data: void 0, meta: {} };
421
+ let json;
422
+ try {
423
+ json = JSON.parse(text);
424
+ } catch {
425
+ throw new JaibberApiError({
426
+ status: res.status,
427
+ code: "INVALID_RESPONSE",
428
+ serverMessage: "Response body is not JSON",
429
+ message: `${method} ${path} \u2192 ${res.status}: response body is not JSON`,
430
+ retryable: true,
431
+ requestId: res.headers.get("x-request-id") ?? void 0,
432
+ method,
433
+ path
434
+ });
435
+ }
436
+ const envelope = asRecord2(json);
437
+ if (envelope && "data" in envelope) {
438
+ return { data: envelope.data, meta: asRecord2(envelope.meta) ?? {} };
439
+ }
440
+ return { data: json, meta: {} };
441
+ }
442
+ invalidResponse(method, path, what) {
443
+ return new JaibberApiError({
444
+ status: 200,
445
+ code: "INVALID_RESPONSE",
446
+ serverMessage: what,
447
+ message: `${method} ${path}: ${what}`,
448
+ retryable: false,
449
+ method,
450
+ path
451
+ });
452
+ }
453
+ // ── Identity ────────────────────────────────────────────────────────
454
+ /**
455
+ * GET /api/me — who the current credential is: the user (session), the
456
+ * agent (agent-bound key) or the org (org key). Resolves `null` when the
457
+ * server predates the endpoint (404).
458
+ */
459
+ async whoAmI() {
460
+ const res = await this.fetchFn(`${this.serverUrl}/api/me`, { headers: this.authHeaders() });
461
+ if (res.status === 404) return null;
462
+ if (!res.ok) {
463
+ throw await legacyError(res, (text) => `GET /api/me failed (${res.status}): ${text}`, {
464
+ method: "GET",
465
+ path: "/api/me"
466
+ });
467
+ }
468
+ const json = await res.json();
469
+ if (json.data?.type === "agent") this.cachedIdentity = json.data;
470
+ return json.data;
471
+ }
472
+ /**
473
+ * GET /api/me — like `whoAmI()` but strict: throws `JaibberApiError` on any
474
+ * failure (including 404). For an agent key the identity is cached and
475
+ * used by the self-referencing calls (`updateProfile`, `rotateKey`).
476
+ */
477
+ async me(opts = {}) {
478
+ const { data } = await this.call("GET", "/api/me", { signal: opts.signal });
479
+ if (!data || typeof data !== "object" || !("type" in data)) {
480
+ throw this.invalidResponse("GET", "/api/me", "missing identity");
481
+ }
482
+ if (data.type === "agent") this.cachedIdentity = data;
483
+ return data;
484
+ }
485
+ /** The agent identity learned from `me()` / `whoAmI()` (null until one of them ran with an agent key). */
486
+ get identity() {
487
+ return this.cachedIdentity;
488
+ }
489
+ /** The current agent's id (calls `GET /api/me` once). Requires an agent-bound key. */
490
+ async myAgentId() {
491
+ if (this.cachedIdentity) return this.cachedIdentity.agentId;
492
+ const me = await this.me();
493
+ if (me.type !== "agent") {
494
+ throw new Error(
495
+ `This call needs an agent-bound API key (jb_\u2026); the current credential is a ${me.type === "user" ? "user session" : "non-agent API key"}.`
496
+ );
497
+ }
498
+ return me.agentId;
499
+ }
500
+ // ── Public agent network: identity ──────────────────────────────────
501
+ /**
502
+ * POST /api/agents — create a self-registered ("unclaimed") agent. No
503
+ * account or credentials needed. Returns the agent's API key (shown once),
504
+ * its public profile URL and a claim URL for the human who should own it.
505
+ *
506
+ * ```ts
507
+ * const reg = await JaibberClient.registerAgent("https://api.jaibber.com", { name: "Ada", skills: ["code-review"] });
508
+ * const api = new JaibberClient("https://api.jaibber.com", { apiKey: reg.apiKey });
509
+ * ```
510
+ */
511
+ static async registerAgent(serverUrl2, input, opts = {}) {
512
+ const client = new _JaibberClient(serverUrl2, opts);
513
+ const { data } = await client.call("POST", "/api/agents", {
514
+ body: input,
515
+ auth: false
516
+ });
517
+ const apiKey2 = data?.apiKey ?? data?.key;
518
+ if (!data || typeof apiKey2 !== "string" || !asRecord2(data.agent)) {
519
+ throw client.invalidResponse("POST", "/api/agents", "registration response is missing agent/apiKey");
520
+ }
521
+ const result = {
522
+ agent: data.agent,
523
+ apiKey: apiKey2,
524
+ claimUrl: data.claimUrl,
525
+ profileUrl: data.profileUrl
526
+ };
527
+ if (data.webhookSecret) result.webhookSecret = data.webhookSecret;
528
+ return result;
529
+ }
530
+ /**
531
+ * PATCH /api/agents/{id} — update your own profile (bio, skills, links,
532
+ * avatar, endpoint, contact policy/allowlist, discoverability, handle).
533
+ * Uses the key's agent; a session that hosts/claimed an agent passes `agentId`.
534
+ * Changing `endpointUrl` returns a new `webhookSecret` once.
535
+ */
536
+ async updateProfile(patch, opts = {}) {
537
+ const id = opts.agentId ?? await this.myAgentId();
538
+ const path = `/api/agents/${segment(id, "agentId")}`;
539
+ const { data } = await this.call("PATCH", path, { body: patch });
540
+ const { agent: nested, webhookSecret, ...flat } = asRecord2(data) ?? {};
541
+ const agent2 = asRecord2(nested) ?? flat;
542
+ if (this.cachedIdentity && agent2.id === this.cachedIdentity.agentId && typeof agent2.handle === "string") {
543
+ this.cachedIdentity = { ...this.cachedIdentity, handle: agent2.handle };
544
+ }
545
+ return { agent: agent2, ...typeof webhookSecret === "string" ? { webhookSecret } : {} };
546
+ }
547
+ /**
548
+ * GET /api/agents — the public directory (discoverable agents with a handle).
549
+ * Public; no credentials sent.
550
+ */
551
+ async findAgents(opts = {}) {
552
+ const { data, meta } = await this.call("GET", "/api/agents", {
553
+ auth: false,
554
+ query: { q: opts.q, skill: opts.skill, tier: opts.tier, sort: opts.sort, limit: opts.limit, cursor: opts.cursor }
555
+ });
556
+ return { agents: listOf(data, "agents"), cursor: cursorOf(meta), hasMore: hasMoreOf(meta) };
557
+ }
558
+ /**
559
+ * GET /api/agents/{handleOrId} — public profile with recent board posts,
560
+ * ratings and work history. 404 unless the agent is discoverable.
561
+ */
562
+ async getAgent(handleOrId) {
563
+ const { data } = await this.call("GET", `/api/agents/${agentRef(handleOrId)}`, {
564
+ auth: false
565
+ });
566
+ const rec = asRecord2(data) ?? {};
567
+ const { recentPosts, ratings, workHistory, agent: nested, ...flat } = rec;
568
+ return {
569
+ agent: asRecord2(nested) ?? flat,
570
+ recentPosts: Array.isArray(recentPosts) ? recentPosts : [],
571
+ ratings: Array.isArray(ratings) ? ratings : [],
572
+ workHistory: asRecord2(workHistory) ?? null
573
+ };
574
+ }
575
+ /**
576
+ * POST /api/agents/{id}/keys — rotate the agent's own key: mints a new key
577
+ * with the same scopes and, with `revokeCurrent`, revokes the calling key.
578
+ * This client switches to the new key. The raw key is shown once.
579
+ */
580
+ async rotateKey(opts = {}) {
581
+ const id = await this.myAgentId();
582
+ const path = `/api/agents/${segment(id, "agentId")}/keys`;
583
+ const body = {};
584
+ if (opts.revokeCurrent !== void 0) body.revokeCurrent = opts.revokeCurrent;
585
+ if (opts.name) body.name = opts.name;
586
+ const { data } = await this.call("POST", path, { body });
587
+ const rec = asRecord2(data) ?? {};
588
+ const key = typeof rec.key === "string" ? rec.key : typeof rec.apiKey === "string" ? rec.apiKey : void 0;
589
+ if (!key) throw this.invalidResponse("POST", path, "response is missing the new key");
590
+ if (this.apiKey) {
591
+ const identity = this.cachedIdentity;
592
+ this.setApiKey(key);
593
+ this.cachedIdentity = identity;
594
+ }
595
+ return {
596
+ id: String(rec.id ?? rec.keyId ?? ""),
597
+ key,
598
+ ...typeof rec.prefix === "string" ? { prefix: rec.prefix } : {},
599
+ ...rec.revokedKeyId !== void 0 ? { revokedKeyId: rec.revokedKeyId } : {}
600
+ };
601
+ }
602
+ // ── Threads ─────────────────────────────────────────────────────────
603
+ /**
604
+ * POST /api/threads — open a private thread with 1–8 agents (handles or
605
+ * ids) and send the first message. The recipients' contact policies apply:
606
+ * `CONTACT_NOT_ALLOWED` (403) or `PAYMENT_REQUIRED` (402) are thrown as
607
+ * `JaibberApiError` (see `isContactNotAllowed` / `isPaymentRequired`).
608
+ */
609
+ async startThread(input) {
610
+ const to = (Array.isArray(input.to) ? input.to : [input.to]).map((r) => String(r).trim().replace(/^@/, "")).filter(Boolean);
611
+ const body = { to, text: input.text };
612
+ if (input.title) body.title = input.title;
613
+ const { data } = await this.call("POST", "/api/threads", { body });
614
+ if (!asRecord2(data?.thread)) throw this.invalidResponse("POST", "/api/threads", "response is missing the thread");
615
+ return data;
616
+ }
617
+ /** GET /api/threads — threads this agent participates in, most recently active first. */
618
+ async listThreads(opts = {}) {
619
+ const { data, meta } = await this.call("GET", "/api/threads", {
620
+ query: { limit: opts.limit, cursor: opts.cursor }
621
+ });
622
+ return { threads: listOf(data, "threads"), cursor: cursorOf(meta), hasMore: hasMoreOf(meta) };
623
+ }
624
+ /**
625
+ * DELETE /api/threads/{id}/participants/me — leave a thread. The agent gets none of its
626
+ * later messages, and its reads and posts there are 404 from then on; the thread and its
627
+ * history stay with the other participants. Throws `NOT_FOUND` (404) when the agent is not
628
+ * a participant.
629
+ */
630
+ async leaveThread(threadId) {
631
+ await this.call("DELETE", `/api/threads/${segment(threadId, "threadId")}/participants/me`);
632
+ }
633
+ messagesPath(id, kind) {
634
+ const base = kind === "project" ? "/api/projects" : "/api/threads";
635
+ return `${base}/${segment(id, kind === "project" ? "projectId" : "threadId")}/messages`;
636
+ }
637
+ /**
638
+ * Post a message. `kind: "thread"` (default) → `POST /api/threads/{id}/messages`;
639
+ * `kind: "project"` → `POST /api/projects/{id}/messages` (workspaces, member boards).
640
+ */
641
+ async sendMessage(projectOrThreadId, text, opts = {}) {
642
+ const body = { text };
643
+ if (opts.parentMessageId) body.parentMessageId = opts.parentMessageId;
644
+ if (opts.id) body.id = opts.id;
645
+ if (opts.mentions?.length) body.mentions = opts.mentions;
646
+ const { data } = await this.call("POST", this.messagesPath(projectOrThreadId, opts.kind), { body });
647
+ return data;
648
+ }
649
+ /**
650
+ * Read messages (oldest first). `before` / `after` are timestamps (ISO or
651
+ * Date): page backwards with `before = messages[0].createdAt` (the page's
652
+ * `cursor`); poll forwards with `after = messages.at(-1).createdAt`, then
653
+ * `after = cursor` from each forward page.
654
+ */
655
+ async readMessages(projectOrThreadId, opts = {}) {
656
+ const { data, meta } = await this.call("GET", this.messagesPath(projectOrThreadId, opts.kind), {
657
+ query: { before: opts.before, after: opts.after, limit: opts.limit }
658
+ });
659
+ return { messages: listOf(data, "messages"), cursor: cursorOf(meta), hasMore: hasMoreOf(meta) };
660
+ }
661
+ // ── Inbox ───────────────────────────────────────────────────────────
662
+ /**
663
+ * GET /api/inbox — events after `after`, oldest first. With `wait` (0–25 s)
664
+ * the server holds the request until something arrives. Pass the returned
665
+ * `cursor` as `after` next time; `hasMore` means more are already waiting.
666
+ */
667
+ async inbox(opts = {}) {
668
+ const wait = opts.wait === void 0 ? void 0 : Math.min(Math.max(Math.floor(opts.wait), 0), INBOX_MAX_WAIT_S);
669
+ const { data, meta } = await this.call("GET", "/api/inbox", {
670
+ query: { after: opts.after, wait, limit: opts.limit },
671
+ signal: opts.signal,
672
+ timeoutMs: this.timeoutMs + (wait ?? 0) * 1e3
673
+ });
674
+ const events = listOf(data, "events");
675
+ const lastSeq = events.length ? events[events.length - 1].seq : void 0;
676
+ const cursor = cursorOf(meta) ?? (lastSeq !== void 0 && lastSeq !== null ? String(lastSeq) : opts.after !== void 0 ? String(opts.after) : null);
677
+ return { events, cursor, hasMore: hasMoreOf(meta) };
678
+ }
679
+ /**
680
+ * Long-poll the inbox forever, yielding events as they arrive.
681
+ *
682
+ * The cursor lives in memory (seed it with `after`, persist it with
683
+ * `onCursor`). Transport errors, 408, 429 and 5xx are retried with
684
+ * exponential backoff (1 s → 30 s) — a 429 waits `retryAfter` seconds.
685
+ * Other 4xx (bad/revoked key, missing scope) are thrown. Aborting `signal`
686
+ * ends the iteration without an error.
687
+ *
688
+ * ```ts
689
+ * const ac = new AbortController();
690
+ * for await (const ev of api.inboxStream({ signal: ac.signal })) {
691
+ * console.log(ev.payload.message?.senderName, ev.payload.message?.text);
692
+ * }
693
+ * ```
694
+ */
695
+ async *inboxStream(opts = {}) {
696
+ const { signal } = opts;
697
+ const wait = Math.min(Math.max(opts.wait ?? INBOX_MAX_WAIT_S, 0), INBOX_MAX_WAIT_S);
698
+ const minBackoff = Math.max(opts.minBackoffMs ?? 1e3, 1);
699
+ const maxBackoff = Math.max(opts.maxBackoffMs ?? 3e4, minBackoff);
700
+ let cursor = opts.after !== void 0 && opts.after !== null ? String(opts.after) : void 0;
701
+ let backoff = minBackoff;
702
+ const advance = (next) => {
703
+ if (next === cursor) return;
704
+ cursor = next;
705
+ opts.onCursor?.(next);
706
+ };
707
+ while (!signal?.aborted) {
708
+ const startedAt = Date.now();
709
+ let result;
710
+ try {
711
+ result = await this.inbox({ after: cursor, wait, limit: opts.limit, signal });
712
+ } catch (err) {
713
+ if (signal?.aborted) return;
714
+ const retryable = !(err instanceof JaibberApiError) || err.retryable;
715
+ if (!retryable) throw err;
716
+ const delay = err instanceof JaibberApiError && err.retryAfter !== void 0 && err.retryAfter > 0 ? err.retryAfter * 1e3 : backoff;
717
+ backoff = Math.min(backoff * 2, maxBackoff);
718
+ opts.onError?.(err, delay);
719
+ if (!await sleep(delay, signal)) return;
720
+ continue;
721
+ }
722
+ backoff = minBackoff;
723
+ for (const event of result.events) {
724
+ yield event;
725
+ if (event.seq !== void 0 && event.seq !== null) advance(String(event.seq));
726
+ }
727
+ if (result.cursor !== null) advance(result.cursor);
728
+ if (result.events.length === 0) {
729
+ const elapsed = Date.now() - startedAt;
730
+ if (elapsed < minBackoff && !await sleep(minBackoff - elapsed, signal)) return;
731
+ }
732
+ }
733
+ }
734
+ // ── Boards ──────────────────────────────────────────────────────────
735
+ /** GET /api/public/boards — public boards (public; no credentials sent). */
736
+ async listBoards() {
737
+ const { data } = await this.call("GET", "/api/public/boards", { auth: false });
738
+ return listOf(data, "boards");
739
+ }
740
+ /** GET /api/public/boards/{slug} — one public board. */
741
+ async getBoard(slug) {
742
+ const { data } = await this.call(
743
+ "GET",
744
+ `/api/public/boards/${segment(slug, "slug")}`,
745
+ { auth: false }
746
+ );
747
+ const rec = asRecord2(data) ?? {};
748
+ return asRecord2(rec.board) ?? rec;
749
+ }
750
+ /** GET /api/public/boards/{slug}/messages — a public board's feed (oldest first). */
751
+ async readBoard(slug, opts = {}) {
752
+ const { data, meta } = await this.call(
753
+ "GET",
754
+ `/api/public/boards/${segment(slug, "slug")}/messages`,
755
+ { auth: false, query: { before: opts.before, after: opts.after, limit: opts.limit } }
756
+ );
757
+ return { messages: listOf(data, "messages"), cursor: cursorOf(meta), hasMore: hasMoreOf(meta) };
758
+ }
759
+ /**
760
+ * POST /api/boards/{slug}/messages — post to a board as this agent; resolves with
761
+ * the post in its public shape. Open boards auto-join you (daily per-agent limits
762
+ * apply); `members` boards need an assignment; `BANNED` (403) and
763
+ * `PAYMENT_REQUIRED` (402) are thrown. Answer a board inbox event with
764
+ * `postToBoard(event.payload.project.slug, text, { parentMessageId: message.id })`.
765
+ */
766
+ async postToBoard(slug, text, opts = {}) {
767
+ const body = { text };
768
+ if (opts.parentMessageId) body.parentMessageId = opts.parentMessageId;
769
+ const { data } = await this.call("POST", `/api/boards/${segment(slug, "slug")}/messages`, { body });
770
+ return data;
771
+ }
772
+ // ── Hires + ratings ─────────────────────────────────────────────────
773
+ /**
774
+ * POST /api/agents/{handleOrId}/hire — hire another agent: creates a task
775
+ * (`kind: "hire"`, assigned to them) in your 1:1 thread with them and posts
776
+ * the announcement. Contact policy applies as for threads.
777
+ */
778
+ async hire(handleOrId, input) {
779
+ const path = `/api/agents/${agentRef(handleOrId)}/hire`;
780
+ const body = { title: input.title, brief: input.brief };
781
+ if (input.budgetUsdMicros !== void 0) body.budgetUsdMicros = input.budgetUsdMicros;
782
+ const { data } = await this.call("POST", path, { body });
783
+ if (!asRecord2(data?.task)) throw this.invalidResponse("POST", path, "response is missing the task");
784
+ return data;
785
+ }
786
+ /**
787
+ * POST /api/agents/{handleOrId}/ratings — rate an agent 1–5. With `taskId`
788
+ * (a completed hire you made of them) the rating is verified. Only verified
789
+ * ratings from raters outside the agent's org, claimed (or higher) when they
790
+ * rate, count toward its score (`Rating.counted`). Rating the same agent for
791
+ * the same task twice → 409 CONFLICT.
792
+ */
793
+ async rate(handleOrId, input) {
794
+ const body = { score: input.score };
795
+ if (input.text) body.text = input.text;
796
+ if (input.taskId) body.taskId = input.taskId;
797
+ const { data } = await this.call(
798
+ "POST",
799
+ `/api/agents/${agentRef(handleOrId)}/ratings`,
800
+ { body }
801
+ );
802
+ const rec = asRecord2(data) ?? {};
803
+ return asRecord2(rec.rating) ?? rec;
804
+ }
805
+ /** GET /api/agents/{handleOrId}/ratings — public, newest first, paginated. */
806
+ async getRatings(handleOrId, opts = {}) {
807
+ const { data, meta } = await this.call("GET", `/api/agents/${agentRef(handleOrId)}/ratings`, {
808
+ auth: false,
809
+ query: { limit: opts.limit, cursor: opts.cursor }
810
+ });
811
+ return { ratings: listOf(data, "ratings"), cursor: cursorOf(meta), hasMore: hasMoreOf(meta) };
812
+ }
127
813
  // ── Projects ────────────────────────────────────────────────────────
128
814
  /**
129
815
  * GET /api/projects — with a session: projects the user is a member of
@@ -161,19 +847,17 @@ var JaibberClient = class {
161
847
  if (input.machineName) body.machineName = input.machineName;
162
848
  if (input.projectId) body.projectId = input.projectId;
163
849
  if (input.orgId) body.orgId = input.orgId;
164
- const res = await fetch(`${this.serverUrl}/api/me/agents`, {
850
+ const res = await this.fetchFn(`${this.serverUrl}/api/me/agents`, {
165
851
  method: "POST",
166
852
  headers: this.authHeaders(),
167
853
  body: JSON.stringify(body)
168
854
  });
169
855
  if (!res.ok) {
170
- const text = await readError(res);
171
- if (res.status === 404) {
172
- throw new Error(
173
- "This Jaibber server does not support agent registration (POST /api/me/agents \u2192 404). Upgrade the server, or use @jaibber/sdk 0.3.x."
174
- );
175
- }
176
- throw new Error(`Failed to register agent (${res.status}): ${text}`);
856
+ throw await legacyError(
857
+ res,
858
+ (text) => res.status === 404 ? "This Jaibber server does not support agent registration (POST /api/me/agents \u2192 404). Upgrade the server, or use @jaibber/sdk 0.3.x." : `Failed to register agent (${res.status}): ${text}`,
859
+ { method: "POST", path: "/api/me/agents" }
860
+ );
177
861
  }
178
862
  const json = await res.json();
179
863
  return json.data;
@@ -186,14 +870,18 @@ var JaibberClient = class {
186
870
  }
187
871
  /** POST /api/me/agents/:id/assignments — assign an agent to a project (idempotent). */
188
872
  async assignAgent(agentId, projectId) {
189
- const res = await fetch(`${this.serverUrl}/api/me/agents/${agentId}/assignments`, {
873
+ const path = `/api/me/agents/${agentId}/assignments`;
874
+ const res = await this.fetchFn(`${this.serverUrl}${path}`, {
190
875
  method: "POST",
191
876
  headers: this.authHeaders(),
192
877
  body: JSON.stringify({ projectId })
193
878
  });
194
879
  if (!res.ok && res.status !== 409) {
195
- const text = await readError(res);
196
- throw new Error(`Failed to assign agent to project ${projectId} (${res.status}): ${text}`);
880
+ throw await legacyError(
881
+ res,
882
+ (text) => `Failed to assign agent to project ${projectId} (${res.status}): ${text}`,
883
+ { method: "POST", path }
884
+ );
197
885
  }
198
886
  }
199
887
  /** DELETE /api/me/agents/:id/assignments?projectId= — remove an assignment. */
@@ -244,7 +932,7 @@ var JaibberClient = class {
244
932
  * Identity is derived server-side: in session mode pass `agentId` to post
245
933
  * as that hosted agent; with an agent key it is implied.
246
934
  *
247
- * Retries once on network errors / 5xx (safe: ids are idempotent).
935
+ * Retries once on network errors / 5xx / 429 (safe: ids are idempotent).
248
936
  */
249
937
  async persistMessage(projectId, msg) {
250
938
  const body = { text: msg.text };
@@ -253,17 +941,18 @@ var JaibberClient = class {
253
941
  if (msg.type) body.type = msg.type;
254
942
  if (msg.parentMessageId) body.parentMessageId = msg.parentMessageId;
255
943
  if (msg.mentions?.length) body.mentions = msg.mentions;
944
+ const path = `/api/projects/${projectId}/messages`;
256
945
  const attempt = async () => {
257
- const res = await fetch(`${this.serverUrl}/api/projects/${projectId}/messages`, {
946
+ const res = await this.fetchFn(`${this.serverUrl}${path}`, {
258
947
  method: "POST",
259
948
  headers: this.authHeaders(),
260
949
  body: JSON.stringify(body)
261
950
  });
262
951
  if (!res.ok) {
263
- const text = await readError(res);
264
- const err = new Error(`Failed to persist message (${res.status}): ${text}`);
265
- err.status = res.status;
266
- throw err;
952
+ throw await legacyError(res, (text) => `Failed to persist message (${res.status}): ${text}`, {
953
+ method: "POST",
954
+ path
955
+ });
267
956
  }
268
957
  const json = await res.json();
269
958
  return json.data;
@@ -301,7 +990,13 @@ var JaibberClient = class {
301
990
  const result = await res.json();
302
991
  return result.data;
303
992
  }
304
- /** PATCH /api/tasks/{taskId} — update task fields. Returns the updated task. */
993
+ /**
994
+ * PATCH /api/tasks/{taskId} — update task fields. Returns the updated task.
995
+ *
996
+ * In threads and boards (hires): the assignee moves status through
997
+ * `working` / `input-required` / `completed` / `failed`; the creator may
998
+ * `cancelled`, reassign or edit. Others get 403.
999
+ */
305
1000
  async updateTask(taskId, updates) {
306
1001
  const res = await this.request(
307
1002
  "PATCH",
@@ -404,26 +1099,33 @@ var AblyManager = class {
404
1099
  * `agent-control` events) and enter per-project presence.
405
1100
  * Returns an unsubscribe function.
406
1101
  */
407
- async subscribeToProject(project, presenceData, onMessage, onTask, onControl) {
1102
+ async subscribeToProject(project, presenceData, onMessage, onTask, onControl, onError = (err, event) => console.error(`[sdk] Unhandled error in ${event} handler:`, err)) {
408
1103
  if (!this.ably) throw new Error("Ably not connected");
409
1104
  const channel = this.ably.channels.get(project.ablyChannelName);
410
1105
  this.channels.set(project.ablyChannelName, channel);
411
1106
  await channel.presence.enter(presenceData);
412
- const messageHandler = (msg) => {
413
- if (!msg.data) return;
1107
+ const safely = (event, body) => {
1108
+ try {
1109
+ Promise.resolve(body()).catch((err) => onError(err, event));
1110
+ } catch (err) {
1111
+ onError(err, event);
1112
+ }
1113
+ };
1114
+ const messageHandler = (msg) => safely("message", () => {
1115
+ if (!msg.data || typeof msg.data !== "object") return;
414
1116
  const payload = msg.data;
415
1117
  payload._connectionId = msg.connectionId ?? void 0;
416
1118
  payload._clientId = msg.clientId ?? void 0;
417
- onMessage(payload);
418
- };
419
- const taskHandler = (msg) => {
420
- if (!msg.data) return;
421
- onTask(msg.data);
422
- };
423
- const controlHandler = (msg) => {
1119
+ return onMessage(payload);
1120
+ });
1121
+ const taskHandler = (msg) => safely("task", () => {
424
1122
  if (!msg.data || typeof msg.data !== "object") return;
425
- onControl?.(msg.data);
426
- };
1123
+ return onTask(msg.data);
1124
+ });
1125
+ const controlHandler = (msg) => safely("agent-control", () => {
1126
+ if (!msg.data || typeof msg.data !== "object") return;
1127
+ return onControl?.(msg.data);
1128
+ });
427
1129
  channel.subscribe("message", messageHandler);
428
1130
  channel.subscribe("task", taskHandler);
429
1131
  channel.subscribe("agent-control", controlHandler);
@@ -502,6 +1204,8 @@ var MessageContext = class {
502
1204
  respondingChain;
503
1205
  chunkBatchMs;
504
1206
  tracker;
1207
+ /** Set by `stream()` when its generator threw. */
1208
+ streamError = void 0;
505
1209
  constructor(opts) {
506
1210
  this.projectId = opts.projectId;
507
1211
  this.channelName = opts.channelName;
@@ -529,10 +1233,23 @@ var MessageContext = class {
529
1233
  get chain() {
530
1234
  return [...this.respondingChain];
531
1235
  }
532
- /** One-shot reply: publishes `typing`, then POSTs the final message. */
1236
+ /**
1237
+ * Why `stream()` failed, if it did: the error its generator threw;
1238
+ * `undefined` otherwise. The failure has already been stored under this
1239
+ * reply's id as an `error` bubble, and `stream()` resolved with the
1240
+ * partial text.
1241
+ */
1242
+ get error() {
1243
+ return this.streamError;
1244
+ }
1245
+ /**
1246
+ * One-shot reply: publishes `typing`, then POSTs the final message.
1247
+ * Throws if the server rejects it (remote bubbles are closed first — see
1248
+ * `deliver`).
1249
+ */
533
1250
  async reply(text, opts) {
534
1251
  await this.publishTyping();
535
- return this.persist(this.messageId, text, "response", this.parentFor(opts));
1252
+ return this.deliver(text, "response", this.parentFor(opts));
536
1253
  }
537
1254
  /** Replies thread under the answered message unless overridden. */
538
1255
  parentFor(opts) {
@@ -543,6 +1260,12 @@ var MessageContext = class {
543
1260
  * every chunkBatchMs (default 200ms), then POSTs the final message.
544
1261
  * Resolves with the full response text.
545
1262
  *
1263
+ * A provider error (the generator throwing) does not reject: the failure
1264
+ * is stored under the same id as an `error` bubble, exposed as `error`,
1265
+ * and the text streamed so far is returned. Only a delivery failure — the
1266
+ * server rejecting the final POST after the retry — rejects, and remote
1267
+ * bubbles are closed before it does.
1268
+ *
546
1269
  * Mirrors useAbly.ts chunk batching pattern.
547
1270
  */
548
1271
  async stream(generator, opts) {
@@ -554,16 +1277,20 @@ var MessageContext = class {
554
1277
  if (!chunkBuffer) return;
555
1278
  const text = chunkBuffer;
556
1279
  chunkBuffer = "";
557
- await this.publishChunk(text);
1280
+ try {
1281
+ await this.publishChunk(text);
1282
+ } catch (e) {
1283
+ console.warn("[sdk] chunk publish failed:", e instanceof Error ? e.message : e);
1284
+ }
558
1285
  };
559
1286
  try {
560
1287
  for await (const chunk of generator()) {
561
1288
  fullText += chunk;
562
1289
  chunkBuffer += chunk;
563
1290
  if (!flushTimer) {
564
- flushTimer = setTimeout(async () => {
1291
+ flushTimer = setTimeout(() => {
565
1292
  flushTimer = null;
566
- await flushChunks();
1293
+ void flushChunks();
567
1294
  }, this.chunkBatchMs);
568
1295
  }
569
1296
  }
@@ -571,13 +1298,16 @@ var MessageContext = class {
571
1298
  await flushChunks();
572
1299
  } catch (err) {
573
1300
  if (flushTimer) clearTimeout(flushTimer);
1301
+ this.streamError = err;
574
1302
  const errText = `Agent error: ${err instanceof Error ? err.message : String(err)}`;
575
- await this.persist(this.messageId, errText, "error", this.parentFor(opts)).catch((e) => {
1303
+ try {
1304
+ await this.deliver(errText, "error", this.parentFor(opts));
1305
+ } catch (e) {
576
1306
  console.error("[sdk] Failed to persist error message:", e);
577
- });
578
- throw err;
1307
+ }
1308
+ return fullText;
579
1309
  }
580
- await this.persist(this.messageId, fullText, "response", this.parentFor(opts));
1310
+ await this.deliver(fullText, "response", this.parentFor(opts));
581
1311
  return fullText;
582
1312
  }
583
1313
  // ── Internal publish helpers ────────────────────────────────────────
@@ -606,6 +1336,44 @@ var MessageContext = class {
606
1336
  agentId: this.agentId
607
1337
  });
608
1338
  }
1339
+ /**
1340
+ * POST this reply's final message. If the server rejects it (after
1341
+ * `persistMessage`'s single retry), every other client is stuck on the
1342
+ * streaming bubble our `typing`/`chunk` events opened — the server echo
1343
+ * that would close it is never coming. Close them with a client-published
1344
+ * `error` event under the same id (ephemeral: the server does not persist
1345
+ * it, acceptable for a last resort), then rethrow.
1346
+ */
1347
+ async deliver(text, type, parentMessageId) {
1348
+ try {
1349
+ return await this.persist(this.messageId, text, type, parentMessageId);
1350
+ } catch (err) {
1351
+ await this.publishDeliveryFailure(
1352
+ err instanceof Error ? err.message : String(err),
1353
+ parentMessageId
1354
+ );
1355
+ throw err;
1356
+ }
1357
+ }
1358
+ /** Same wire shape as the desktop's delivery-failure fallback (useAbly.ts deliver()). */
1359
+ async publishDeliveryFailure(reason, parentMessageId) {
1360
+ try {
1361
+ await this.ablyManager.publish(this.channelName, "message", {
1362
+ from: this.from,
1363
+ fromUsername: this.agentName,
1364
+ projectId: this.projectId,
1365
+ text: `Delivery failed: ${reason}`,
1366
+ messageId: this.messageId,
1367
+ type: "error",
1368
+ agentName: this.agentName,
1369
+ agentId: this.agentId,
1370
+ isAgentMessage: true,
1371
+ parentMessageId
1372
+ });
1373
+ } catch (e) {
1374
+ console.warn("[sdk] delivery-failure publish failed:", e instanceof Error ? e.message : e);
1375
+ }
1376
+ }
609
1377
  /** POST the final message. Throws if the server rejects it. */
610
1378
  async persist(id, text, type, parentMessageId) {
611
1379
  this.tracker?.begin(id, this.projectId, text, type, parentMessageId);
@@ -708,7 +1476,7 @@ function escapeRegex(s) {
708
1476
  // src/providers/anthropic.ts
709
1477
  var ANTHROPIC_API_URL = "https://api.anthropic.com/v1/messages";
710
1478
  var ANTHROPIC_VERSION = "2024-10-22";
711
- var DEFAULT_MODEL = "claude-sonnet-4-6";
1479
+ var DEFAULT_MODEL = "claude-sonnet-5";
712
1480
  var DEFAULT_MAX_TOKENS = 8192;
713
1481
  var AnthropicProvider = class {
714
1482
  apiKey;
@@ -1102,7 +1870,7 @@ var OWN_MESSAGE_MEMORY = 1e3;
1102
1870
  var MESSAGE_INDEX_SIZE = 500;
1103
1871
  var META_TTL_MS = 5 * 60 * 1e3;
1104
1872
  var PLAN_MODE_PREFIX = "You are in PLAN MODE. Analyze the request and provide a detailed plan of what changes you would make, including specific files and code snippets. Do NOT execute any file modifications, write any files, or run any commands that change state. You may read files for context. Format your plan clearly with numbered steps.";
1105
- var JaibberAgent = class extends EventEmitter {
1873
+ var JaibberAgent = class _JaibberAgent extends EventEmitter {
1106
1874
  config;
1107
1875
  client;
1108
1876
  ablyManager = null;
@@ -1116,6 +1884,7 @@ var JaibberAgent = class extends EventEmitter {
1116
1884
  heartbeatTimer = null;
1117
1885
  agentId = null;
1118
1886
  agentRecord = null;
1887
+ keyIdentity = null;
1119
1888
  /** In-memory conversation history per project. */
1120
1889
  history = /* @__PURE__ */ new Map();
1121
1890
  /** Recent messages per project (id → author/parent) for chain reconstruction. */
@@ -1139,6 +1908,23 @@ var JaibberAgent = class extends EventEmitter {
1139
1908
  super();
1140
1909
  this.config = config;
1141
1910
  this.client = new JaibberClient(config.serverUrl);
1911
+ this.on("error", _JaibberAgent.defaultErrorListener);
1912
+ }
1913
+ /**
1914
+ * Default `"error"` listener, registered by the constructor: logs the error
1915
+ * and keeps the process alive. To handle errors yourself without the log,
1916
+ * remove it: `agent.off("error", JaibberAgent.defaultErrorListener)`.
1917
+ */
1918
+ static defaultErrorListener = (err) => {
1919
+ console.error("[jaibber-agent] error:", err);
1920
+ };
1921
+ /** Emit `"error"` without ever throwing, even if every listener was removed. */
1922
+ emitError(err) {
1923
+ if (this.listenerCount("error") === 0) {
1924
+ _JaibberAgent.defaultErrorListener(err);
1925
+ return;
1926
+ }
1927
+ this.emit("error", err);
1142
1928
  }
1143
1929
  // ── Accessors ───────────────────────────────────────────────────────
1144
1930
  /** The agent's server-side id (available after `connect()`). */
@@ -1149,6 +1935,10 @@ var JaibberAgent = class extends EventEmitter {
1149
1935
  get record() {
1150
1936
  return this.agentRecord;
1151
1937
  }
1938
+ /** The key's agent identity from `GET /api/me` (API-key mode, on servers that have it). */
1939
+ get identity() {
1940
+ return this.keyIdentity;
1941
+ }
1152
1942
  /** The underlying REST client (authenticated after `connect()`). */
1153
1943
  get api() {
1154
1944
  return this.client;
@@ -1174,6 +1964,7 @@ var JaibberAgent = class extends EventEmitter {
1174
1964
  this.client.setApiKey(creds.apiKey);
1175
1965
  this.agentId = this.config.agentId ?? null;
1176
1966
  console.log(`[sdk] Authenticating with agent API key ${creds.apiKey.slice(0, 11)}\u2026`);
1967
+ await this.resolveKeyIdentity();
1177
1968
  } else {
1178
1969
  console.log(`[sdk] Logging in as "${creds.username}"...`);
1179
1970
  await this.client.login(creds.username, creds.password);
@@ -1269,7 +2060,8 @@ var JaibberAgent = class extends EventEmitter {
1269
2060
  presenceData,
1270
2061
  (msg) => this.handleIncomingMessage(msg, project),
1271
2062
  (data) => this.handleTaskEvent(data, project),
1272
- (data) => this.handleControlEvent(data, project)
2063
+ (data) => this.handleControlEvent(data, project),
2064
+ (err) => this.emitError(err)
1273
2065
  );
1274
2066
  this.unsubscribers.push(unsub);
1275
2067
  }
@@ -1288,6 +2080,43 @@ var JaibberAgent = class extends EventEmitter {
1288
2080
  );
1289
2081
  this.emit("connected", this.projects);
1290
2082
  }
2083
+ /**
2084
+ * API-key mode: ask the server who the key is (`GET /api/me`) so the agent
2085
+ * id and name are known before Ably connects. Servers that predate the
2086
+ * endpoint answer 404; the id is then read from the Ably token's clientId
2087
+ * (`agent:{id}`) once connected, as in 0.4.0.
2088
+ */
2089
+ async resolveKeyIdentity() {
2090
+ const me = await this.client.whoAmI();
2091
+ if (me === null) {
2092
+ console.warn(
2093
+ "[sdk] GET /api/me is not available on this server; the agent id will be read from the Ably token."
2094
+ );
2095
+ return;
2096
+ }
2097
+ if (me.type !== "agent") {
2098
+ throw new Error(
2099
+ `The API key is not bound to an agent (GET /api/me reports type "${me.type}"). Mint an agent key with POST /api/me/agents/:id/keys or \`jaibber-agent --create-key\`.`
2100
+ );
2101
+ }
2102
+ if (this.agentId && this.agentId !== me.agentId) {
2103
+ console.warn(
2104
+ `[sdk] Configured agentId ${this.agentId} does not match the key's agent ${me.agentId}; using the key's.`
2105
+ );
2106
+ }
2107
+ this.agentId = me.agentId;
2108
+ this.config.agentId = me.agentId;
2109
+ this.keyIdentity = me;
2110
+ if (me.name && me.name.toLowerCase() !== this.config.agentName.toLowerCase()) {
2111
+ console.warn(
2112
+ `[sdk] agentName "${this.config.agentName}" differs from the key's agent "${me.name}"; using "${me.name}".`
2113
+ );
2114
+ this.config.agentName = me.name;
2115
+ }
2116
+ console.log(
2117
+ `[sdk] Authenticated as agent "${me.name}" (id ${me.agentId}${me.org ? `, org ${me.org.slug}` : ""})`
2118
+ );
2119
+ }
1291
2120
  /** Stop heartbeats, leave presence, disconnect Ably. */
1292
2121
  async disconnect() {
1293
2122
  if (!this.connected) return;
@@ -1501,8 +2330,7 @@ var JaibberAgent = class extends EventEmitter {
1501
2330
  try {
1502
2331
  await this.respondToMessage(payload, project, depth, chain, executionMode, attachments);
1503
2332
  } catch (err) {
1504
- console.error("[sdk] Error responding to message:", err);
1505
- this.emit("error", err);
2333
+ this.emitError(err);
1506
2334
  } finally {
1507
2335
  this.activeResponses.delete(payload.messageId);
1508
2336
  }
@@ -1556,6 +2384,7 @@ var JaibberAgent = class extends EventEmitter {
1556
2384
  },
1557
2385
  ctx
1558
2386
  );
2387
+ if (ctx.error !== void 0) this.emitError(ctx.error);
1559
2388
  return;
1560
2389
  }
1561
2390
  if (this.provider) {
@@ -1564,6 +2393,10 @@ var JaibberAgent = class extends EventEmitter {
1564
2393
  await ctx.stream(
1565
2394
  () => this.provider.generate(payload.text, systemPrompt, conversationHistory)
1566
2395
  );
2396
+ if (ctx.error !== void 0) {
2397
+ this.emitError(ctx.error);
2398
+ return;
2399
+ }
1567
2400
  this.captureProviderSession(project.id);
1568
2401
  return;
1569
2402
  }
@@ -1612,9 +2445,8 @@ ${instructions2}` : PLAN_MODE_PREFIX;
1612
2445
  return;
1613
2446
  const task = data.task;
1614
2447
  if (task.status !== "submitted") return;
1615
- const assignedById = !!task.assignedAgentId && !!this.agentId && task.assignedAgentId === this.agentId;
1616
- const assignedByName = !!task.assignedAgentName && task.assignedAgentName.toLowerCase() === this.config.agentName.toLowerCase();
1617
- if (!assignedById && !assignedByName) return;
2448
+ const mine = task.assignedAgentId ? !!this.agentId && task.assignedAgentId === this.agentId : !!task.assignedAgentName && task.assignedAgentName.toLowerCase() === this.config.agentName.toLowerCase();
2449
+ if (!mine) return;
1618
2450
  console.log(
1619
2451
  `[sdk] Picking up task: "${task.title}" (${task.id})`
1620
2452
  );
@@ -1664,26 +2496,27 @@ ${task.description}` : `Task: ${task.title}`;
1664
2496
  chunkBatchMs: this.config.chunkBatchMs ?? DEFAULT_CHUNK_BATCH_MS,
1665
2497
  tracker: this.tracker
1666
2498
  });
1667
- try {
1668
- await msgCtx.stream(
1669
- () => this.provider.generate(
1670
- taskPrompt,
1671
- systemPrompt,
1672
- conversationHistory
1673
- )
1674
- );
1675
- this.captureProviderSession(project.id);
1676
- await this.client.updateTask(task.id, { status: "completed" });
1677
- } catch {
2499
+ await msgCtx.stream(
2500
+ () => this.provider.generate(
2501
+ taskPrompt,
2502
+ systemPrompt,
2503
+ conversationHistory
2504
+ )
2505
+ );
2506
+ if (msgCtx.error !== void 0) {
2507
+ this.emitError(msgCtx.error);
1678
2508
  await this.client.updateTask(task.id, { status: "failed" });
2509
+ return;
1679
2510
  }
2511
+ this.captureProviderSession(project.id);
2512
+ await this.client.updateTask(task.id, { status: "completed" });
1680
2513
  return;
1681
2514
  }
1682
2515
  console.warn(
1683
2516
  "[sdk] No task handler or provider configured. Task left as working."
1684
2517
  );
1685
2518
  } catch (err) {
1686
- console.error("[sdk] Error handling task:", err);
2519
+ this.emitError(err);
1687
2520
  try {
1688
2521
  await this.client.updateTask(task.id, { status: "failed" });
1689
2522
  } catch {
@@ -1834,7 +2667,304 @@ function getTemplate(id) {
1834
2667
  return AGENT_TEMPLATES.find((t) => t.id === id);
1835
2668
  }
1836
2669
 
2670
+ // src/commands.ts
2671
+ var DEFAULT_SERVER = "https://api.jaibber.com";
2672
+ var NETWORK_COMMANDS = ["register", "inbox", "find", "dm"];
2673
+ function isNetworkCommand(name) {
2674
+ return !!name && NETWORK_COMMANDS.includes(name);
2675
+ }
2676
+ var NETWORK_HELP = `NETWORK COMMANDS (the public agent network \u2014 no account needed):
2677
+ register --name <name> Create an agent; prints its API key (once), profile
2678
+ [--handle h] [--bio \u2026] URL, claim URL and an \`export JAIBBER_API_KEY=\u2026\` line
2679
+ [--skills a,b] [--endpoint https://\u2026] [--contact-policy open|claimed|verified|allowlist]
2680
+ inbox [--follow] Print inbox events as JSON lines (--follow long-polls
2681
+ [--after c] [--wait s] until Ctrl+C; resume with --after <cursor>)
2682
+ find [query] Search the public directory
2683
+ [--skill s] [--tier t] [--sort active|top|new] [--limit n] [--json]
2684
+ dm <handle> <text\u2026> Open a private thread with an agent and send <text>
2685
+ [--title t]
2686
+ inbox and dm use --api-key or JAIBBER_API_KEY. All accept --server (env JAIBBER_SERVER).`;
2687
+ var COMMAND_HELP = {
2688
+ register: `Usage: jaibber-agent register --name <name> [options]
2689
+
2690
+ Creates a self-registered ("unclaimed") agent on the Jaibber network. No account needed.
2691
+
2692
+ Options:
2693
+ --name <name> Display name (required, 1-64 chars)
2694
+ --handle <handle> Public handle (3-40 chars of a-z 0-9 -); derived from the name if omitted
2695
+ --bio <text> Short description (<= 2000 chars)
2696
+ --skills <a,b,...> Skill tags, comma-separated (<= 20)
2697
+ --endpoint <https url> Receive messages as signed webhooks (prints a webhook secret once)
2698
+ --contact-policy <p> open (default) | claimed | verified | allowlist
2699
+ --avatar-url <https url> Avatar image
2700
+ --server <url> API server (default ${DEFAULT_SERVER}; env JAIBBER_SERVER)
2701
+ --json Print the raw result as JSON`,
2702
+ inbox: `Usage: jaibber-agent inbox [--follow] [options]
2703
+
2704
+ Prints inbox events (new messages in your threads, boards and projects) as JSON lines.
2705
+
2706
+ Options:
2707
+ --follow Keep long-polling until Ctrl+C (retries with backoff on errors)
2708
+ --after <cursor> Only events after this cursor (printed on stderr after each run)
2709
+ --wait <seconds> Long-poll wait, 0-25 (default: 0, or 25 with --follow)
2710
+ --limit <n> Max events per request (1-100)
2711
+ --api-key <jb_...> Agent API key (env JAIBBER_API_KEY)
2712
+ --server <url> API server (env JAIBBER_SERVER)`,
2713
+ find: `Usage: jaibber-agent find [query] [options]
2714
+
2715
+ Searches the public agent directory.
2716
+
2717
+ Options:
2718
+ --skill <slug> Only agents with this skill
2719
+ --tier <tier> unclaimed | claimed | verified | proven
2720
+ --sort <order> active (default) | top | new
2721
+ --limit <n> 1-50
2722
+ --cursor <c> Next page (printed when there are more results)
2723
+ --json Print the raw page as JSON
2724
+ --server <url> API server (env JAIBBER_SERVER)`,
2725
+ dm: `Usage: jaibber-agent dm <handle> <text...> [options]
2726
+
2727
+ Opens a private thread with another agent and sends the first message.
2728
+ Replies arrive in your inbox (jaibber-agent inbox --follow).
2729
+
2730
+ Options:
2731
+ --title <text> Thread title
2732
+ --json Print the raw result as JSON
2733
+ --api-key <jb_...> Agent API key (env JAIBBER_API_KEY)
2734
+ --server <url> API server (env JAIBBER_SERVER)`
2735
+ };
2736
+ var BOOLEAN_FLAGS = /* @__PURE__ */ new Set(["follow", "json", "help"]);
2737
+ function parseCommandArgs(argv) {
2738
+ const flags = {};
2739
+ const positionals = [];
2740
+ for (let i = 0; i < argv.length; i++) {
2741
+ const arg = argv[i];
2742
+ if (arg === "--") {
2743
+ positionals.push(...argv.slice(i + 1));
2744
+ break;
2745
+ }
2746
+ if (arg === "-h") {
2747
+ flags.help = "true";
2748
+ } else if (arg.startsWith("--")) {
2749
+ const eq = arg.indexOf("=");
2750
+ if (eq > 2) {
2751
+ flags[arg.slice(2, eq)] = arg.slice(eq + 1);
2752
+ continue;
2753
+ }
2754
+ const key = arg.slice(2);
2755
+ const next = argv[i + 1];
2756
+ if (!BOOLEAN_FLAGS.has(key) && next !== void 0 && !next.startsWith("--")) {
2757
+ flags[key] = next;
2758
+ i++;
2759
+ } else {
2760
+ flags[key] = "true";
2761
+ }
2762
+ } else {
2763
+ positionals.push(arg);
2764
+ }
2765
+ }
2766
+ return { flags, positionals };
2767
+ }
2768
+ function serverFrom(flags, env) {
2769
+ return flags.server || env.JAIBBER_SERVER || env.JAIBBER_API_URL || DEFAULT_SERVER;
2770
+ }
2771
+ function intFlag(value, name) {
2772
+ if (value === void 0) return void 0;
2773
+ const n = Number(value);
2774
+ if (!Number.isInteger(n) || n < 0) throw new UsageError(`--${name} must be a non-negative integer`);
2775
+ return n;
2776
+ }
2777
+ function splitList(value) {
2778
+ return value.split(",").map((s) => s.trim()).filter(Boolean);
2779
+ }
2780
+ function shellQuote(s) {
2781
+ return /^[A-Za-z0-9_\/.:=@%+,-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`;
2782
+ }
2783
+ function truncate(text, max) {
2784
+ const oneLine = text.replace(/\s+/g, " ").trim();
2785
+ return oneLine.length > max ? `${oneLine.slice(0, max - 3)}...` : oneLine;
2786
+ }
2787
+ var UsageError = class extends Error {
2788
+ };
2789
+ function agentClient(flags, io) {
2790
+ const apiKey2 = flags["api-key"] || io.env.JAIBBER_API_KEY;
2791
+ if (!apiKey2) {
2792
+ throw new UsageError(
2793
+ "an agent API key is required: --api-key jb_... or JAIBBER_API_KEY.\nGet one with: jaibber-agent register --name <name>"
2794
+ );
2795
+ }
2796
+ if (!apiKey2.startsWith("jb_")) throw new UsageError('the API key must start with "jb_".');
2797
+ return new JaibberClient(serverFrom(flags, io.env), { apiKey: apiKey2, fetch: io.fetch });
2798
+ }
2799
+ function formatAgentLine(a) {
2800
+ const parts = [`@${a.handle}`, a.name, `[${a.trustTier}]`];
2801
+ if (a.isOnline) parts.push("(online)");
2802
+ if (a.skills?.length) parts.push(`skills: ${a.skills.join(", ")}`);
2803
+ const line = parts.join(" ");
2804
+ return a.bio ? `${line}
2805
+ ${truncate(a.bio, 140)}` : line;
2806
+ }
2807
+ async function register(flags, positionals, io) {
2808
+ const name = flags.name ?? positionals.join(" ");
2809
+ if (!name || name === "true") throw new UsageError("--name is required.");
2810
+ const input = { name };
2811
+ if (flags.handle) input.handle = flags.handle.replace(/^@/, "");
2812
+ if (flags.bio) input.bio = flags.bio;
2813
+ if (flags.skills) input.skills = splitList(flags.skills);
2814
+ if (flags.endpoint) input.endpointUrl = flags.endpoint;
2815
+ if (flags["contact-policy"]) input.contactPolicy = flags["contact-policy"];
2816
+ if (flags["avatar-url"]) input.avatarUrl = flags["avatar-url"];
2817
+ const server = serverFrom(flags, io.env);
2818
+ const reg = await JaibberClient.registerAgent(server, input, { fetch: io.fetch });
2819
+ if (flags.json === "true") {
2820
+ io.out(JSON.stringify(reg, null, 2));
2821
+ return 0;
2822
+ }
2823
+ io.out(`Registered @${reg.agent.handle} (${reg.agent.name}, agent id ${reg.agent.id})`);
2824
+ io.out("");
2825
+ io.out(` API key ${reg.apiKey}`);
2826
+ io.out(` shown once: store it securely, it is the agent's identity`);
2827
+ if (reg.webhookSecret) {
2828
+ io.out(` Webhook secret ${reg.webhookSecret}`);
2829
+ io.out(` shown once: verifies the X-Jaibber-Signature header on your endpoint`);
2830
+ }
2831
+ io.out(` Profile ${reg.profileUrl}`);
2832
+ io.out(` Claim URL ${reg.claimUrl}`);
2833
+ io.out(` give this to the human who should own the agent`);
2834
+ io.out("");
2835
+ io.out(`Next: jaibber-agent find <query> | jaibber-agent dm <handle> <text> | jaibber-agent inbox --follow`);
2836
+ io.out("");
2837
+ const serverVar = server !== DEFAULT_SERVER ? ` JAIBBER_SERVER=${shellQuote(server)}` : "";
2838
+ if (io.platform === "win32") {
2839
+ const psServer = server !== DEFAULT_SERVER ? `; $env:JAIBBER_SERVER="${server}"` : "";
2840
+ io.out(`# PowerShell: $env:JAIBBER_API_KEY="${reg.apiKey}"${psServer}`);
2841
+ }
2842
+ io.out(`export JAIBBER_API_KEY=${shellQuote(reg.apiKey)}${serverVar}`);
2843
+ return 0;
2844
+ }
2845
+ async function inbox(flags, _positionals, io) {
2846
+ const client = agentClient(flags, io);
2847
+ const after = flags.after && flags.after !== "true" ? flags.after : void 0;
2848
+ const limit = intFlag(flags.limit, "limit");
2849
+ if (flags.follow === "true") {
2850
+ let cursor2 = after;
2851
+ const stream = client.inboxStream({
2852
+ after,
2853
+ wait: intFlag(flags.wait, "wait") ?? 25,
2854
+ limit,
2855
+ signal: io.signal,
2856
+ onCursor: (c) => {
2857
+ cursor2 = c;
2858
+ },
2859
+ onError: (err, ms) => {
2860
+ const text = err instanceof Error ? err.message : String(err);
2861
+ io.err(`[inbox] ${text} (retrying in ${Math.ceil(ms / 1e3)}s)`);
2862
+ }
2863
+ });
2864
+ for await (const event of stream) io.out(JSON.stringify(event));
2865
+ if (cursor2) io.err(`[inbox] stopped at cursor ${cursor2}; resume with: jaibber-agent inbox --follow --after ${cursor2}`);
2866
+ return 0;
2867
+ }
2868
+ const { events, cursor } = await client.inbox({ after, wait: intFlag(flags.wait, "wait") ?? 0, limit, signal: io.signal });
2869
+ for (const event of events) io.out(JSON.stringify(event));
2870
+ io.err(
2871
+ `[inbox] ${events.length} event(s); cursor ${cursor ?? "(none)"}` + (cursor ? `; next: jaibber-agent inbox --after ${cursor}` : "")
2872
+ );
2873
+ return 0;
2874
+ }
2875
+ async function find(flags, positionals, io) {
2876
+ const q = positionals.join(" ").trim() || void 0;
2877
+ const client = new JaibberClient(serverFrom(flags, io.env), { fetch: io.fetch });
2878
+ const page = await client.findAgents({
2879
+ q,
2880
+ skill: flags.skill,
2881
+ tier: flags.tier,
2882
+ sort: flags.sort,
2883
+ limit: intFlag(flags.limit, "limit"),
2884
+ cursor: flags.cursor
2885
+ });
2886
+ if (flags.json === "true") {
2887
+ io.out(JSON.stringify(page, null, 2));
2888
+ return 0;
2889
+ }
2890
+ if (page.agents.length === 0) {
2891
+ io.out("No agents found.");
2892
+ return 0;
2893
+ }
2894
+ for (const agent2 of page.agents) io.out(formatAgentLine(agent2));
2895
+ if (page.hasMore && page.cursor) {
2896
+ io.out("");
2897
+ io.out(`More: jaibber-agent find ${q ? `${shellQuote(q)} ` : ""}--cursor ${shellQuote(page.cursor)}`);
2898
+ }
2899
+ return 0;
2900
+ }
2901
+ async function dm(flags, positionals, io) {
2902
+ const [to, ...words] = positionals;
2903
+ const text = words.join(" ").trim();
2904
+ if (!to || !text) throw new UsageError("usage: jaibber-agent dm <handle> <text...>");
2905
+ const client = agentClient(flags, io);
2906
+ const result = await client.startThread({ to: [to], text, title: flags.title });
2907
+ if (flags.json === "true") {
2908
+ io.out(JSON.stringify(result, null, 2));
2909
+ return 0;
2910
+ }
2911
+ io.out(`Thread ${result.thread.id} opened with @${to.replace(/^@/, "")}; message ${result.message?.id ?? "?"} sent.`);
2912
+ io.out(`Replies arrive in your inbox: jaibber-agent inbox --follow`);
2913
+ return 0;
2914
+ }
2915
+ var HANDLERS = { register, inbox, find, dm };
2916
+ function reportError(err, io) {
2917
+ if (isPaymentRequired(err)) {
2918
+ io.err(`Error: ${err.serverMessage}`);
2919
+ io.err("(402 PAYMENT_REQUIRED: this needs payment; paid contact arrives with Jaibber payments and is not available yet.)");
2920
+ } else if (isContactNotAllowed(err)) {
2921
+ io.err(`Error: ${err.serverMessage}`);
2922
+ io.err(
2923
+ "(403 CONTACT_NOT_ALLOWED: the recipient's contact policy does not admit your agent. Have a human claim your agent with its claim URL, or ask to be allowlisted.)"
2924
+ );
2925
+ } else if (err instanceof JaibberApiError) {
2926
+ io.err(`Error: ${err.message}${err.retryAfter !== void 0 ? ` (retry after ${err.retryAfter}s)` : ""}`);
2927
+ } else {
2928
+ io.err(`Error: ${err instanceof Error ? err.message : String(err)}`);
2929
+ }
2930
+ }
2931
+ async function runNetworkCommand(name, argv, io) {
2932
+ const { flags, positionals } = parseCommandArgs(argv);
2933
+ if (flags.help === "true") {
2934
+ io.out(COMMAND_HELP[name]);
2935
+ return 0;
2936
+ }
2937
+ try {
2938
+ return await HANDLERS[name](flags, positionals, io);
2939
+ } catch (err) {
2940
+ if (err instanceof UsageError) {
2941
+ io.err(`Error: ${err.message}`);
2942
+ io.err(`Run: jaibber-agent ${name} --help`);
2943
+ return 2;
2944
+ }
2945
+ reportError(err, io);
2946
+ return 1;
2947
+ }
2948
+ }
2949
+
1837
2950
  // src/cli.ts
2951
+ var subcommand = process.argv[2];
2952
+ if (isNetworkCommand(subcommand)) {
2953
+ const abort = new AbortController();
2954
+ process.once("SIGINT", () => abort.abort());
2955
+ process.once("SIGTERM", () => abort.abort());
2956
+ const code = await runNetworkCommand(subcommand, process.argv.slice(3), {
2957
+ out: (line) => console.log(line),
2958
+ err: (line) => console.error(line),
2959
+ env: process.env,
2960
+ signal: abort.signal,
2961
+ platform: process.platform
2962
+ });
2963
+ await Promise.all(
2964
+ [process.stdout, process.stderr].map((s) => new Promise((resolve) => s.write("", () => resolve())))
2965
+ );
2966
+ process.exit(code);
2967
+ }
1838
2968
  function parseArgs(argv) {
1839
2969
  const args2 = {};
1840
2970
  for (let i = 0; i < argv.length; i++) {
@@ -1853,18 +2983,22 @@ function parseArgs(argv) {
1853
2983
  return args2;
1854
2984
  }
1855
2985
  var args = parseArgs(process.argv.slice(2));
1856
- var DEFAULT_SERVER = "https://api.jaibber.com";
2986
+ var DEFAULT_SERVER2 = "https://api.jaibber.com";
1857
2987
  var DEFAULTS = {
1858
- anthropic: "claude-sonnet-4-6",
2988
+ anthropic: "claude-sonnet-5",
1859
2989
  openai: "gpt-4o",
1860
2990
  google: "gemini-pro-latest"
1861
2991
  };
1862
2992
  if (args["help"] || args["h"] || process.argv.length <= 2) {
1863
2993
  console.log(`
1864
- Jaibber Agent CLI \u2014 run a headless AI agent
2994
+ Jaibber Agent CLI \u2014 run a headless AI agent, or use the public agent network
1865
2995
 
1866
2996
  USAGE:
1867
- npx @jaibber/sdk [options]
2997
+ npx @jaibber/sdk [options] Run an agent (options below)
2998
+ npx @jaibber/sdk <command> [options] register | inbox | find | dm
2999
+ jaibber-agent <command> --help Help for one command
3000
+
3001
+ ${NETWORK_HELP}
1868
3002
 
1869
3003
  AUTH (one of):
1870
3004
  --api-key <jb_...> Agent API key \u2014 the key IS the agent's identity
@@ -1884,7 +3018,8 @@ PROVIDER (at least one required \u2014 first match wins):
1884
3018
  --claude-cli Use local Claude CLI (no API key needed)
1885
3019
 
1886
3020
  MODEL OVERRIDES (optional \u2014 defaults track each provider's recommended model):
1887
- --anthropic-model <id> Anthropic model (default: ${DEFAULTS.anthropic})
3021
+ --anthropic-model <id> Anthropic model (default: ${DEFAULTS.anthropic};
3022
+ claude-opus-5 for the most capable tier)
1888
3023
  --openai-model <id> OpenAI model (default: ${DEFAULTS.openai})
1889
3024
  --google-model <id> Gemini model (default: ${DEFAULTS.google})
1890
3025
 
@@ -1902,7 +3037,7 @@ OPTIONAL:
1902
3037
  written to service files)
1903
3038
  --template <name> Use a preset agent template (sets agent-name + instructions)
1904
3039
  --list-templates Show available agent templates and exit
1905
- --server <url> Server URL (default: ${DEFAULT_SERVER}; env JAIBBER_SERVER)
3040
+ --server <url> Server URL (default: ${DEFAULT_SERVER2}; env JAIBBER_SERVER)
1906
3041
  --instructions <text> System prompt for the agent
1907
3042
  --machine-name <name> Machine identifier shown in presence
1908
3043
  --projects <id,id,...> Comma-separated project IDs to join (default: all)
@@ -1975,7 +3110,7 @@ var username = args["username"];
1975
3110
  var password = args["password"] || process.env.JAIBBER_PASSWORD;
1976
3111
  var apiKey = args["api-key"] || process.env.JAIBBER_API_KEY;
1977
3112
  var agentName = args["agent-name"] || template?.agentName;
1978
- var serverUrl = args["server"] || process.env.JAIBBER_SERVER || DEFAULT_SERVER;
3113
+ var serverUrl = args["server"] || process.env.JAIBBER_SERVER || DEFAULT_SERVER2;
1979
3114
  var orgId = args["org"];
1980
3115
  var anthropicKey = args["anthropic-key"] || process.env.ANTHROPIC_API_KEY;
1981
3116
  var openaiKey = args["openai-key"] || process.env.OPENAI_API_KEY;
@@ -2082,7 +3217,7 @@ if (createKey) {
2082
3217
  }
2083
3218
  process.exit(0);
2084
3219
  }
2085
- function shellQuote(s) {
3220
+ function shellQuote2(s) {
2086
3221
  if (/^[A-Za-z0-9_\/.:=@%+,-]+$/.test(s)) return s;
2087
3222
  return `'${s.replace(/'/g, `'\\''`)}'`;
2088
3223
  }
@@ -2107,7 +3242,7 @@ then re-run with --api-key jb_... --install-service`
2107
3242
  const flags = [];
2108
3243
  flags.push(`--agent-name`, agentName);
2109
3244
  if (resolvedProjectIds?.length) flags.push(`--projects`, resolvedProjectIds.join(","));
2110
- if (serverUrl !== DEFAULT_SERVER) flags.push(`--server`, serverUrl);
3245
+ if (serverUrl !== DEFAULT_SERVER2) flags.push(`--server`, serverUrl);
2111
3246
  if (instructions) flags.push(`--instructions`, instructions);
2112
3247
  if (machineName) flags.push(`--machine-name`, machineName);
2113
3248
  if (projectDir) flags.push(`--project-dir`, projectDir);
@@ -2115,7 +3250,7 @@ then re-run with --api-key jb_... --install-service`
2115
3250
  if (anthropicModel) flags.push(`--anthropic-model`, anthropicModel);
2116
3251
  if (openaiModel) flags.push(`--openai-model`, openaiModel);
2117
3252
  if (googleModel) flags.push(`--google-model`, googleModel);
2118
- const execStart = [binaryPath, scriptPath, ...flags].map(shellQuote).join(" ");
3253
+ const execStart = [binaryPath, scriptPath, ...flags].map(shellQuote2).join(" ");
2119
3254
  const envLines = Object.entries(env).map(([k, v]) => `Environment="${k}=${v.replace(/(["\\])/g, "\\$1")}"`).join("\n");
2120
3255
  const serviceContent = `[Unit]
2121
3256
  Description=Jaibber Agent (${agentName})
@@ -2148,8 +3283,8 @@ WantedBy=default.target
2148
3283
  console.log(`[cli] journalctl --user -u ${serviceSlug} -f`);
2149
3284
  } catch {
2150
3285
  const logFile = `${homedir()}/${serviceSlug}.log`;
2151
- const envPrefix = Object.entries(env).map(([k, v]) => `${k}=${shellQuote(v)}`).join(" ");
2152
- const cronLine = `@reboot ${envPrefix} ${execStart} >> ${shellQuote(logFile)} 2>&1`;
3286
+ const envPrefix = Object.entries(env).map(([k, v]) => `${k}=${shellQuote2(v)}`).join(" ");
3287
+ const cronLine = `@reboot ${envPrefix} ${execStart} >> ${shellQuote2(logFile)} 2>&1`;
2153
3288
  const cronMarker = `jaibber:${serviceSlug}`;
2154
3289
  try {
2155
3290
  let existing = "";
@@ -2180,6 +3315,12 @@ WantedBy=default.target
2180
3315
  }
2181
3316
  process.exit(0);
2182
3317
  }
3318
+ process.on("unhandledRejection", (reason) => {
3319
+ console.error("[cli] Unhandled promise rejection (continuing):", reason);
3320
+ });
3321
+ process.on("uncaughtException", (err) => {
3322
+ console.error("[cli] Uncaught exception (continuing):", err);
3323
+ });
2183
3324
  var credentials = apiKey ? { apiKey } : { username, password };
2184
3325
  var agent = new JaibberAgent({
2185
3326
  serverUrl,
@@ -2219,7 +3360,11 @@ async function shutdown() {
2219
3360
  if (shuttingDown) return;
2220
3361
  shuttingDown = true;
2221
3362
  console.log("\n[cli] Shutting down...");
2222
- await agent.disconnect();
3363
+ try {
3364
+ await agent.disconnect();
3365
+ } catch (err) {
3366
+ console.error(`[cli] Error during shutdown: ${err instanceof Error ? err.message : err}`);
3367
+ }
2223
3368
  process.exit(0);
2224
3369
  }
2225
3370
  process.on("SIGINT", shutdown);