@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/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,487 @@ 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
+ }
510
+ // ── Identity ────────────────────────────────────────────────────────
511
+ /**
512
+ * GET /api/me — who the current credential is: the user (session), the
513
+ * agent (agent-bound key) or the org (org key). Resolves `null` when the
514
+ * server predates the endpoint (404).
515
+ */
516
+ async whoAmI() {
517
+ const res = await this.fetchFn(`${this.serverUrl}/api/me`, { headers: this.authHeaders() });
518
+ if (res.status === 404) return null;
519
+ if (!res.ok) {
520
+ throw await legacyError(res, (text) => `GET /api/me failed (${res.status}): ${text}`, {
521
+ method: "GET",
522
+ path: "/api/me"
523
+ });
524
+ }
525
+ const json = await res.json();
526
+ if (json.data?.type === "agent") this.cachedIdentity = json.data;
527
+ return json.data;
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
+ }
172
870
  // ── Projects ────────────────────────────────────────────────────────
173
871
  /**
174
872
  * GET /api/projects — with a session: projects the user is a member of
@@ -206,19 +904,17 @@ var JaibberClient = class {
206
904
  if (input.machineName) body.machineName = input.machineName;
207
905
  if (input.projectId) body.projectId = input.projectId;
208
906
  if (input.orgId) body.orgId = input.orgId;
209
- const res = await fetch(`${this.serverUrl}/api/me/agents`, {
907
+ const res = await this.fetchFn(`${this.serverUrl}/api/me/agents`, {
210
908
  method: "POST",
211
909
  headers: this.authHeaders(),
212
910
  body: JSON.stringify(body)
213
911
  });
214
912
  if (!res.ok) {
215
- const text = await readError(res);
216
- if (res.status === 404) {
217
- throw new Error(
218
- "This Jaibber server does not support agent registration (POST /api/me/agents \u2192 404). Upgrade the server, or use @jaibber/sdk 0.3.x."
219
- );
220
- }
221
- 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
+ );
222
918
  }
223
919
  const json = await res.json();
224
920
  return json.data;
@@ -231,14 +927,18 @@ var JaibberClient = class {
231
927
  }
232
928
  /** POST /api/me/agents/:id/assignments — assign an agent to a project (idempotent). */
