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