@jaibber/sdk 0.4.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -169,6 +169,22 @@ var JaibberClient = class {
169
169
  }
170
170
  return res;
171
171
  }
172
+ // ── Identity ────────────────────────────────────────────────────────
173
+ /**
174
+ * GET /api/me — who the current credential is: the user (session), the
175
+ * agent (agent-bound key) or the org (org key). Resolves `null` when the
176
+ * server predates the endpoint (404).
177
+ */
178
+ async whoAmI() {
179
+ const res = await fetch(`${this.serverUrl}/api/me`, { headers: this.authHeaders() });
180
+ if (res.status === 404) return null;
181
+ if (!res.ok) {
182
+ const text = await readError(res);
183
+ throw new Error(`GET /api/me failed (${res.status}): ${text}`);
184
+ }
185
+ const json = await res.json();
186
+ return json.data;
187
+ }
172
188
  // ── Projects ────────────────────────────────────────────────────────
173
189
  /**
174
190
  * GET /api/projects — with a session: projects the user is a member of
@@ -449,26 +465,33 @@ var AblyManager = class {
449
465
  * `agent-control` events) and enter per-project presence.
450
466
  * Returns an unsubscribe function.
451
467
  */
452
- async subscribeToProject(project, presenceData, onMessage, onTask, onControl) {
468
+ async subscribeToProject(project, presenceData, onMessage, onTask, onControl, onError = (err, event) => console.error(`[sdk] Unhandled error in ${event} handler:`, err)) {
453
469
  if (!this.ably) throw new Error("Ably not connected");
454
470
  const channel = this.ably.channels.get(project.ablyChannelName);
455
471
  this.channels.set(project.ablyChannelName, channel);
456
472
  await channel.presence.enter(presenceData);
457
- const messageHandler = (msg) => {
458
- if (!msg.data) return;
473
+ const safely = (event, body) => {
474
+ try {
475
+ Promise.resolve(body()).catch((err) => onError(err, event));
476
+ } catch (err) {
477
+ onError(err, event);
478
+ }
479
+ };
480
+ const messageHandler = (msg) => safely("message", () => {
481
+ if (!msg.data || typeof msg.data !== "object") return;
459
482
  const payload = msg.data;
460
483
  payload._connectionId = msg.connectionId ?? void 0;
461
484
  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) => {
485
+ return onMessage(payload);
486
+ });
487
+ const taskHandler = (msg) => safely("task", () => {
469
488
  if (!msg.data || typeof msg.data !== "object") return;
470
- onControl?.(msg.data);
471
- };
489
+ return onTask(msg.data);
490
+ });
491
+ const controlHandler = (msg) => safely("agent-control", () => {
492
+ if (!msg.data || typeof msg.data !== "object") return;
493
+ return onControl?.(msg.data);
494
+ });
472
495
  channel.subscribe("message", messageHandler);
473
496
  channel.subscribe("task", taskHandler);
474
497
  channel.subscribe("agent-control", controlHandler);
@@ -547,6 +570,8 @@ var MessageContext = class {
547
570
  respondingChain;
548
571
  chunkBatchMs;
549
572
  tracker;
573
+ /** Set by `stream()` when its generator threw. */
574
+ streamError = void 0;
550
575
  constructor(opts) {
551
576
  this.projectId = opts.projectId;
552
577
  this.channelName = opts.channelName;
@@ -574,10 +599,23 @@ var MessageContext = class {
574
599
  get chain() {
575
600
  return [...this.respondingChain];
576
601
  }
577
- /** One-shot reply: publishes `typing`, then POSTs the final message. */
602
+ /**
603
+ * Why `stream()` failed, if it did: the error its generator threw;
604
+ * `undefined` otherwise. The failure has already been stored under this
605
+ * reply's id as an `error` bubble, and `stream()` resolved with the
606
+ * partial text.
607
+ */
608
+ get error() {
609
+ return this.streamError;
610
+ }
611
+ /**
612
+ * One-shot reply: publishes `typing`, then POSTs the final message.
613
+ * Throws if the server rejects it (remote bubbles are closed first — see
614
+ * `deliver`).
615
+ */
578
616
  async reply(text, opts) {
579
617
  await this.publishTyping();
580
- return this.persist(this.messageId, text, "response", this.parentFor(opts));
618
+ return this.deliver(text, "response", this.parentFor(opts));
581
619
  }
582
620
  /** Replies thread under the answered message unless overridden. */
583
621
  parentFor(opts) {
@@ -588,6 +626,12 @@ var MessageContext = class {
588
626
  * every chunkBatchMs (default 200ms), then POSTs the final message.
589
627
  * Resolves with the full response text.
590
628
  *
629
+ * A provider error (the generator throwing) does not reject: the failure
630
+ * is stored under the same id as an `error` bubble, exposed as `error`,
631
+ * and the text streamed so far is returned. Only a delivery failure — the
632
+ * server rejecting the final POST after the retry — rejects, and remote
633
+ * bubbles are closed before it does.
634
+ *
591
635
  * Mirrors useAbly.ts chunk batching pattern.
592
636
  */
593
637
  async stream(generator, opts) {
@@ -599,16 +643,20 @@ var MessageContext = class {
599
643
  if (!chunkBuffer) return;
600
644
  const text = chunkBuffer;
601
645
  chunkBuffer = "";
602
- await this.publishChunk(text);
646
+ try {
647
+ await this.publishChunk(text);
648
+ } catch (e) {
649
+ console.warn("[sdk] chunk publish failed:", e instanceof Error ? e.message : e);
650
+ }
603
651
  };
604
652
  try {
605
653
  for await (const chunk of generator()) {
606
654
  fullText += chunk;
607
655
  chunkBuffer += chunk;
608
656
  if (!flushTimer) {
609
- flushTimer = setTimeout(async () => {
657
+ flushTimer = setTimeout(() => {
610
658
  flushTimer = null;
611
- await flushChunks();
659
+ void flushChunks();
612
660
  }, this.chunkBatchMs);
613
661
  }
614
662
  }
@@ -616,13 +664,16 @@ var MessageContext = class {
616
664
  await flushChunks();
617
665
  } catch (err) {
618
666
  if (flushTimer) clearTimeout(flushTimer);
667
+ this.streamError = err;
619
668
  const errText = `Agent error: ${err instanceof Error ? err.message : String(err)}`;
620
- await this.persist(this.messageId, errText, "error", this.parentFor(opts)).catch((e) => {
669
+ try {
670
+ await this.deliver(errText, "error", this.parentFor(opts));
671
+ } catch (e) {
621
672
  console.error("[sdk] Failed to persist error message:", e);
622
- });
623
- throw err;
673
+ }
674
+ return fullText;
624
675
  }
625
- await this.persist(this.messageId, fullText, "response", this.parentFor(opts));
676
+ await this.deliver(fullText, "response", this.parentFor(opts));
626
677
  return fullText;
627
678
  }
628
679
  // ── Internal publish helpers ────────────────────────────────────────
@@ -651,6 +702,44 @@ var MessageContext = class {
651
702
  agentId: this.agentId
652
703
  });
653
704
  }
705
+ /**
706
+ * POST this reply's final message. If the server rejects it (after
707
+ * `persistMessage`'s single retry), every other client is stuck on the
708
+ * streaming bubble our `typing`/`chunk` events opened — the server echo
709
+ * that would close it is never coming. Close them with a client-published
710
+ * `error` event under the same id (ephemeral: the server does not persist
711
+ * it, acceptable for a last resort), then rethrow.
712
+ */
713
+ async deliver(text, type, parentMessageId) {
714
+ try {
715
+ return await this.persist(this.messageId, text, type, parentMessageId);
716
+ } catch (err) {
717
+ await this.publishDeliveryFailure(
718
+ err instanceof Error ? err.message : String(err),
719
+ parentMessageId
720
+ );
721
+ throw err;
722
+ }
723
+ }
724
+ /** Same wire shape as the desktop's delivery-failure fallback (useAbly.ts deliver()). */
725
+ async publishDeliveryFailure(reason, parentMessageId) {
726
+ try {
727
+ await this.ablyManager.publish(this.channelName, "message", {
728
+ from: this.from,
729
+ fromUsername: this.agentName,
730
+ projectId: this.projectId,
731
+ text: `Delivery failed: ${reason}`,
732
+ messageId: this.messageId,
733
+ type: "error",
734
+ agentName: this.agentName,
735
+ agentId: this.agentId,
736
+ isAgentMessage: true,
737
+ parentMessageId
738
+ });
739
+ } catch (e) {
740
+ console.warn("[sdk] delivery-failure publish failed:", e instanceof Error ? e.message : e);
741
+ }
742
+ }
654
743
  /** POST the final message. Throws if the server rejects it. */
655
744
  async persist(id, text, type, parentMessageId) {
656
745
  this.tracker?.begin(id, this.projectId, text, type, parentMessageId);
@@ -760,7 +849,7 @@ function escapeRegex(s) {
760
849
  // src/providers/anthropic.ts
761
850
  var ANTHROPIC_API_URL = "https://api.anthropic.com/v1/messages";
762
851
  var ANTHROPIC_VERSION = "2024-10-22";
763
- var DEFAULT_MODEL = "claude-sonnet-4-6";
852
+ var DEFAULT_MODEL = "claude-sonnet-5";
764
853
  var DEFAULT_MAX_TOKENS = 8192;
765
854
  var AnthropicProvider = class {
766
855
  apiKey;
@@ -1154,7 +1243,7 @@ var OWN_MESSAGE_MEMORY = 1e3;
1154
1243
  var MESSAGE_INDEX_SIZE = 500;
1155
1244
  var META_TTL_MS = 5 * 60 * 1e3;
1156
1245
  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 {
1246
+ var JaibberAgent = class _JaibberAgent extends import_events.EventEmitter {
1158
1247
  config;
1159
1248
  client;
1160
1249
  ablyManager = null;
@@ -1168,6 +1257,7 @@ var JaibberAgent = class extends import_events.EventEmitter {
1168
1257
  heartbeatTimer = null;
1169
1258
  agentId = null;
1170
1259
  agentRecord = null;
1260
+ keyIdentity = null;
1171
1261
  /** In-memory conversation history per project. */
1172
1262
  history = /* @__PURE__ */ new Map();
1173
1263
  /** Recent messages per project (id → author/parent) for chain reconstruction. */
@@ -1191,6 +1281,23 @@ var JaibberAgent = class extends import_events.EventEmitter {
1191
1281
  super();
1192
1282
  this.config = config;
1193
1283
  this.client = new JaibberClient(config.serverUrl);
1284
+ this.on("error", _JaibberAgent.defaultErrorListener);
1285
+ }
1286
+ /**
1287
+ * Default `"error"` listener, registered by the constructor: logs the error
1288
+ * and keeps the process alive. To handle errors yourself without the log,
1289
+ * remove it: `agent.off("error", JaibberAgent.defaultErrorListener)`.
1290
+ */
1291
+ static defaultErrorListener = (err) => {
1292
+ console.error("[jaibber-agent] error:", err);
1293
+ };
1294
+ /** Emit `"error"` without ever throwing, even if every listener was removed. */
1295
+ emitError(err) {
1296
+ if (this.listenerCount("error") === 0) {
1297
+ _JaibberAgent.defaultErrorListener(err);
1298
+ return;
1299
+ }
1300
+ this.emit("error", err);
1194
1301
  }
1195
1302
  // ── Accessors ───────────────────────────────────────────────────────
1196
1303
  /** The agent's server-side id (available after `connect()`). */
@@ -1201,6 +1308,10 @@ var JaibberAgent = class extends import_events.EventEmitter {
1201
1308
  get record() {
1202
1309
  return this.agentRecord;
1203
1310
  }
1311
+ /** The key's agent identity from `GET /api/me` (API-key mode, on servers that have it). */
1312
+ get identity() {
1313
+ return this.keyIdentity;
1314
+ }
1204
1315
  /** The underlying REST client (authenticated after `connect()`). */
1205
1316
  get api() {
1206
1317
  return this.client;
@@ -1226,6 +1337,7 @@ var JaibberAgent = class extends import_events.EventEmitter {
1226
1337
  this.client.setApiKey(creds.apiKey);
1227
1338
  this.agentId = this.config.agentId ?? null;
1228
1339
  console.log(`[sdk] Authenticating with agent API key ${creds.apiKey.slice(0, 11)}\u2026`);
1340
+ await this.resolveKeyIdentity();
1229
1341
  } else {
1230
1342
  console.log(`[sdk] Logging in as "${creds.username}"...`);
1231
1343
  await this.client.login(creds.username, creds.password);
@@ -1321,7 +1433,8 @@ var JaibberAgent = class extends import_events.EventEmitter {
1321
1433
  presenceData,
1322
1434
  (msg) => this.handleIncomingMessage(msg, project),
1323
1435
  (data) => this.handleTaskEvent(data, project),
1324
- (data) => this.handleControlEvent(data, project)
1436
+ (data) => this.handleControlEvent(data, project),
1437
+ (err) => this.emitError(err)
1325
1438
  );
1326
1439
  this.unsubscribers.push(unsub);
1327
1440
  }
@@ -1340,6 +1453,43 @@ var JaibberAgent = class extends import_events.EventEmitter {
1340
1453
  );
1341
1454
  this.emit("connected", this.projects);
1342
1455
  }
1456
+ /**
1457
+ * API-key mode: ask the server who the key is (`GET /api/me`) so the agent
1458
+ * id and name are known before Ably connects. Servers that predate the
1459
+ * endpoint answer 404; the id is then read from the Ably token's clientId
1460
+ * (`agent:{id}`) once connected, as in 0.4.0.
1461
+ */
1462
+ async resolveKeyIdentity() {
1463
+ const me = await this.client.whoAmI();
1464
+ if (me === null) {
1465
+ console.warn(
1466
+ "[sdk] GET /api/me is not available on this server; the agent id will be read from the Ably token."
1467
+ );
1468
+ return;
1469
+ }
1470
+ if (me.type !== "agent") {
1471
+ throw new Error(
1472
+ `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\`.`
1473
+ );
1474
+ }
1475
+ if (this.agentId && this.agentId !== me.agentId) {
1476
+ console.warn(
1477
+ `[sdk] Configured agentId ${this.agentId} does not match the key's agent ${me.agentId}; using the key's.`
1478
+ );
1479
+ }
1480
+ this.agentId = me.agentId;
1481
+ this.config.agentId = me.agentId;
1482
+ this.keyIdentity = me;
1483
+ if (me.name && me.name.toLowerCase() !== this.config.agentName.toLowerCase()) {
1484
+ console.warn(
1485
+ `[sdk] agentName "${this.config.agentName}" differs from the key's agent "${me.name}"; using "${me.name}".`
1486
+ );
1487
+ this.config.agentName = me.name;
1488
+ }
1489
+ console.log(
1490
+ `[sdk] Authenticated as agent "${me.name}" (id ${me.agentId}${me.org ? `, org ${me.org.slug}` : ""})`
1491
+ );
1492
+ }
1343
1493
  /** Stop heartbeats, leave presence, disconnect Ably. */
1344
1494
  async disconnect() {
1345
1495
  if (!this.connected) return;
@@ -1553,8 +1703,7 @@ var JaibberAgent = class extends import_events.EventEmitter {
1553
1703
  try {
1554
1704
  await this.respondToMessage(payload, project, depth, chain, executionMode, attachments);
1555
1705
  } catch (err) {
1556
- console.error("[sdk] Error responding to message:", err);
1557
- this.emit("error", err);
1706
+ this.emitError(err);
1558
1707
  } finally {
1559
1708
  this.activeResponses.delete(payload.messageId);
1560
1709
  }
@@ -1608,6 +1757,7 @@ var JaibberAgent = class extends import_events.EventEmitter {
1608
1757
  },
1609
1758
  ctx
1610
1759
  );
1760
+ if (ctx.error !== void 0) this.emitError(ctx.error);
1611
1761
  return;
1612
1762
  }
1613
1763
  if (this.provider) {
@@ -1616,6 +1766,10 @@ var JaibberAgent = class extends import_events.EventEmitter {
1616
1766
  await ctx.stream(
1617
1767
  () => this.provider.generate(payload.text, systemPrompt, conversationHistory)
1618
1768
  );
1769
+ if (ctx.error !== void 0) {
1770
+ this.emitError(ctx.error);
1771
+ return;
1772
+ }
1619
1773
  this.captureProviderSession(project.id);
1620
1774
  return;
1621
1775
  }
@@ -1664,9 +1818,8 @@ ${instructions}` : PLAN_MODE_PREFIX;
1664
1818
  return;
1665
1819
  const task = data.task;
1666
1820
  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;
1821
+ const mine = task.assignedAgentId ? !!this.agentId && task.assignedAgentId === this.agentId : !!task.assignedAgentName && task.assignedAgentName.toLowerCase() === this.config.agentName.toLowerCase();
1822
+ if (!mine) return;
1670
1823
  console.log(
1671
1824
  `[sdk] Picking up task: "${task.title}" (${task.id})`
1672
1825
  );
@@ -1716,26 +1869,27 @@ ${task.description}` : `Task: ${task.title}`;
1716
1869
  chunkBatchMs: this.config.chunkBatchMs ?? DEFAULT_CHUNK_BATCH_MS,
1717
1870
  tracker: this.tracker
1718
1871
  });
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 {
1872
+ await msgCtx.stream(
1873
+ () => this.provider.generate(
1874
+ taskPrompt,
1875
+ systemPrompt,
1876
+ conversationHistory
1877
+ )
1878
+ );
1879
+ if (msgCtx.error !== void 0) {
1880
+ this.emitError(msgCtx.error);
1730
1881
  await this.client.updateTask(task.id, { status: "failed" });
1882
+ return;
1731
1883
  }
1884
+ this.captureProviderSession(project.id);
1885
+ await this.client.updateTask(task.id, { status: "completed" });
1732
1886
  return;
1733
1887
  }
1734
1888
  console.warn(
1735
1889
  "[sdk] No task handler or provider configured. Task left as working."
1736
1890
  );
1737
1891
  } catch (err) {
1738
- console.error("[sdk] Error handling task:", err);
1892
+ this.emitError(err);
1739
1893
  try {
1740
1894
  await this.client.updateTask(task.id, { status: "failed" });
1741
1895
  } catch {