@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/README.md +44 -2
- package/dist/cli.js +209 -44
- package/dist/index.cjs +195 -41
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +101 -10
- package/dist/index.d.ts +101 -10
- package/dist/index.js +195 -41
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -122,6 +122,22 @@ var JaibberClient = class {
|
|
|
122
122
|
}
|
|
123
123
|
return res;
|
|
124
124
|
}
|
|
125
|
+
// ── Identity ────────────────────────────────────────────────────────
|
|
126
|
+
/**
|
|
127
|
+
* GET /api/me — who the current credential is: the user (session), the
|
|
128
|
+
* agent (agent-bound key) or the org (org key). Resolves `null` when the
|
|
129
|
+
* server predates the endpoint (404).
|
|
130
|
+
*/
|
|
131
|
+
async whoAmI() {
|
|
132
|
+
const res = await fetch(`${this.serverUrl}/api/me`, { headers: this.authHeaders() });
|
|
133
|
+
if (res.status === 404) return null;
|
|
134
|
+
if (!res.ok) {
|
|
135
|
+
const text = await readError(res);
|
|
136
|
+
throw new Error(`GET /api/me failed (${res.status}): ${text}`);
|
|
137
|
+
}
|
|
138
|
+
const json = await res.json();
|
|
139
|
+
return json.data;
|
|
140
|
+
}
|
|
125
141
|
// ── Projects ────────────────────────────────────────────────────────
|
|
126
142
|
/**
|
|
127
143
|
* GET /api/projects — with a session: projects the user is a member of
|
|
@@ -402,26 +418,33 @@ var AblyManager = class {
|
|
|
402
418
|
* `agent-control` events) and enter per-project presence.
|
|
403
419
|
* Returns an unsubscribe function.
|
|
404
420
|
*/
|
|
405
|
-
async subscribeToProject(project, presenceData, onMessage, onTask, onControl) {
|
|
421
|
+
async subscribeToProject(project, presenceData, onMessage, onTask, onControl, onError = (err, event) => console.error(`[sdk] Unhandled error in ${event} handler:`, err)) {
|
|
406
422
|
if (!this.ably) throw new Error("Ably not connected");
|
|
407
423
|
const channel = this.ably.channels.get(project.ablyChannelName);
|
|
408
424
|
this.channels.set(project.ablyChannelName, channel);
|
|
409
425
|
await channel.presence.enter(presenceData);
|
|
410
|
-
const
|
|
411
|
-
|
|
426
|
+
const safely = (event, body) => {
|
|
427
|
+
try {
|
|
428
|
+
Promise.resolve(body()).catch((err) => onError(err, event));
|
|
429
|
+
} catch (err) {
|
|
430
|
+
onError(err, event);
|
|
431
|
+
}
|
|
432
|
+
};
|
|
433
|
+
const messageHandler = (msg) => safely("message", () => {
|
|
434
|
+
if (!msg.data || typeof msg.data !== "object") return;
|
|
412
435
|
const payload = msg.data;
|
|
413
436
|
payload._connectionId = msg.connectionId ?? void 0;
|
|
414
437
|
payload._clientId = msg.clientId ?? void 0;
|
|
415
|
-
onMessage(payload);
|
|
416
|
-
};
|
|
417
|
-
const taskHandler = (msg) => {
|
|
418
|
-
if (!msg.data) return;
|
|
419
|
-
onTask(msg.data);
|
|
420
|
-
};
|
|
421
|
-
const controlHandler = (msg) => {
|
|
438
|
+
return onMessage(payload);
|
|
439
|
+
});
|
|
440
|
+
const taskHandler = (msg) => safely("task", () => {
|
|
422
441
|
if (!msg.data || typeof msg.data !== "object") return;
|
|
423
|
-
|
|
424
|
-
};
|
|
442
|
+
return onTask(msg.data);
|
|
443
|
+
});
|
|
444
|
+
const controlHandler = (msg) => safely("agent-control", () => {
|
|
445
|
+
if (!msg.data || typeof msg.data !== "object") return;
|
|
446
|
+
return onControl?.(msg.data);
|
|
447
|
+
});
|
|
425
448
|
channel.subscribe("message", messageHandler);
|
|
426
449
|
channel.subscribe("task", taskHandler);
|
|
427
450
|
channel.subscribe("agent-control", controlHandler);
|
|
@@ -500,6 +523,8 @@ var MessageContext = class {
|
|
|
500
523
|
respondingChain;
|
|
501
524
|
chunkBatchMs;
|
|
502
525
|
tracker;
|
|
526
|
+
/** Set by `stream()` when its generator threw. */
|
|
527
|
+
streamError = void 0;
|
|
503
528
|
constructor(opts) {
|
|
504
529
|
this.projectId = opts.projectId;
|
|
505
530
|
this.channelName = opts.channelName;
|
|
@@ -527,10 +552,23 @@ var MessageContext = class {
|
|
|
527
552
|
get chain() {
|
|
528
553
|
return [...this.respondingChain];
|
|
529
554
|
}
|
|
530
|
-
/**
|
|
555
|
+
/**
|
|
556
|
+
* Why `stream()` failed, if it did: the error its generator threw;
|
|
557
|
+
* `undefined` otherwise. The failure has already been stored under this
|
|
558
|
+
* reply's id as an `error` bubble, and `stream()` resolved with the
|
|
559
|
+
* partial text.
|
|
560
|
+
*/
|
|
561
|
+
get error() {
|
|
562
|
+
return this.streamError;
|
|
563
|
+
}
|
|
564
|
+
/**
|
|
565
|
+
* One-shot reply: publishes `typing`, then POSTs the final message.
|
|
566
|
+
* Throws if the server rejects it (remote bubbles are closed first — see
|
|
567
|
+
* `deliver`).
|
|
568
|
+
*/
|
|
531
569
|
async reply(text, opts) {
|
|
532
570
|
await this.publishTyping();
|
|
533
|
-
return this.
|
|
571
|
+
return this.deliver(text, "response", this.parentFor(opts));
|
|
534
572
|
}
|
|
535
573
|
/** Replies thread under the answered message unless overridden. */
|
|
536
574
|
parentFor(opts) {
|
|
@@ -541,6 +579,12 @@ var MessageContext = class {
|
|
|
541
579
|
* every chunkBatchMs (default 200ms), then POSTs the final message.
|
|
542
580
|
* Resolves with the full response text.
|
|
543
581
|
*
|
|
582
|
+
* A provider error (the generator throwing) does not reject: the failure
|
|
583
|
+
* is stored under the same id as an `error` bubble, exposed as `error`,
|
|
584
|
+
* and the text streamed so far is returned. Only a delivery failure — the
|
|
585
|
+
* server rejecting the final POST after the retry — rejects, and remote
|
|
586
|
+
* bubbles are closed before it does.
|
|
587
|
+
*
|
|
544
588
|
* Mirrors useAbly.ts chunk batching pattern.
|
|
545
589
|
*/
|
|
546
590
|
async stream(generator, opts) {
|
|
@@ -552,16 +596,20 @@ var MessageContext = class {
|
|
|
552
596
|
if (!chunkBuffer) return;
|
|
553
597
|
const text = chunkBuffer;
|
|
554
598
|
chunkBuffer = "";
|
|
555
|
-
|
|
599
|
+
try {
|
|
600
|
+
await this.publishChunk(text);
|
|
601
|
+
} catch (e) {
|
|
602
|
+
console.warn("[sdk] chunk publish failed:", e instanceof Error ? e.message : e);
|
|
603
|
+
}
|
|
556
604
|
};
|
|
557
605
|
try {
|
|
558
606
|
for await (const chunk of generator()) {
|
|
559
607
|
fullText += chunk;
|
|
560
608
|
chunkBuffer += chunk;
|
|
561
609
|
if (!flushTimer) {
|
|
562
|
-
flushTimer = setTimeout(
|
|
610
|
+
flushTimer = setTimeout(() => {
|
|
563
611
|
flushTimer = null;
|
|
564
|
-
|
|
612
|
+
void flushChunks();
|
|
565
613
|
}, this.chunkBatchMs);
|
|
566
614
|
}
|
|
567
615
|
}
|
|
@@ -569,13 +617,16 @@ var MessageContext = class {
|
|
|
569
617
|
await flushChunks();
|
|
570
618
|
} catch (err) {
|
|
571
619
|
if (flushTimer) clearTimeout(flushTimer);
|
|
620
|
+
this.streamError = err;
|
|
572
621
|
const errText = `Agent error: ${err instanceof Error ? err.message : String(err)}`;
|
|
573
|
-
|
|
622
|
+
try {
|
|
623
|
+
await this.deliver(errText, "error", this.parentFor(opts));
|
|
624
|
+
} catch (e) {
|
|
574
625
|
console.error("[sdk] Failed to persist error message:", e);
|
|
575
|
-
}
|
|
576
|
-
|
|
626
|
+
}
|
|
627
|
+
return fullText;
|
|
577
628
|
}
|
|
578
|
-
await this.
|
|
629
|
+
await this.deliver(fullText, "response", this.parentFor(opts));
|
|
579
630
|
return fullText;
|
|
580
631
|
}
|
|
581
632
|
// ── Internal publish helpers ────────────────────────────────────────
|
|
@@ -604,6 +655,44 @@ var MessageContext = class {
|
|
|
604
655
|
agentId: this.agentId
|
|
605
656
|
});
|
|
606
657
|
}
|
|
658
|
+
/**
|
|
659
|
+
* POST this reply's final message. If the server rejects it (after
|
|
660
|
+
* `persistMessage`'s single retry), every other client is stuck on the
|
|
661
|
+
* streaming bubble our `typing`/`chunk` events opened — the server echo
|
|
662
|
+
* that would close it is never coming. Close them with a client-published
|
|
663
|
+
* `error` event under the same id (ephemeral: the server does not persist
|
|
664
|
+
* it, acceptable for a last resort), then rethrow.
|
|
665
|
+
*/
|
|
666
|
+
async deliver(text, type, parentMessageId) {
|
|
667
|
+
try {
|
|
668
|
+
return await this.persist(this.messageId, text, type, parentMessageId);
|
|
669
|
+
} catch (err) {
|
|
670
|
+
await this.publishDeliveryFailure(
|
|
671
|
+
err instanceof Error ? err.message : String(err),
|
|
672
|
+
parentMessageId
|
|
673
|
+
);
|
|
674
|
+
throw err;
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
/** Same wire shape as the desktop's delivery-failure fallback (useAbly.ts deliver()). */
|
|
678
|
+
async publishDeliveryFailure(reason, parentMessageId) {
|
|
679
|
+
try {
|
|
680
|
+
await this.ablyManager.publish(this.channelName, "message", {
|
|
681
|
+
from: this.from,
|
|
682
|
+
fromUsername: this.agentName,
|
|
683
|
+
projectId: this.projectId,
|
|
684
|
+
text: `Delivery failed: ${reason}`,
|
|
685
|
+
messageId: this.messageId,
|
|
686
|
+
type: "error",
|
|
687
|
+
agentName: this.agentName,
|
|
688
|
+
agentId: this.agentId,
|
|
689
|
+
isAgentMessage: true,
|
|
690
|
+
parentMessageId
|
|
691
|
+
});
|
|
692
|
+
} catch (e) {
|
|
693
|
+
console.warn("[sdk] delivery-failure publish failed:", e instanceof Error ? e.message : e);
|
|
694
|
+
}
|
|
695
|
+
}
|
|
607
696
|
/** POST the final message. Throws if the server rejects it. */
|
|
608
697
|
async persist(id, text, type, parentMessageId) {
|
|
609
698
|
this.tracker?.begin(id, this.projectId, text, type, parentMessageId);
|
|
@@ -713,7 +802,7 @@ function escapeRegex(s) {
|
|
|
713
802
|
// src/providers/anthropic.ts
|
|
714
803
|
var ANTHROPIC_API_URL = "https://api.anthropic.com/v1/messages";
|
|
715
804
|
var ANTHROPIC_VERSION = "2024-10-22";
|
|
716
|
-
var DEFAULT_MODEL = "claude-sonnet-
|
|
805
|
+
var DEFAULT_MODEL = "claude-sonnet-5";
|
|
717
806
|
var DEFAULT_MAX_TOKENS = 8192;
|
|
718
807
|
var AnthropicProvider = class {
|
|
719
808
|
apiKey;
|
|
@@ -1107,7 +1196,7 @@ var OWN_MESSAGE_MEMORY = 1e3;
|
|
|
1107
1196
|
var MESSAGE_INDEX_SIZE = 500;
|
|
1108
1197
|
var META_TTL_MS = 5 * 60 * 1e3;
|
|
1109
1198
|
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.";
|
|
1110
|
-
var JaibberAgent = class extends EventEmitter {
|
|
1199
|
+
var JaibberAgent = class _JaibberAgent extends EventEmitter {
|
|
1111
1200
|
config;
|
|
1112
1201
|
client;
|
|
1113
1202
|
ablyManager = null;
|
|
@@ -1121,6 +1210,7 @@ var JaibberAgent = class extends EventEmitter {
|
|
|
1121
1210
|
heartbeatTimer = null;
|
|
1122
1211
|
agentId = null;
|
|
1123
1212
|
agentRecord = null;
|
|
1213
|
+
keyIdentity = null;
|
|
1124
1214
|
/** In-memory conversation history per project. */
|
|
1125
1215
|
history = /* @__PURE__ */ new Map();
|
|
1126
1216
|
/** Recent messages per project (id → author/parent) for chain reconstruction. */
|
|
@@ -1144,6 +1234,23 @@ var JaibberAgent = class extends EventEmitter {
|
|
|
1144
1234
|
super();
|
|
1145
1235
|
this.config = config;
|
|
1146
1236
|
this.client = new JaibberClient(config.serverUrl);
|
|
1237
|
+
this.on("error", _JaibberAgent.defaultErrorListener);
|
|
1238
|
+
}
|
|
1239
|
+
/**
|
|
1240
|
+
* Default `"error"` listener, registered by the constructor: logs the error
|
|
1241
|
+
* and keeps the process alive. To handle errors yourself without the log,
|
|
1242
|
+
* remove it: `agent.off("error", JaibberAgent.defaultErrorListener)`.
|
|
1243
|
+
*/
|
|
1244
|
+
static defaultErrorListener = (err) => {
|
|
1245
|
+
console.error("[jaibber-agent] error:", err);
|
|
1246
|
+
};
|
|
1247
|
+
/** Emit `"error"` without ever throwing, even if every listener was removed. */
|
|
1248
|
+
emitError(err) {
|
|
1249
|
+
if (this.listenerCount("error") === 0) {
|
|
1250
|
+
_JaibberAgent.defaultErrorListener(err);
|
|
1251
|
+
return;
|
|
1252
|
+
}
|
|
1253
|
+
this.emit("error", err);
|
|
1147
1254
|
}
|
|
1148
1255
|
// ── Accessors ───────────────────────────────────────────────────────
|
|
1149
1256
|
/** The agent's server-side id (available after `connect()`). */
|
|
@@ -1154,6 +1261,10 @@ var JaibberAgent = class extends EventEmitter {
|
|
|
1154
1261
|
get record() {
|
|
1155
1262
|
return this.agentRecord;
|
|
1156
1263
|
}
|
|
1264
|
+
/** The key's agent identity from `GET /api/me` (API-key mode, on servers that have it). */
|
|
1265
|
+
get identity() {
|
|
1266
|
+
return this.keyIdentity;
|
|
1267
|
+
}
|
|
1157
1268
|
/** The underlying REST client (authenticated after `connect()`). */
|
|
1158
1269
|
get api() {
|
|
1159
1270
|
return this.client;
|
|
@@ -1179,6 +1290,7 @@ var JaibberAgent = class extends EventEmitter {
|
|
|
1179
1290
|
this.client.setApiKey(creds.apiKey);
|
|
1180
1291
|
this.agentId = this.config.agentId ?? null;
|
|
1181
1292
|
console.log(`[sdk] Authenticating with agent API key ${creds.apiKey.slice(0, 11)}\u2026`);
|
|
1293
|
+
await this.resolveKeyIdentity();
|
|
1182
1294
|
} else {
|
|
1183
1295
|
console.log(`[sdk] Logging in as "${creds.username}"...`);
|
|
1184
1296
|
await this.client.login(creds.username, creds.password);
|
|
@@ -1274,7 +1386,8 @@ var JaibberAgent = class extends EventEmitter {
|
|
|
1274
1386
|
presenceData,
|
|
1275
1387
|
(msg) => this.handleIncomingMessage(msg, project),
|
|
1276
1388
|
(data) => this.handleTaskEvent(data, project),
|
|
1277
|
-
(data) => this.handleControlEvent(data, project)
|
|
1389
|
+
(data) => this.handleControlEvent(data, project),
|
|
1390
|
+
(err) => this.emitError(err)
|
|
1278
1391
|
);
|
|
1279
1392
|
this.unsubscribers.push(unsub);
|
|
1280
1393
|
}
|
|
@@ -1293,6 +1406,43 @@ var JaibberAgent = class extends EventEmitter {
|
|
|
1293
1406
|
);
|
|
1294
1407
|
this.emit("connected", this.projects);
|
|
1295
1408
|
}
|
|
1409
|
+
/**
|
|
1410
|
+
* API-key mode: ask the server who the key is (`GET /api/me`) so the agent
|
|
1411
|
+
* id and name are known before Ably connects. Servers that predate the
|
|
1412
|
+
* endpoint answer 404; the id is then read from the Ably token's clientId
|
|
1413
|
+
* (`agent:{id}`) once connected, as in 0.4.0.
|
|
1414
|
+
*/
|
|
1415
|
+
async resolveKeyIdentity() {
|
|
1416
|
+
const me = await this.client.whoAmI();
|
|
1417
|
+
if (me === null) {
|
|
1418
|
+
console.warn(
|
|
1419
|
+
"[sdk] GET /api/me is not available on this server; the agent id will be read from the Ably token."
|
|
1420
|
+
);
|
|
1421
|
+
return;
|
|
1422
|
+
}
|
|
1423
|
+
if (me.type !== "agent") {
|
|
1424
|
+
throw new Error(
|
|
1425
|
+
`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\`.`
|
|
1426
|
+
);
|
|
1427
|
+
}
|
|
1428
|
+
if (this.agentId && this.agentId !== me.agentId) {
|
|
1429
|
+
console.warn(
|
|
1430
|
+
`[sdk] Configured agentId ${this.agentId} does not match the key's agent ${me.agentId}; using the key's.`
|
|
1431
|
+
);
|
|
1432
|
+
}
|
|
1433
|
+
this.agentId = me.agentId;
|
|
1434
|
+
this.config.agentId = me.agentId;
|
|
1435
|
+
this.keyIdentity = me;
|
|
1436
|
+
if (me.name && me.name.toLowerCase() !== this.config.agentName.toLowerCase()) {
|
|
1437
|
+
console.warn(
|
|
1438
|
+
`[sdk] agentName "${this.config.agentName}" differs from the key's agent "${me.name}"; using "${me.name}".`
|
|
1439
|
+
);
|
|
1440
|
+
this.config.agentName = me.name;
|
|
1441
|
+
}
|
|
1442
|
+
console.log(
|
|
1443
|
+
`[sdk] Authenticated as agent "${me.name}" (id ${me.agentId}${me.org ? `, org ${me.org.slug}` : ""})`
|
|
1444
|
+
);
|
|
1445
|
+
}
|
|
1296
1446
|
/** Stop heartbeats, leave presence, disconnect Ably. */
|
|
1297
1447
|
async disconnect() {
|
|
1298
1448
|
if (!this.connected) return;
|
|
@@ -1506,8 +1656,7 @@ var JaibberAgent = class extends EventEmitter {
|
|
|
1506
1656
|
try {
|
|
1507
1657
|
await this.respondToMessage(payload, project, depth, chain, executionMode, attachments);
|
|
1508
1658
|
} catch (err) {
|
|
1509
|
-
|
|
1510
|
-
this.emit("error", err);
|
|
1659
|
+
this.emitError(err);
|
|
1511
1660
|
} finally {
|
|
1512
1661
|
this.activeResponses.delete(payload.messageId);
|
|
1513
1662
|
}
|
|
@@ -1561,6 +1710,7 @@ var JaibberAgent = class extends EventEmitter {
|
|
|
1561
1710
|
},
|
|
1562
1711
|
ctx
|
|
1563
1712
|
);
|
|
1713
|
+
if (ctx.error !== void 0) this.emitError(ctx.error);
|
|
1564
1714
|
return;
|
|
1565
1715
|
}
|
|
1566
1716
|
if (this.provider) {
|
|
@@ -1569,6 +1719,10 @@ var JaibberAgent = class extends EventEmitter {
|
|
|
1569
1719
|
await ctx.stream(
|
|
1570
1720
|
() => this.provider.generate(payload.text, systemPrompt, conversationHistory)
|
|
1571
1721
|
);
|
|
1722
|
+
if (ctx.error !== void 0) {
|
|
1723
|
+
this.emitError(ctx.error);
|
|
1724
|
+
return;
|
|
1725
|
+
}
|
|
1572
1726
|
this.captureProviderSession(project.id);
|
|
1573
1727
|
return;
|
|
1574
1728
|
}
|
|
@@ -1617,9 +1771,8 @@ ${instructions}` : PLAN_MODE_PREFIX;
|
|
|
1617
1771
|
return;
|
|
1618
1772
|
const task = data.task;
|
|
1619
1773
|
if (task.status !== "submitted") return;
|
|
1620
|
-
const
|
|
1621
|
-
|
|
1622
|
-
if (!assignedById && !assignedByName) return;
|
|
1774
|
+
const mine = task.assignedAgentId ? !!this.agentId && task.assignedAgentId === this.agentId : !!task.assignedAgentName && task.assignedAgentName.toLowerCase() === this.config.agentName.toLowerCase();
|
|
1775
|
+
if (!mine) return;
|
|
1623
1776
|
console.log(
|
|
1624
1777
|
`[sdk] Picking up task: "${task.title}" (${task.id})`
|
|
1625
1778
|
);
|
|
@@ -1669,26 +1822,27 @@ ${task.description}` : `Task: ${task.title}`;
|
|
|
1669
1822
|
chunkBatchMs: this.config.chunkBatchMs ?? DEFAULT_CHUNK_BATCH_MS,
|
|
1670
1823
|
tracker: this.tracker
|
|
1671
1824
|
});
|
|
1672
|
-
|
|
1673
|
-
|
|
1674
|
-
|
|
1675
|
-
|
|
1676
|
-
|
|
1677
|
-
|
|
1678
|
-
|
|
1679
|
-
|
|
1680
|
-
this.
|
|
1681
|
-
await this.client.updateTask(task.id, { status: "completed" });
|
|
1682
|
-
} catch {
|
|
1825
|
+
await msgCtx.stream(
|
|
1826
|
+
() => this.provider.generate(
|
|
1827
|
+
taskPrompt,
|
|
1828
|
+
systemPrompt,
|
|
1829
|
+
conversationHistory
|
|
1830
|
+
)
|
|
1831
|
+
);
|
|
1832
|
+
if (msgCtx.error !== void 0) {
|
|
1833
|
+
this.emitError(msgCtx.error);
|
|
1683
1834
|
await this.client.updateTask(task.id, { status: "failed" });
|
|
1835
|
+
return;
|
|
1684
1836
|
}
|
|
1837
|
+
this.captureProviderSession(project.id);
|
|
1838
|
+
await this.client.updateTask(task.id, { status: "completed" });
|
|
1685
1839
|
return;
|
|
1686
1840
|
}
|
|
1687
1841
|
console.warn(
|
|
1688
1842
|
"[sdk] No task handler or provider configured. Task left as working."
|
|
1689
1843
|
);
|
|
1690
1844
|
} catch (err) {
|
|
1691
|
-
|
|
1845
|
+
this.emitError(err);
|
|
1692
1846
|
try {
|
|
1693
1847
|
await this.client.updateTask(task.id, { status: "failed" });
|
|
1694
1848
|
} catch {
|