233
929
  async assignAgent(agentId, projectId) {
234
- 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}`, {
235
932
  method: "POST",
236
933
  headers: this.authHeaders(),
237
934
  body: JSON.stringify({ projectId })
238
935
  });
239
936
  if (!res.ok && res.status !== 409) {
240
- const text = await readError(res);
241
- 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
+ );
242
942
  }
243
943
  }
244
944
  /** DELETE /api/me/agents/:id/assignments?projectId= — remove an assignment. */
@@ -289,7 +989,7 @@ var JaibberClient = class {
289
989
  * Identity is derived server-side: in session mode pass `agentId` to post
290
990
  * as that hosted agent; with an agent key it is implied.
291
991
  *
292
- * Retries once on network errors / 5xx (safe: ids are idempotent).
992
+ * Retries once on network errors / 5xx / 429 (safe: ids are idempotent).
293
993
  */
294
994
  async persistMessage(projectId, msg) {
295
995
  const body = { text: msg.text };
@@ -298,17 +998,18 @@ var JaibberClient = class {
298
998
  if (msg.type) body.type = msg.type;
299
999
  if (msg.parentMessageId) body.parentMessageId = msg.parentMessageId;
300
1000
  if (msg.mentions?.length) body.mentions = msg.mentions;
1001
+ const path = `/api/projects/${projectId}/messages`;
301
1002
  const attempt = async () => {
302
- const res = await fetch(`${this.serverUrl}/api/projects/${projectId}/messages`, {
1003
+ const res = await this.fetchFn(`${this.serverUrl}${path}`, {
303
1004
  method: "POST",
304
1005
  headers: this.authHeaders(),
305
1006
  body: JSON.stringify(body)
306
1007
  });
307
1008
  if (!res.ok) {
308
- const text = await readError(res);
309
- const err = new Error(`Failed to persist message (${res.status}): ${text}`);
310
- err.status = res.status;
311
- throw err;
1009
+ throw await legacyError(res, (text) => `Failed to persist message (${res.status}): ${text}`, {
1010
+ method: "POST",
1011
+ path
1012
+ });
312
1013
  }
313
1014
  const json = await res.json();
314
1015
  return json.data;
@@ -346,7 +1047,13 @@ var JaibberClient = class {
346
1047
  const result = await res.json();
347
1048
  return result.data;
348
1049
  }
349
- /** 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
+ */
350
1057
  async updateTask(taskId, updates) {
351
1058
  const res = await this.request(
352
1059
  "PATCH",
@@ -449,26 +1156,33 @@ var AblyManager = class {
449
1156
  * `agent-control` events) and enter per-project presence.
450
1157
  * Returns an unsubscribe function.
451
1158
  */
452
- async subscribeToProject(project, presenceData, onMessage, onTask, onControl) {
1159
+ async subscribeToProject(project, presenceData, onMessage, onTask, onControl, onError = (err, event) => console.error(`[sdk] Unhandled error in ${event} handler:`, err)) {
453
1160
  if (!this.ably) throw new Error("Ably not connected");
454
1161
  const channel = this.ably.channels.get(project.ablyChannelName);
455
1162
  this.channels.set(project.ablyChannelName, channel);
456
1163
  await channel.presence.enter(presenceData);
457
- const messageHandler = (msg) => {
458
- if (!msg.data) return;
1164
+ const safely = (event, body) => {
1165
+ try {
1166
+ Promise.resolve(body()).catch((err) => onError(err, event));
1167
+ } catch (err) {
1168
+ onError(err, event);
1169
+ }
1170
+ };
1171
+ const messageHandler = (msg) => safely("message", () => {
1172
+ if (!msg.data || typeof msg.data !== "object") return;
459
1173
  const payload = msg.data;
460
1174
  payload._connectionId = msg.connectionId ?? void 0;
461
1175
  payload._clientId = msg.clientId ?? void 0;
462
- onMessage(payload);
463
- };
464
- const taskHandler = (msg) => {
465
- if (!msg.data) return;
466
- onTask(msg.data);
467
- };
468
- const controlHandler = (msg) => {
1176
+ return onMessage(payload);
1177
+ });
1178
+ const taskHandler = (msg) => safely("task", () => {
469
1179
  if (!msg.data || typeof msg.data !== "object") return;
470
- onControl?.(msg.data);
471
- };
1180
+ return onTask(msg.data);
1181
+ });
1182
+ const controlHandler = (msg) => safely("agent-control", () => {
1183
+ if (!msg.data || typeof msg.data !== "object") return;
1184
+ return onControl?.(msg.data);
1185
+ });
472
1186
  channel.subscribe("message", messageHandler);
473
1187
  channel.subscribe("task", taskHandler);
474
1188
  channel.subscribe("agent-control", controlHandler);
@@ -547,6 +1261,8 @@ var MessageContext = class {
547
1261
  respondingChain;
548
1262
  chunkBatchMs;
549
1263
  tracker;
1264
+ /** Set by `stream()` when its generator threw. */
1265
+ streamError = void 0;
550
1266
  constructor(opts) {
551
1267
  this.projectId = opts.projectId;
552
1268
  this.channelName = opts.channelName;
@@ -574,10 +1290,23 @@ var MessageContext = class {
574
1290
  get chain() {
575
1291
  return [...this.respondingChain];
576
1292
  }
577
- /** One-shot reply: publishes `typing`, then POSTs the final message. */
1293
+ /**
1294
+ * Why `stream()` failed, if it did: the error its generator threw;
1295
+ * `undefined` otherwise. The failure has already been stored under this
1296
+ * reply's id as an `error` bubble, and `stream()` resolved with the
1297
+ * partial text.
1298
+ */
1299
+ get error() {
1300
+ return this.streamError;
1301
+ }
1302
+ /**
1303
+ * One-shot reply: publishes `typing`, then POSTs the final message.
1304
+ * Throws if the server rejects it (remote bubbles are closed first — see
1305
+ * `deliver`).
1306
+ */
578
1307
  async reply(text, opts) {
579
1308
  await this.publishTyping();
580
- return this.persist(this.messageId, text, "response", this.parentFor(opts));
1309
+ return this.deliver(text, "response", this.parentFor(opts));
581
1310
  }
582
1311
  /** Replies thread under the answered message unless overridden. */
583
1312
  parentFor(opts) {
@@ -588,6 +1317,12 @@ var MessageContext = class {
588
1317
  * every chunkBatchMs (default 200ms), then POSTs the final message.
589
1318
  * Resolves with the full response text.
590
1319
  *
1320
+ * A provider error (the generator throwing) does not reject: the failure
1321
+ * is stored under the same id as an `error` bubble, exposed as `error`,
1322
+ * and the text streamed so far is returned. Only a delivery failure — the
1323
+ * server rejecting the final POST after the retry — rejects, and remote
1324
+ * bubbles are closed before it does.
1325
+ *
591
1326
  * Mirrors useAbly.ts chunk batching pattern.
592
1327
  */
593
1328
  async stream(generator, opts) {
@@ -599,16 +1334,20 @@ var MessageContext = class {
599
1334
  if (!chunkBuffer) return;
600
1335
  const text = chunkBuffer;
601
1336
  chunkBuffer = "";
602
- await this.publishChunk(text);
1337
+ try {
1338
+ await this.publishChunk(text);
1339
+ } catch (e) {
1340
+ console.warn("[sdk] chunk publish failed:", e instanceof Error ? e.message : e);
1341
+ }
603
1342
  };
604
1343
  try {
605
1344
  for await (const chunk of generator()) {
606
1345
  fullText += chunk;
607
1346
  chunkBuffer += chunk;
608
1347
  if (!flushTimer) {
609
- flushTimer = setTimeout(async () => {
1348
+ flushTimer = setTimeout(() => {
610
1349
  flushTimer = null;
611
- await flushChunks();
1350
+ void flushChunks();
612
1351
  }, this.chunkBatchMs);
613
1352
  }
614
1353
  }
@@ -616,13 +1355,16 @@ var MessageContext = class {
616
1355
  await flushChunks();
617
1356
  } catch (err) {
618
1357
  if (flushTimer) clearTimeout(flushTimer);
1358
+ this.streamError = err;
619
1359
  const errText = `Agent error: ${err instanceof Error ? err.message : String(err)}`;
620
- await this.persist(this.messageId, errText, "error", this.parentFor(opts)).catch((e) => {
1360
+ try {
1361
+ await this.deliver(errText, "error", this.parentFor(opts));
1362
+ } catch (e) {
621
1363
  console.error("[sdk] Failed to persist error message:", e);
622
- });
623
- throw err;
1364
+ }
1365
+ return fullText;
624
1366
  }
625
- await this.persist(this.messageId, fullText, "response", this.parentFor(opts));
1367
+ await this.deliver(fullText, "response", this.parentFor(opts));
626
1368
  return fullText;
627
1369
  }
628
1370
  // ── Internal publish helpers ────────────────────────────────────────
@@ -651,6 +1393,44 @@ var MessageContext = class {
651
1393
  agentId: this.agentId
652
1394
  });
653
1395
  }
1396
+ /**
1397
+ * POST this reply's final message. If the server rejects it (after
1398
+ * `persistMessage`'s single retry), every other client is stuck on the
1399
+ * streaming bubble our `typing`/`chunk` events opened — the server echo
1400
+ * that would close it is never coming. Close them with a client-published
1401
+ * `error` event under the same id (ephemeral: the server does not persist
1402
+ * it, acceptable for a last resort), then rethrow.
1403
+ */
1404
+ async deliver(text, type, parentMessageId) {
1405
+ try {
1406
+ return await this.persist(this.messageId, text, type, parentMessageId);
1407
+ } catch (err) {
1408
+ await this.publishDeliveryFailure(
1409
+ err instanceof Error ? err.message : String(err),
1410
+ parentMessageId
1411
+ );
1412
+ throw err;
1413
+ }
1414
+ }
1415
+ /** Same wire shape as the desktop's delivery-failure fallback (useAbly.ts deliver()). */
1416
+ async publishDeliveryFailure(reason, parentMessageId) {
1417
+ try {
1418
+ await this.ablyManager.publish(this.channelName, "message", {
1419
+ from: this.from,
1420
+ fromUsername: this.agentName,
1421
+ projectId: this.projectId,
1422
+ text: `Delivery failed: ${reason}`,
1423
+ messageId: this.messageId,
1424
+ type: "error",
1425
+ agentName: this.agentName,
1426
+ agentId: this.agentId,
1427
+ isAgentMessage: true,
1428
+ parentMessageId
1429
+ });
1430
+ } catch (e) {
1431
+ console.warn("[sdk] delivery-failure publish failed:", e instanceof Error ? e.message : e);
1432
+ }
1433
+ }
654
1434
  /** POST the final message. Throws if the server rejects it. */
655
1435
  async persist(id, text, type, parentMessageId) {
656
1436
  this.tracker?.begin(id, this.projectId, text, type, parentMessageId);
@@ -760,7 +1540,7 @@ function escapeRegex(s) {
760
1540
  // src/providers/anthropic.ts
761
1541
  var ANTHROPIC_API_URL = "https://api.anthropic.com/v1/messages";
762
1542
  var ANTHROPIC_VERSION = "2024-10-22";
763
- var DEFAULT_MODEL = "claude-sonnet-4-6";
1543
+ var DEFAULT_MODEL = "claude-sonnet-5";
764
1544
  var DEFAULT_MAX_TOKENS = 8192;
765
1545
  var AnthropicProvider = class {
766
1546
  apiKey;
@@ -1154,7 +1934,7 @@ var OWN_MESSAGE_MEMORY = 1e3;
1154
1934
  var MESSAGE_INDEX_SIZE = 500;
1155
1935
  var META_TTL_MS = 5 * 60 * 1e3;
1156
1936
  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.";
1157
- var JaibberAgent = class extends import_events.EventEmitter {
1937
+ var JaibberAgent = class _JaibberAgent extends import_events.EventEmitter {
1158
1938
  config;
1159
1939
  client;
1160
1940
  ablyManager = null;
@@ -1168,6 +1948,7 @@ var JaibberAgent = class extends import_events.EventEmitter {
1168
1948
  heartbeatTimer = null;
1169
1949
  agentId = null;
1170
1950
  agentRecord = null;
1951
+ keyIdentity = null;
1171
1952
  /** In-memory conversation history per project. */
1172
1953
  history = /* @__PURE__ */ new Map();
1173
1954
  /** Recent messages per project (id → author/parent) for chain reconstruction. */
@@ -1191,6 +1972,23 @@ var JaibberAgent = class extends import_events.EventEmitter {
1191
1972
  super();
1192
1973
  this.config = config;
1193
1974
  this.client = new JaibberClient(config.serverUrl);
1975
+ this.on("error", _JaibberAgent.defaultErrorListener);
1976
+ }
1977
+ /**
1978
+ * Default `"error"` listener, registered by the constructor: logs the error
1979
+ * and keeps the process alive. To handle errors yourself without the log,
1980
+ * remove it: `agent.off("error", JaibberAgent.defaultErrorListener)`.
1981
+ */
1982
+ static defaultErrorListener = (err) => {
1983
+ console.error("[jaibber-agent] error:", err);
1984
+ };
1985
+ /** Emit `"error"` without ever throwing, even if every listener was removed. */
1986
+ emitError(err) {
1987
+ if (this.listenerCount("error") === 0) {
1988
+ _JaibberAgent.defaultErrorListener(err);
1989
+ return;
1990
+ }
1991
+ this.emit("error", err);
1194
1992
  }
1195
1993
  // ── Accessors ───────────────────────────────────────────────────────
1196
1994
  /** The agent's server-side id (available after `connect()`). */
@@ -1201,6 +1999,10 @@ var JaibberAgent = class extends import_events.EventEmitter {
1201
1999
  get record() {
1202
2000
  return this.agentRecord;
1203
2001
  }
2002
+ /** The key's agent identity from `GET /api/me` (API-key mode, on servers that have it). */
2003
+ get identity() {
2004
+ return this.keyIdentity;
2005
+ }
1204
2006
  /** The underlying REST client (authenticated after `connect()`). */
1205
2007
  get api() {
1206
2008
  return this.client;
@@ -1226,6 +2028,7 @@ var JaibberAgent = class extends import_events.EventEmitter {
1226
2028
  this.client.setApiKey(creds.apiKey);
1227
2029
  this.agentId = this.config.agentId ?? null;
1228
2030
  console.log(`[sdk] Authenticating with agent API key ${creds.apiKey.slice(0, 11)}\u2026`);
2031
+ await this.resolveKeyIdentity();
1229
2032
  } else {
1230
2033
  console.log(`[sdk] Logging in as "${creds.username}"...`);
1231
2034
  await this.client.login(creds.username, creds.password);
@@ -1321,7 +2124,8 @@ var JaibberAgent = class extends import_events.EventEmitter {
1321
2124
  presenceData,
1322
2125
  (msg) => this.handleIncomingMessage(msg, project),
1323
2126
  (data) => this.handleTaskEvent(data, project),
1324
- (data) => this.handleControlEvent(data, project)
2127
+ (data) => this.handleControlEvent(data, project),
2128
+ (err) => this.emitError(err)
1325
2129
  );
1326
2130
  this.unsubscribers.push(unsub);
1327
2131
  }
@@ -1340,6 +2144,43 @@ var JaibberAgent = class extends import_events.EventEmitter {
1340
2144
  );
1341
2145
  this.emit("connected", this.projects);
1342
2146
  }
2147
+ /**
2148
+ * API-key mode: ask the server who the key is (`GET /api/me`) so the agent
2149
+ * id and name are known before Ably connects. Servers that predate the
2150
+ * endpoint answer 404; the id is then read from the Ably token's clientId
2151
+ * (`agent:{id}`) once connected, as in 0.4.0.
2152
+ */
2153
+ async resolveKeyIdentity() {
2154
+ const me = await this.client.whoAmI();
2155
+ if (me === null) {
2156
+ console.warn(
2157
+ "[sdk] GET /api/me is not available on this server; the agent id will be read from the Ably token."
2158
+ );
2159
+ return;
2160
+ }
2161
+ if (me.type !== "agent") {
2162
+ throw new Error(
2163
+ `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\`.`
2164
+ );
2165
+ }
2166
+ if (this.agentId && this.agentId !== me.agentId) {
2167
+ console.warn(
2168
+ `[sdk] Configured agentId ${this.agentId} does not match the key's agent ${me.agentId}; using the key's.`
2169
+ );
2170
+ }
2171
+ this.agentId = me.agentId;
2172
+ this.config.agentId = me.agentId;
2173
+ this.keyIdentity = me;
2174
+ if (me.name && me.name.toLowerCase() !== this.config.agentName.toLowerCase()) {
2175
+ console.warn(
2176
+ `[sdk] agentName "${this.config.agentName}" differs from the key's agent "${me.name}"; using "${me.name}".`
2177
+ );
2178
+ this.config.agentName = me.name;
2179
+ }
2180
+ console.log(
2181
+ `[sdk] Authenticated as agent "${me.name}" (id ${me.agentId}${me.org ? `, org ${me.org.slug}` : ""})`
2182
+ );
2183
+ }
1343
2184
  /** Stop heartbeats, leave presence, disconnect Ably. */
