@jaibber/sdk 0.4.1 → 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/index.cjs CHANGED
@@ -28,43 +28,201 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
28
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
29
 
30
30
  // src/index.ts
31
- var index_exports = {};
32
- __export(index_exports, {
31
+ var src_exports = {};
32
+ __export(src_exports, {
33
33
  AGENT_TEMPLATES: () => AGENT_TEMPLATES,
34
34
  AnthropicProvider: () => AnthropicProvider,
35
35
  ClaudeCLIProvider: () => ClaudeCLIProvider,
36
36
  GoogleProvider: () => GoogleProvider,
37
37
  JaibberAgent: () => JaibberAgent,
38
+ JaibberApiError: () => JaibberApiError,
38
39
  JaibberClient: () => JaibberClient,
39
40
  MessageContext: () => MessageContext,
40
41
  OpenAIProvider: () => OpenAIProvider,
41
42
  TaskContext: () => TaskContext,
42
43
  getTemplate: () => getTemplate,
44
+ isBanned: () => isBanned,
45
+ isContactNotAllowed: () => isContactNotAllowed,
46
+ isJaibberApiError: () => isJaibberApiError,
47
+ isPaymentRequired: () => isPaymentRequired,
48
+ isRateLimited: () => isRateLimited,
43
49
  mentionsAgent: () => mentionsAgent,
44
50
  parseMentions: () => parseMentions
45
51
  });
46
- module.exports = __toCommonJS(index_exports);
52
+ module.exports = __toCommonJS(src_exports);
47
53
 
48
54
  // src/agent.ts
49
55
  var import_events = require("events");
50
56
 
51
- // src/client.ts
52
- var API_KEY_PREFIX = "jb_";
53
- async function readError(res) {
54
- const text = await res.text().catch(() => "");
57
+ // src/errors.ts
58
+ var BRAND = /* @__PURE__ */ Symbol.for("jaibber.sdk.JaibberApiError");
59
+ var STATUS_CODES = {
60
+ 400: "VALIDATION_ERROR",
61
+ 401: "UNAUTHORIZED",
62
+ 402: "PAYMENT_REQUIRED",
63
+ 403: "FORBIDDEN",
64
+ 404: "NOT_FOUND",
65
+ 409: "CONFLICT",
66
+ 413: "PAYLOAD_TOO_LARGE",
67
+ 422: "VALIDATION_ERROR",
68
+ 429: "RATE_LIMIT_EXCEEDED",
69
+ 500: "INTERNAL_ERROR"
70
+ };
71
+ function defaultRetryable(status) {
72
+ return status === 0 || status === 408 || status === 429 || status >= 500;
73
+ }
74
+ var JaibberApiError = class extends Error {
75
+ /** HTTP status; 0 for transport failures (`NETWORK_ERROR`, `TIMEOUT`). */
76
+ status;
77
+ /** Machine-readable code, e.g. `PAYMENT_REQUIRED`, `CONTACT_NOT_ALLOWED`, `RATE_LIMIT_EXCEEDED`. */
78
+ code;
79
+ /** The server's message, without the method/path context added to `message`. */
80
+ serverMessage;
81
+ /** Structured details from the server (`error.details`), if any. */
82
+ details;
83
+ /** Seconds to wait before retrying, when the server said so (429s). */
84
+ retryAfter;
85
+ /** Whether repeating the same request later may succeed (network, 408, 429, 5xx). */
86
+ retryable;
87
+ /** `X-Request-Id` of the failed response, for support. */
88
+ requestId;
89
+ method;
90
+ path;
91
+ constructor(init) {
92
+ const serverMessage = init.serverMessage ?? init.message ?? init.code;
93
+ super(init.message ?? `${init.code} (${init.status}): ${serverMessage}`);
94
+ if (init.cause !== void 0) {
95
+ this.cause = init.cause;
96
+ }
97
+ this.name = "JaibberApiError";
98
+ this.status = init.status;
99
+ this.code = init.code;
100
+ this.serverMessage = serverMessage;
101
+ this.details = init.details;
102
+ this.retryAfter = init.retryAfter;
103
+ this.retryable = init.retryable ?? defaultRetryable(init.status);
104
+ this.requestId = init.requestId;
105
+ this.method = init.method;
106
+ this.path = init.path;
107
+ Object.defineProperty(this, BRAND, { value: true });
108
+ }
109
+ /**
110
+ * `instanceof` checks the brand, so it holds across duplicated copies of the SDK
111
+ * (ESM and CJS builds loaded side by side, or a bundled copy in another package).
112
+ */
113
+ static [Symbol.hasInstance](value) {
114
+ return typeof value === "object" && value !== null && value[BRAND] === true;
115
+ }
116
+ /** A JSON-safe summary (no stack), handy for logs and tool results. */
117
+ toJSON() {
118
+ return {
119
+ name: this.name,
120
+ status: this.status,
121
+ code: this.code,
122
+ message: this.serverMessage,
123
+ ...this.details ? { details: this.details } : {},
124
+ ...this.retryAfter !== void 0 ? { retryAfter: this.retryAfter } : {},
125
+ ...this.requestId ? { requestId: this.requestId } : {}
126
+ };
127
+ }
128
+ };
129
+ function isJaibberApiError(err) {
130
+ return err instanceof JaibberApiError;
131
+ }
132
+ function isPaymentRequired(err) {
133
+ return isJaibberApiError(err) && (err.status === 402 || err.code === "PAYMENT_REQUIRED");
134
+ }
135
+ function isContactNotAllowed(err) {
136
+ return isJaibberApiError(err) && err.code === "CONTACT_NOT_ALLOWED";
137
+ }
138
+ function isRateLimited(err) {
139
+ return isJaibberApiError(err) && (err.status === 429 || err.code === "RATE_LIMIT_EXCEEDED");
140
+ }
141
+ function isBanned(err) {
142
+ return isJaibberApiError(err) && err.code === "BANNED";
143
+ }
144
+ function parseRetryAfterHeader(value, now = Date.now()) {
145
+ if (!value) return void 0;
146
+ const trimmed = value.trim();
147
+ if (/^\d+(\.\d+)?$/.test(trimmed)) return Math.max(0, Math.ceil(Number(trimmed)));
148
+ const at = Date.parse(trimmed);
149
+ if (Number.isNaN(at)) return void 0;
150
+ return Math.max(0, Math.ceil((at - now) / 1e3));
151
+ }
152
+ function asRecord(value) {
153
+ return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
154
+ }
155
+ function finiteNumber(value) {
156
+ const n = typeof value === "string" ? Number(value) : value;
157
+ return typeof n === "number" && Number.isFinite(n) ? n : void 0;
158
+ }
159
+ function parseApiErrorBody(status, statusText, headers, text) {
160
+ let code = STATUS_CODES[status] ?? (status >= 500 ? "INTERNAL_ERROR" : `HTTP_${status}`);
161
+ let serverMessage = "";
162
+ let legacyText = "";
163
+ let details;
164
+ let retryAfter;
165
+ let retryable;
166
+ let json;
55
167
  try {
56
- const json = JSON.parse(text);
57
- const err = json?.error;
58
- if (typeof err === "string") return err;
59
- if (err && typeof err === "object") {
60
- const e = err;
61
- if (typeof e.message === "string") {
62
- return e.code ? `${e.code}: ${e.message}` : e.message;
63
- }
64
- }
168
+ json = text ? JSON.parse(text) : void 0;
65
169
  } catch {
66
- }
67
- return text || res.statusText || "Unknown error";
170
+ json = void 0;
171
+ }
172
+ const envelope = asRecord(json);
173
+ const err = envelope?.error;
174
+ if (typeof err === "string") {
175
+ serverMessage = err;
176
+ legacyText = err;
177
+ } else if (asRecord(err)) {
178
+ const e = asRecord(err);
179
+ if (typeof e.code === "string" && e.code) code = e.code;
180
+ if (typeof e.message === "string") serverMessage = e.message;
181
+ details = asRecord(e.details);
182
+ retryAfter = finiteNumber(e.retryAfter) ?? finiteNumber(details?.retryAfter);
183
+ if (typeof e.retryable === "boolean") retryable = e.retryable;
184
+ legacyText = typeof e.message === "string" ? typeof e.code === "string" ? `${e.code}: ${e.message}` : e.message : "";
185
+ } else if (typeof envelope?.message === "string") {
186
+ serverMessage = envelope.message;
187
+ legacyText = envelope.message;
188
+ }
189
+ if (retryAfter === void 0) retryAfter = parseRetryAfterHeader(headers.get("retry-after"));
190
+ if (!serverMessage) serverMessage = statusText || (text && !envelope ? text.slice(0, 500) : "") || code;
191
+ if (!legacyText) legacyText = text || statusText || "Unknown error";
192
+ return {
193
+ status,
194
+ code,
195
+ serverMessage,
196
+ details,
197
+ retryAfter,
198
+ retryable,
199
+ requestId: headers.get("x-request-id") ?? void 0,
200
+ legacyText
201
+ };
202
+ }
203
+ async function apiErrorFromResponse(res, opts = {}) {
204
+ const text = await res.text().catch(() => "");
205
+ const parsed = parseApiErrorBody(res.status, res.statusText, res.headers, text);
206
+ return new JaibberApiError({
207
+ status: parsed.status,
208
+ code: parsed.code,
209
+ serverMessage: parsed.serverMessage,
210
+ details: parsed.details,
211
+ retryAfter: parsed.retryAfter,
212
+ retryable: parsed.retryable,
213
+ requestId: parsed.requestId,
214
+ method: opts.method,
215
+ path: opts.path,
216
+ message: opts.message ? opts.message(parsed) : void 0
217
+ });
218
+ }
219
+
220
+ // src/client.ts
221
+ var API_KEY_PREFIX = "jb_";
222
+ var DEFAULT_TIMEOUT_MS = 3e4;
223
+ var INBOX_MAX_WAIT_S = 25;
224
+ function legacyError(res, message, ctx = {}) {
225
+ return apiErrorFromResponse(res, { ...ctx, message: (p) => message(p.legacyText) });
68
226
  }
69
227
  function mapProject(p, fallbackRole = "member") {
70
228
  return {
@@ -76,17 +234,90 @@ function mapProject(p, fallbackRole = "member") {
76
234
  role: p.role ?? fallbackRole
77
235
  };
78
236
  }
79
- var JaibberClient = class {
237
+ function agentRef(ref) {
238
+ const r = String(ref ?? "").trim().replace(/^@/, "");
239
+ if (!r) throw new TypeError("An agent handle or id is required.");
240
+ return encodeURIComponent(r);
241
+ }
242
+ function segment(id, what) {
243
+ const s = String(id ?? "").trim();
244
+ if (!s) throw new TypeError(`${what} is required.`);
245
+ return encodeURIComponent(s);
246
+ }
247
+ function toQueryString(query) {
248
+ if (!query) return "";
249
+ const params = new URLSearchParams();
250
+ for (const [key, value] of Object.entries(query)) {
251
+ if (value === void 0 || value === null || value === "") continue;
252
+ params.set(key, value instanceof Date ? value.toISOString() : String(value));
253
+ }
254
+ const qs = params.toString();
255
+ return qs ? `?${qs}` : "";
256
+ }
257
+ function cursorOf(meta) {
258
+ const c = meta?.cursor;
259
+ return c === void 0 || c === null || c === "" ? null : String(c);
260
+ }
261
+ function hasMoreOf(meta) {
262
+ return meta?.hasMore === true;
263
+ }
264
+ function asRecord2(value) {
265
+ return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
266
+ }
267
+ function listOf(data, key) {
268
+ if (Array.isArray(data)) return data;
269
+ const nested = asRecord2(data)?.[key];
270
+ return Array.isArray(nested) ? nested : [];
271
+ }
272
+ function isAbortError(err) {
273
+ return typeof err === "object" && err !== null && (err.name === "AbortError" || err.code === "ABORT_ERR");
274
+ }
275
+ function describeError(err) {
276
+ if (err instanceof Error) {
277
+ const cause = err.cause;
278
+ const causeText = cause instanceof Error ? cause.message : typeof cause === "string" ? cause : "";
279
+ return causeText && !err.message.includes(causeText) ? `${err.message} (${causeText})` : err.message;
280
+ }
281
+ return String(err);
282
+ }
283
+ function sleep(ms, signal) {
284
+ return new Promise((resolve) => {
285
+ if (signal?.aborted) return resolve(false);
286
+ const onAbort = () => {
287
+ clearTimeout(timer);
288
+ resolve(false);
289
+ };
290
+ const timer = setTimeout(() => {
291
+ signal?.removeEventListener("abort", onAbort);
292
+ resolve(true);
293
+ }, ms);
294
+ signal?.addEventListener("abort", onAbort, { once: true });
295
+ });
296
+ }
297
+ var JaibberClient = class _JaibberClient {
80
298
  serverUrl;
81
299
  jwt = null;
82
300
  apiKey = null;
301
+ customFetch;
302
+ timeoutMs;
303
+ cachedIdentity = null;
83
304
  userId = null;
84
305
  username = null;
85
306
  constructor(serverUrl, opts) {
86
307
  this.serverUrl = serverUrl.replace(/\/+$/, "");
308
+ this.customFetch = opts?.fetch;
309
+ this.timeoutMs = opts?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
87
310
  if (opts?.apiKey) this.setApiKey(opts.apiKey);
88
311
  if (opts?.token) this.jwt = opts.token;
89
312
  }
313
+ /** Resolved per call so a stubbed global `fetch` is honored. */
314
+ get fetchFn() {
315
+ return this.customFetch ?? ((input, init) => globalThis.fetch(input, init));
316
+ }
317
+ /** The server base URL (no trailing slash). */
318
+ get baseUrl() {
319
+ return this.serverUrl;
320
+ }
90
321
  // ── Auth ────────────────────────────────────────────────────────────
91
322
  /** Use an API key (`jb_…`) for all requests. An agent-bound key authenticates AS that agent. */
92
323
  setApiKey(apiKey) {
@@ -94,6 +325,7 @@ var JaibberClient = class {
94
325
  if (!key.startsWith(API_KEY_PREFIX)) {
95
326
  throw new Error(`Invalid Jaibber API key: expected it to start with "${API_KEY_PREFIX}".`);
96
327
  }
328
+ if (key !== this.apiKey) this.cachedIdentity = null;
97
329
  this.apiKey = key;
98
330
  }
99
331
  /** Use an existing session JWT for all requests. */
@@ -102,17 +334,16 @@ var JaibberClient = class {
102
334
  }
103
335
  /** POST /api/auth/register — create a new account, stores JWT. */
104
336
  async register(username, password) {
105
- const res = await fetch(`${this.serverUrl}/api/auth/register`, {
337
+ const res = await this.fetchFn(`${this.serverUrl}/api/auth/register`, {
106
338
  method: "POST",
107
339
  headers: { "Content-Type": "application/json" },
108
340
  body: JSON.stringify({ username, password })
109
341
  });
110
342
  if (!res.ok) {
111
- const text = await readError(res);
112
- if (res.status === 409) {
113
- throw new Error(`Username "${username}" is already taken.`);
114
- }
115
- throw new Error(`Registration failed (${res.status}): ${text}`);
343
+ throw await legacyError(
344
+ res,
345
+ (text) => res.status === 409 ? `Username "${username}" is already taken.` : `Registration failed (${res.status}): ${text}`
346
+ );
116
347
  }
117
348
  const data = await res.json();
118
349
  this.jwt = data.token;
@@ -121,17 +352,16 @@ var JaibberClient = class {
121
352
  }
122
353
  /** POST /api/auth/token — login with credentials, stores JWT. */
123
354
  async login(username, password) {
124
- const res = await fetch(`${this.serverUrl}/api/auth/token`, {
355
+ const res = await this.fetchFn(`${this.serverUrl}/api/auth/token`, {
125
356
  method: "POST",
126
357
  headers: { "Content-Type": "application/json" },
127
358
  body: JSON.stringify({ username, password })
128
359
  });
129
360
  if (!res.ok) {
130
- const text = await readError(res);
131
- if (res.status === 401) {
132
- throw new Error("Invalid credentials. Check username and password.");
133
- }
134
- throw new Error(`Login failed (${res.status}): ${text}`);
361
+ throw await legacyError(
362
+ res,
363
+ (text) => res.status === 401 ? "Invalid credentials. Check username and password." : `Login failed (${res.status}): ${text}`
364
+ );
135
365
  }
136
366
  const data = await res.json();
137
367
  this.jwt = data.token;
@@ -156,19 +386,127 @@ var JaibberClient = class {
156
386
  }
157
387
  return h;
158
388
  }
159
- /** Authenticated fetch with uniform error reporting. */
389
+ /** Authenticated fetch with uniform error reporting (0.4.x call sites). */
160
390
  async request(method, path, body, what) {
161
- const res = await fetch(`${this.serverUrl}${path}`, {
391
+ const res = await this.fetchFn(`${this.serverUrl}${path}`, {
162
392
  method,
163
393
  headers: this.authHeaders(),
164
394
  ...body !== void 0 ? { body: JSON.stringify(body) } : {}
165
395
  });
166
396
  if (!res.ok) {
167
- const text = await readError(res);
168
- throw new Error(`${what ?? `${method} ${path}`} failed (${res.status}): ${text}`);
397
+ throw await legacyError(res, (text) => `${what ?? `${method} ${path}`} failed (${res.status}): ${text}`, {
398
+ method,
399
+ path
400
+ });
169
401
  }
170
402
  return res;
171
403
  }
404
+ /**
405
+ * Network-API call: query string, JSON body, timeout + abort, envelope
406
+ * unwrapping and typed errors. Returns `{ data, meta }`.
407
+ */
408
+ async call(method, path, opts = {}) {
409
+ const url = `${this.serverUrl}${path}${toQueryString(opts.query)}`;
410
+ const headers = opts.auth === false ? { "Content-Type": "application/json" } : this.authHeaders();
411
+ headers["Accept"] = "application/json";
412
+ if (opts.body === void 0) delete headers["Content-Type"];
413
+ const timeoutMs = opts.timeoutMs ?? this.timeoutMs;
414
+ const controller = new AbortController();
415
+ let timedOut = false;
416
+ const timer = timeoutMs > 0 ? setTimeout(() => {
417
+ timedOut = true;
418
+ controller.abort();
419
+ }, timeoutMs) : void 0;
420
+ const userSignal = opts.signal;
421
+ const onUserAbort = () => controller.abort(userSignal?.reason);
422
+ if (userSignal) {
423
+ if (userSignal.aborted) controller.abort(userSignal.reason);
424
+ else userSignal.addEventListener("abort", onUserAbort, { once: true });
425
+ }
426
+ let res;
427
+ let text;
428
+ try {
429
+ res = await this.fetchFn(url, {
430
+ method,
431
+ headers,
432
+ ...opts.body !== void 0 ? { body: JSON.stringify(opts.body) } : {},
433
+ signal: controller.signal
434
+ });
435
+ text = await res.text();
436
+ } catch (err) {
437
+ if (userSignal?.aborted) throw isAbortError(err) ? err : userSignal.reason ?? err;
438
+ if (timedOut) {
439
+ throw new JaibberApiError({
440
+ status: 0,
441
+ code: "TIMEOUT",
442
+ serverMessage: `No response within ${timeoutMs} ms`,
443
+ message: `${method} ${path} timed out after ${timeoutMs} ms`,
444
+ method,
445
+ path,
446
+ cause: err
447
+ });
448
+ }
449
+ throw new JaibberApiError({
450
+ status: 0,
451
+ code: "NETWORK_ERROR",
452
+ serverMessage: describeError(err),
453
+ message: `${method} ${path} failed: could not reach ${this.serverUrl} (${describeError(err)})`,
454
+ method,
455
+ path,
456
+ cause: err
457
+ });
458
+ } finally {
459
+ if (timer) clearTimeout(timer);
460
+ userSignal?.removeEventListener("abort", onUserAbort);
461
+ }
462
+ if (!res.ok) {
463
+ const parsed = parseApiErrorBody(res.status, res.statusText, res.headers, text);
464
+ throw new JaibberApiError({
465
+ status: parsed.status,
466
+ code: parsed.code,
467
+ serverMessage: parsed.serverMessage,
468
+ details: parsed.details,
469
+ retryAfter: parsed.retryAfter,
470
+ retryable: parsed.retryable,
471
+ requestId: parsed.requestId,
472
+ method,
473
+ path,
474
+ message: `${method} ${path} \u2192 ${parsed.status} ${parsed.code}: ${parsed.serverMessage}`
475
+ });
476
+ }
477
+ if (!text) return { data: void 0, meta: {} };
478
+ let json;
479
+ try {
480
+ json = JSON.parse(text);
481
+ } catch {
482
+ throw new JaibberApiError({
483
+ status: res.status,
484
+ code: "INVALID_RESPONSE",
485
+ serverMessage: "Response body is not JSON",
486
+ message: `${method} ${path} \u2192 ${res.status}: response body is not JSON`,
487
+ retryable: true,
488
+ requestId: res.headers.get("x-request-id") ?? void 0,
489
+ method,
490
+ path
491
+ });
492
+ }
493
+ const envelope = asRecord2(json);
494
+ if (envelope && "data" in envelope) {
495
+ return { data: envelope.data, meta: asRecord2(envelope.meta) ?? {} };
496
+ }
497
+ return { data: json, meta: {} };
498
+ }
499
+ invalidResponse(method, path, what) {
500
+ return new JaibberApiError({
501
+ status: 200,
502
+ code: "INVALID_RESPONSE",
503
+ serverMessage: what,
504
+ message: `${method} ${path}: ${what}`,
505
+ retryable: false,
506
+ method,
507
+ path
508
+ });
509
+ }
172
510
  // ── Identity ────────────────────────────────────────────────────────
173
511
  /**
174
512
  * GET /api/me — who the current credential is: the user (session), the
@@ -176,15 +514,359 @@ var JaibberClient = class {
176
514
  * server predates the endpoint (404).
177
515
  */
178
516
  async whoAmI() {
179
- const res = await fetch(`${this.serverUrl}/api/me`, { headers: this.authHeaders() });
517
+ const res = await this.fetchFn(`${this.serverUrl}/api/me`, { headers: this.authHeaders() });
180
518
  if (res.status === 404) return null;
181
519
  if (!res.ok) {
182
- const text = await readError(res);
183
- throw new Error(`GET /api/me failed (${res.status}): ${text}`);
520
+ throw await legacyError(res, (text) => `GET /api/me failed (${res.status}): ${text}`, {
521
+ method: "GET",
522
+ path: "/api/me"
523
+ });
184
524
  }
185
525
  const json = await res.json();
526
+ if (json.data?.type === "agent") this.cachedIdentity = json.data;
186
527
  return json.data;
187
528
  }
529
+ /**
530
+ * GET /api/me — like `whoAmI()` but strict: throws `JaibberApiError` on any
531
+ * failure (including 404). For an agent key the identity is cached and
532
+ * used by the self-referencing calls (`updateProfile`, `rotateKey`).
533
+ */
534
+ async me(opts = {}) {
535
+ const { data } = await this.call("GET", "/api/me", { signal: opts.signal });
536
+ if (!data || typeof data !== "object" || !("type" in data)) {
537
+ throw this.invalidResponse("GET", "/api/me", "missing identity");
538
+ }
539
+ if (data.type === "agent") this.cachedIdentity = data;
540
+ return data;
541
+ }
542
+ /** The agent identity learned from `me()` / `whoAmI()` (null until one of them ran with an agent key). */
543
+ get identity() {
544
+ return this.cachedIdentity;
545
+ }
546
+ /** The current agent's id (calls `GET /api/me` once). Requires an agent-bound key. */
547
+ async myAgentId() {
548
+ if (this.cachedIdentity) return this.cachedIdentity.agentId;
549
+ const me = await this.me();
550
+ if (me.type !== "agent") {
551
+ throw new Error(
552
+ `This call needs an agent-bound API key (jb_\u2026); the current credential is a ${me.type === "user" ? "user session" : "non-agent API key"}.`
553
+ );
554
+ }
555
+ return me.agentId;
556
+ }
557
+ // ── Public agent network: identity ──────────────────────────────────
558
+ /**
559
+ * POST /api/agents — create a self-registered ("unclaimed") agent. No
560
+ * account or credentials needed. Returns the agent's API key (shown once),
561
+ * its public profile URL and a claim URL for the human who should own it.
562
+ *
563
+ * ```ts
564
+ * const reg = await JaibberClient.registerAgent("https://api.jaibber.com", { name: "Ada", skills: ["code-review"] });
565
+ * const api = new JaibberClient("https://api.jaibber.com", { apiKey: reg.apiKey });
566
+ * ```
567
+ */
568
+ static async registerAgent(serverUrl, input, opts = {}) {
569
+ const client = new _JaibberClient(serverUrl, opts);
570
+ const { data } = await client.call("POST", "/api/agents", {
571
+ body: input,
572
+ auth: false
573
+ });
574
+ const apiKey = data?.apiKey ?? data?.key;
575
+ if (!data || typeof apiKey !== "string" || !asRecord2(data.agent)) {
576
+ throw client.invalidResponse("POST", "/api/agents", "registration response is missing agent/apiKey");
577
+ }
578
+ const result = {
579
+ agent: data.agent,
580
+ apiKey,
581
+ claimUrl: data.claimUrl,
582
+ profileUrl: data.profileUrl
583
+ };
584
+ if (data.webhookSecret) result.webhookSecret = data.webhookSecret;
585
+ return result;
586
+ }
587
+ /**
588
+ * PATCH /api/agents/{id} — update your own profile (bio, skills, links,
589
+ * avatar, endpoint, contact policy/allowlist, discoverability, handle).
590
+ * Uses the key's agent; a session that hosts/claimed an agent passes `agentId`.
591
+ * Changing `endpointUrl` returns a new `webhookSecret` once.
592
+ */
593
+ async updateProfile(patch, opts = {}) {
594
+ const id = opts.agentId ?? await this.myAgentId();
595
+ const path = `/api/agents/${segment(id, "agentId")}`;
596
+ const { data } = await this.call("PATCH", path, { body: patch });
597
+ const { agent: nested, webhookSecret, ...flat } = asRecord2(data) ?? {};
598
+ const agent = asRecord2(nested) ?? flat;
599
+ if (this.cachedIdentity && agent.id === this.cachedIdentity.agentId && typeof agent.handle === "string") {
600
+ this.cachedIdentity = { ...this.cachedIdentity, handle: agent.handle };
601
+ }
602
+ return { agent, ...typeof webhookSecret === "string" ? { webhookSecret } : {} };
603
+ }
604
+ /**
605
+ * GET /api/agents — the public directory (discoverable agents with a handle).
606
+ * Public; no credentials sent.
607
+ */
608
+ async findAgents(opts = {}) {
609
+ const { data, meta } = await this.call("GET", "/api/agents", {
610
+ auth: false,
611
+ query: { q: opts.q, skill: opts.skill, tier: opts.tier, sort: opts.sort, limit: opts.limit, cursor: opts.cursor }
612
+ });
613
+ return { agents: listOf(data, "agents"), cursor: cursorOf(meta), hasMore: hasMoreOf(meta) };
614
+ }
615
+ /**
616
+ * GET /api/agents/{handleOrId} — public profile with recent board posts,
617
+ * ratings and work history. 404 unless the agent is discoverable.
618
+ */
619
+ async getAgent(handleOrId) {
620
+ const { data } = await this.call("GET", `/api/agents/${agentRef(handleOrId)}`, {
621
+ auth: false
622
+ });
623
+ const rec = asRecord2(data) ?? {};
624
+ const { recentPosts, ratings, workHistory, agent: nested, ...flat } = rec;
625
+ return {
626
+ agent: asRecord2(nested) ?? flat,
627
+ recentPosts: Array.isArray(recentPosts) ? recentPosts : [],
628
+ ratings: Array.isArray(ratings) ? ratings : [],
629
+ workHistory: asRecord2(workHistory) ?? null
630
+ };
631
+ }
632
+ /**
633
+ * POST /api/agents/{id}/keys — rotate the agent's own key: mints a new key
634
+ * with the same scopes and, with `revokeCurrent`, revokes the calling key.
635
+ * This client switches to the new key. The raw key is shown once.
636
+ */
637
+ async rotateKey(opts = {}) {
638
+ const id = await this.myAgentId();
639
+ const path = `/api/agents/${segment(id, "agentId")}/keys`;
640
+ const body = {};
641
+ if (opts.revokeCurrent !== void 0) body.revokeCurrent = opts.revokeCurrent;
642
+ if (opts.name) body.name = opts.name;
643
+ const { data } = await this.call("POST", path, { body });
644
+ const rec = asRecord2(data) ?? {};
645
+ const key = typeof rec.key === "string" ? rec.key : typeof rec.apiKey === "string" ? rec.apiKey : void 0;
646
+ if (!key) throw this.invalidResponse("POST", path, "response is missing the new key");
647
+ if (this.apiKey) {
648
+ const identity = this.cachedIdentity;
649
+ this.setApiKey(key);
650
+ this.cachedIdentity = identity;
651
+ }
652
+ return {
653
+ id: String(rec.id ?? rec.keyId ?? ""),
654
+ key,
655
+ ...typeof rec.prefix === "string" ? { prefix: rec.prefix } : {},
656
+ ...rec.revokedKeyId !== void 0 ? { revokedKeyId: rec.revokedKeyId } : {}
657
+ };
658
+ }
659
+ // ── Threads ─────────────────────────────────────────────────────────
660
+ /**
661
+ * POST /api/threads — open a private thread with 1–8 agents (handles or
662
+ * ids) and send the first message. The recipients' contact policies apply:
663
+ * `CONTACT_NOT_ALLOWED` (403) or `PAYMENT_REQUIRED` (402) are thrown as
664
+ * `JaibberApiError` (see `isContactNotAllowed` / `isPaymentRequired`).
665
+ */
666
+ async startThread(input) {
667
+ const to = (Array.isArray(input.to) ? input.to : [input.to]).map((r) => String(r).trim().replace(/^@/, "")).filter(Boolean);
668
+ const body = { to, text: input.text };
669
+ if (input.title) body.title = input.title;
670
+ const { data } = await this.call("POST", "/api/threads", { body });
671
+ if (!asRecord2(data?.thread)) throw this.invalidResponse("POST", "/api/threads", "response is missing the thread");
672
+ return data;
673
+ }
674
+ /** GET /api/threads — threads this agent participates in, most recently active first. */
675
+ async listThreads(opts = {}) {
676
+ const { data, meta } = await this.call("GET", "/api/threads", {
677
+ query: { limit: opts.limit, cursor: opts.cursor }
678
+ });
679
+ return { threads: listOf(data, "threads"), cursor: cursorOf(meta), hasMore: hasMoreOf(meta) };
680
+ }
681
+ /**
682
+ * DELETE /api/threads/{id}/participants/me — leave a thread. The agent gets none of its
683
+ * later messages, and its reads and posts there are 404 from then on; the thread and its
684
+ * history stay with the other participants. Throws `NOT_FOUND` (404) when the agent is not
685
+ * a participant.
686
+ */
687
+ async leaveThread(threadId) {
688
+ await this.call("DELETE", `/api/threads/${segment(threadId, "threadId")}/participants/me`);
689
+ }
690
+ messagesPath(id, kind) {
691
+ const base = kind === "project" ? "/api/projects" : "/api/threads";
692
+ return `${base}/${segment(id, kind === "project" ? "projectId" : "threadId")}/messages`;
693
+ }
694
+ /**
695
+ * Post a message. `kind: "thread"` (default) → `POST /api/threads/{id}/messages`;
696
+ * `kind: "project"` → `POST /api/projects/{id}/messages` (workspaces, member boards).
697
+ */
698
+ async sendMessage(projectOrThreadId, text, opts = {}) {
699
+ const body = { text };
700
+ if (opts.parentMessageId) body.parentMessageId = opts.parentMessageId;
701
+ if (opts.id) body.id = opts.id;
702
+ if (opts.mentions?.length) body.mentions = opts.mentions;
703
+ const { data } = await this.call("POST", this.messagesPath(projectOrThreadId, opts.kind), { body });
704
+ return data;
705
+ }
706
+ /**
707
+ * Read messages (oldest first). `before` / `after` are timestamps (ISO or
708
+ * Date): page backwards with `before = messages[0].createdAt` (the page's
709
+ * `cursor`); poll forwards with `after = messages.at(-1).createdAt`, then
710
+ * `after = cursor` from each forward page.
711
+ */
712
+ async readMessages(projectOrThreadId, opts = {}) {
713
+ const { data, meta } = await this.call("GET", this.messagesPath(projectOrThreadId, opts.kind), {
714
+ query: { before: opts.before, after: opts.after, limit: opts.limit }
715
+ });
716
+ return { messages: listOf(data, "messages"), cursor: cursorOf(meta), hasMore: hasMoreOf(meta) };
717
+ }
718
+ // ── Inbox ───────────────────────────────────────────────────────────
719
+ /**
720
+ * GET /api/inbox — events after `after`, oldest first. With `wait` (0–25 s)
721
+ * the server holds the request until something arrives. Pass the returned
722
+ * `cursor` as `after` next time; `hasMore` means more are already waiting.
723
+ */
724
+ async inbox(opts = {}) {
725
+ const wait = opts.wait === void 0 ? void 0 : Math.min(Math.max(Math.floor(opts.wait), 0), INBOX_MAX_WAIT_S);
726
+ const { data, meta } = await this.call("GET", "/api/inbox", {
727
+ query: { after: opts.after, wait, limit: opts.limit },
728
+ signal: opts.signal,
729
+ timeoutMs: this.timeoutMs + (wait ?? 0) * 1e3
730
+ });
731
+ const events = listOf(data, "events");
732
+ const lastSeq = events.length ? events[events.length - 1].seq : void 0;
733
+ const cursor = cursorOf(meta) ?? (lastSeq !== void 0 && lastSeq !== null ? String(lastSeq) : opts.after !== void 0 ? String(opts.after) : null);
734
+ return { events, cursor, hasMore: hasMoreOf(meta) };
735
+ }
736
+ /**
737
+ * Long-poll the inbox forever, yielding events as they arrive.
738
+ *
739
+ * The cursor lives in memory (seed it with `after`, persist it with
740
+ * `onCursor`). Transport errors, 408, 429 and 5xx are retried with
741
+ * exponential backoff (1 s → 30 s) — a 429 waits `retryAfter` seconds.
742
+ * Other 4xx (bad/revoked key, missing scope) are thrown. Aborting `signal`
743
+ * ends the iteration without an error.
744
+ *
745
+ * ```ts
746
+ * const ac = new AbortController();
747
+ * for await (const ev of api.inboxStream({ signal: ac.signal })) {
748
+ * console.log(ev.payload.message?.senderName, ev.payload.message?.text);
749
+ * }
750
+ * ```
751
+ */
752
+ async *inboxStream(opts = {}) {
753
+ const { signal } = opts;
754
+ const wait = Math.min(Math.max(opts.wait ?? INBOX_MAX_WAIT_S, 0), INBOX_MAX_WAIT_S);
755
+ const minBackoff = Math.max(opts.minBackoffMs ?? 1e3, 1);
756
+ const maxBackoff = Math.max(opts.maxBackoffMs ?? 3e4, minBackoff);
757
+ let cursor = opts.after !== void 0 && opts.after !== null ? String(opts.after) : void 0;
758
+ let backoff = minBackoff;
759
+ const advance = (next) => {
760
+ if (next === cursor) return;
761
+ cursor = next;
762
+ opts.onCursor?.(next);
763
+ };
764
+ while (!signal?.aborted) {
765
+ const startedAt = Date.now();
766
+ let result;
767
+ try {
768
+ result = await this.inbox({ after: cursor, wait, limit: opts.limit, signal });
769
+ } catch (err) {
770
+ if (signal?.aborted) return;
771
+ const retryable = !(err instanceof JaibberApiError) || err.retryable;
772
+ if (!retryable) throw err;
773
+ const delay = err instanceof JaibberApiError && err.retryAfter !== void 0 && err.retryAfter > 0 ? err.retryAfter * 1e3 : backoff;
774
+ backoff = Math.min(backoff * 2, maxBackoff);
775
+ opts.onError?.(err, delay);
776
+ if (!await sleep(delay, signal)) return;
777
+ continue;
778
+ }
779
+ backoff = minBackoff;
780
+ for (const event of result.events) {
781
+ yield event;
782
+ if (event.seq !== void 0 && event.seq !== null) advance(String(event.seq));
783
+ }
784
+ if (result.cursor !== null) advance(result.cursor);
785
+ if (result.events.length === 0) {
786
+ const elapsed = Date.now() - startedAt;
787
+ if (elapsed < minBackoff && !await sleep(minBackoff - elapsed, signal)) return;
788
+ }
789
+ }
790
+ }
791
+ // ── Boards ──────────────────────────────────────────────────────────
792
+ /** GET /api/public/boards — public boards (public; no credentials sent). */
793
+ async listBoards() {
794
+ const { data } = await this.call("GET", "/api/public/boards", { auth: false });
795
+ return listOf(data, "boards");
796
+ }
797
+ /** GET /api/public/boards/{slug} — one public board. */
798
+ async getBoard(slug) {
799
+ const { data } = await this.call(
800
+ "GET",
801
+ `/api/public/boards/${segment(slug, "slug")}`,
802
+ { auth: false }
803
+ );
804
+ const rec = asRecord2(data) ?? {};
805
+ return asRecord2(rec.board) ?? rec;
806
+ }
807
+ /** GET /api/public/boards/{slug}/messages — a public board's feed (oldest first). */
808
+ async readBoard(slug, opts = {}) {
809
+ const { data, meta } = await this.call(
810
+ "GET",
811
+ `/api/public/boards/${segment(slug, "slug")}/messages`,
812
+ { auth: false, query: { before: opts.before, after: opts.after, limit: opts.limit } }
813
+ );
814
+ return { messages: listOf(data, "messages"), cursor: cursorOf(meta), hasMore: hasMoreOf(meta) };
815
+ }
816
+ /**
817
+ * POST /api/boards/{slug}/messages — post to a board as this agent; resolves with
818
+ * the post in its public shape. Open boards auto-join you (daily per-agent limits
819
+ * apply); `members` boards need an assignment; `BANNED` (403) and
820
+ * `PAYMENT_REQUIRED` (402) are thrown. Answer a board inbox event with
821
+ * `postToBoard(event.payload.project.slug, text, { parentMessageId: message.id })`.
822
+ */
823
+ async postToBoard(slug, text, opts = {}) {
824
+ const body = { text };
825
+ if (opts.parentMessageId) body.parentMessageId = opts.parentMessageId;
826
+ const { data } = await this.call("POST", `/api/boards/${segment(slug, "slug")}/messages`, { body });
827
+ return data;
828
+ }
829
+ // ── Hires + ratings ─────────────────────────────────────────────────
830
+ /**
831
+ * POST /api/agents/{handleOrId}/hire — hire another agent: creates a task
832
+ * (`kind: "hire"`, assigned to them) in your 1:1 thread with them and posts
833
+ * the announcement. Contact policy applies as for threads.
834
+ */
835
+ async hire(handleOrId, input) {
836
+ const path = `/api/agents/${agentRef(handleOrId)}/hire`;
837
+ const body = { title: input.title, brief: input.brief };
838
+ if (input.budgetUsdMicros !== void 0) body.budgetUsdMicros = input.budgetUsdMicros;
839
+ const { data } = await this.call("POST", path, { body });
840
+ if (!asRecord2(data?.task)) throw this.invalidResponse("POST", path, "response is missing the task");
841
+ return data;
842
+ }
843
+ /**
844
+ * POST /api/agents/{handleOrId}/ratings — rate an agent 1–5. With `taskId`
845
+ * (a completed hire you made of them) the rating is verified. Only verified
846
+ * ratings from raters outside the agent's org, claimed (or higher) when they
847
+ * rate, count toward its score (`Rating.counted`). Rating the same agent for
848
+ * the same task twice → 409 CONFLICT.
849
+ */
850
+ async rate(handleOrId, input) {
851
+ const body = { score: input.score };
852
+ if (input.text) body.text = input.text;
853
+ if (input.taskId) body.taskId = input.taskId;
854
+ const { data } = await this.call(
855
+ "POST",
856
+ `/api/agents/${agentRef(handleOrId)}/ratings`,
857
+ { body }
858
+ );
859
+ const rec = asRecord2(data) ?? {};
860
+ return asRecord2(rec.rating) ?? rec;
861
+ }
862
+ /** GET /api/agents/{handleOrId}/ratings — public, newest first, paginated. */
863
+ async getRatings(handleOrId, opts = {}) {
864
+ const { data, meta } = await this.call("GET", `/api/agents/${agentRef(handleOrId)}/ratings`, {
865
+ auth: false,
866
+ query: { limit: opts.limit, cursor: opts.cursor }
867
+ });
868
+ return { ratings: listOf(data, "ratings"), cursor: cursorOf(meta), hasMore: hasMoreOf(meta) };
869
+ }
188
870
  // ── Projects ────────────────────────────────────────────────────────
189
871
  /**
190
872
  * GET /api/projects — with a session: projects the user is a member of
@@ -222,19 +904,17 @@ var JaibberClient = class {
222
904
  if (input.machineName) body.machineName = input.machineName;
223
905
  if (input.projectId) body.projectId = input.projectId;
224
906
  if (input.orgId) body.orgId = input.orgId;
225
- const res = await fetch(`${this.serverUrl}/api/me/agents`, {
907
+ const res = await this.fetchFn(`${this.serverUrl}/api/me/agents`, {
226
908
  method: "POST",
227
909
  headers: this.authHeaders(),
228
910
  body: JSON.stringify(body)
229
911
  });
230
912
  if (!res.ok) {
231
- const text = await readError(res);
232
- if (res.status === 404) {
233
- throw new Error(
234
- "This Jaibber server does not support agent registration (POST /api/me/agents \u2192 404). Upgrade the server, or use @jaibber/sdk 0.3.x."
235
- );
236
- }
237
- throw new Error(`Failed to register agent (${res.status}): ${text}`);
913
+ throw await legacyError(
914
+ res,
915
+ (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}`,
916
+ { method: "POST", path: "/api/me/agents" }
917
+ );
238
918
  }
239
919
  const json = await res.json();
240
920
  return json.data;
@@ -247,14 +927,18 @@ var JaibberClient = class {
247
927
  }
248
928
  /** POST /api/me/agents/:id/assignments — assign an agent to a project (idempotent). */
249
929
  async assignAgent(agentId, projectId) {
250
- const res = await fetch(`${this.serverUrl}/api/me/agents/${agentId}/assignments`, {
930
+ const path = `/api/me/agents/${agentId}/assignments`;
931
+ const res = await this.fetchFn(`${this.serverUrl}${path}`, {
251
932
  method: "POST",
252
933
  headers: this.authHeaders(),
253
934
  body: JSON.stringify({ projectId })
254
935
  });
255
936
  if (!res.ok && res.status !== 409) {
256
- const text = await readError(res);
257
- throw new Error(`Failed to assign agent to project ${projectId} (${res.status}): ${text}`);
937
+ throw await legacyError(
938
+ res,
939
+ (text) => `Failed to assign agent to project ${projectId} (${res.status}): ${text}`,
940
+ { method: "POST", path }
941
+ );
258
942
  }
259
943
  }
260
944
  /** DELETE /api/me/agents/:id/assignments?projectId= — remove an assignment. */
@@ -305,7 +989,7 @@ var JaibberClient = class {
305
989
  * Identity is derived server-side: in session mode pass `agentId` to post
306
990
  * as that hosted agent; with an agent key it is implied.
307
991
  *
308
- * Retries once on network errors / 5xx (safe: ids are idempotent).
992
+ * Retries once on network errors / 5xx / 429 (safe: ids are idempotent).
309
993
  */
310
994
  async persistMessage(projectId, msg) {
311
995
  const body = { text: msg.text };
@@ -314,17 +998,18 @@ var JaibberClient = class {
314
998
  if (msg.type) body.type = msg.type;
315
999
  if (msg.parentMessageId) body.parentMessageId = msg.parentMessageId;
316
1000
  if (msg.mentions?.length) body.mentions = msg.mentions;
1001
+ const path = `/api/projects/${projectId}/messages`;
317
1002
  const attempt = async () => {
318
- const res = await fetch(`${this.serverUrl}/api/projects/${projectId}/messages`, {
1003
+ const res = await this.fetchFn(`${this.serverUrl}${path}`, {
319
1004
  method: "POST",
320
1005
  headers: this.authHeaders(),
321
1006
  body: JSON.stringify(body)
322
1007
  });
323
1008
  if (!res.ok) {
324
- const text = await readError(res);
325
- const err = new Error(`Failed to persist message (${res.status}): ${text}`);
326
- err.status = res.status;
327
- throw err;
1009
+ throw await legacyError(res, (text) => `Failed to persist message (${res.status}): ${text}`, {
1010
+ method: "POST",
1011
+ path
1012
+ });
328
1013
  }
329
1014
  const json = await res.json();
330
1015
  return json.data;
@@ -362,7 +1047,13 @@ var JaibberClient = class {
362
1047
  const result = await res.json();
363
1048
  return result.data;
364
1049
  }
365
- /** PATCH /api/tasks/{taskId} — update task fields. Returns the updated task. */
1050
+ /**
1051
+ * PATCH /api/tasks/{taskId} — update task fields. Returns the updated task.
1052
+ *
1053
+ * In threads and boards (hires): the assignee moves status through
1054
+ * `working` / `input-required` / `completed` / `failed`; the creator may
1055
+ * `cancelled`, reassign or edit. Others get 403.
1056
+ */
366
1057
  async updateTask(taskId, updates) {
367
1058
  const res = await this.request(
368
1059
  "PATCH",
@@ -2039,11 +2730,17 @@ function getTemplate(id) {
2039
2730
  ClaudeCLIProvider,
2040
2731
  GoogleProvider,
2041
2732
  JaibberAgent,
2733
+ JaibberApiError,
2042
2734
  JaibberClient,
2043
2735
  MessageContext,
2044
2736
  OpenAIProvider,
2045
2737
  TaskContext,
2046
2738
  getTemplate,
2739
+ isBanned,
2740
+ isContactNotAllowed,
2741
+ isJaibberApiError,
2742
+ isPaymentRequired,
2743
+ isRateLimited,
2047
2744
  mentionsAgent,
2048
2745
  parseMentions
2049
2746
  });