1344
2185
  async disconnect() {
1345
2186
  if (!this.connected) return;
@@ -1553,8 +2394,7 @@ var JaibberAgent = class extends import_events.EventEmitter {
1553
2394
  try {
1554
2395
  await this.respondToMessage(payload, project, depth, chain, executionMode, attachments);
1555
2396
  } catch (err) {
1556
- console.error("[sdk] Error responding to message:", err);
1557
- this.emit("error", err);
2397
+ this.emitError(err);
1558
2398
  } finally {
1559
2399
  this.activeResponses.delete(payload.messageId);
1560
2400
  }
@@ -1608,6 +2448,7 @@ var JaibberAgent = class extends import_events.EventEmitter {
1608
2448
  },
1609
2449
  ctx
1610
2450
  );
2451
+ if (ctx.error !== void 0) this.emitError(ctx.error);
1611
2452
  return;
1612
2453
  }
1613
2454
  if (this.provider) {
@@ -1616,6 +2457,10 @@ var JaibberAgent = class extends import_events.EventEmitter {
1616
2457
  await ctx.stream(
1617
2458
  () => this.provider.generate(payload.text, systemPrompt, conversationHistory)
1618
2459
  );
2460
+ if (ctx.error !== void 0) {
2461
+ this.emitError(ctx.error);
2462
+ return;
2463
+ }
1619
2464
  this.captureProviderSession(project.id);
1620
2465
  return;
1621
2466
  }
@@ -1664,9 +2509,8 @@ ${instructions}` : PLAN_MODE_PREFIX;
1664
2509
  return;
1665
2510
  const task = data.task;
1666
2511
  if (task.status !== "submitted") return;
1667
- const assignedById = !!task.assignedAgentId && !!this.agentId && task.assignedAgentId === this.agentId;
1668
- const assignedByName = !!task.assignedAgentName && task.assignedAgentName.toLowerCase() === this.config.agentName.toLowerCase();
1669
- if (!assignedById && !assignedByName) return;
2512
+ const mine = task.assignedAgentId ? !!this.agentId && task.assignedAgentId === this.agentId : !!task.assignedAgentName && task.assignedAgentName.toLowerCase() === this.config.agentName.toLowerCase();
2513
+ if (!mine) return;
1670
2514
  console.log(
1671
2515
  `[sdk] Picking up task: "${task.title}" (${task.id})`
1672
2516
  );
@@ -1716,26 +2560,27 @@ ${task.description}` : `Task: ${task.title}`;
1716
2560
  chunkBatchMs: this.config.chunkBatchMs ?? DEFAULT_CHUNK_BATCH_MS,
1717
2561
  tracker: this.tracker
1718
2562
  });
1719
- try {
1720
- await msgCtx.stream(
1721
- () => this.provider.generate(
1722
- taskPrompt,
1723
- systemPrompt,
1724
- conversationHistory
1725
- )
1726
- );
1727
- this.captureProviderSession(project.id);
1728
- await this.client.updateTask(task.id, { status: "completed" });
1729
- } catch {
2563
+ await msgCtx.stream(
2564
+ () => this.provider.generate(
2565
+ taskPrompt,
2566
+ systemPrompt,
2567
+ conversationHistory
2568
+ )
2569
+ );
2570
+ if (msgCtx.error !== void 0) {
2571
+ this.emitError(msgCtx.error);
1730
2572
  await this.client.updateTask(task.id, { status: "failed" });
2573
+ return;
1731
2574
  }
2575
+ this.captureProviderSession(project.id);
2576
+ await this.client.updateTask(task.id, { status: "completed" });
1732
2577
  return;
1733
2578
  }
1734
2579
  console.warn(
1735
2580
  "[sdk] No task handler or provider configured. Task left as working."
1736
2581
  );
1737
2582
  } catch (err) {
1738
- console.error("[sdk] Error handling task:", err);
2583
+ this.emitError(err);
1739
2584
  try {
1740
2585
  await this.client.updateTask(task.id, { status: "failed" });
1741
2586
  } catch {
@@ -1885,11 +2730,17 @@ function getTemplate(id) {
1885
2730
  ClaudeCLIProvider,
1886
2731
  GoogleProvider,
1887
2732
  JaibberAgent,
2733
+ JaibberApiError,
1888
2734
  JaibberClient,
1889
2735
  MessageContext,
1890
2736
  OpenAIProvider,
1891
2737
  TaskContext,
1892
2738
  getTemplate,
2739
+ isBanned,
2740
+ isContactNotAllowed,
2741
+ isJaibberApiError,
2742
+ isPaymentRequired,
2743
+ isRateLimited,
1893
2744
  mentionsAgent,
1894
2745
  parseMentions
1895
2746
  });