@jaibber/sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,890 @@
1
+ // src/agent.ts
2
+ import { EventEmitter } from "events";
3
+ import { v4 as uuidv42 } from "uuid";
4
+
5
+ // src/client.ts
6
+ var JaibberClient = class {
7
+ serverUrl;
8
+ jwt = null;
9
+ userId = null;
10
+ username = null;
11
+ constructor(serverUrl) {
12
+ this.serverUrl = serverUrl.replace(/\/+$/, "");
13
+ }
14
+ // ── Auth ────────────────────────────────────────────────────────────
15
+ /** POST /api/auth/token — login with credentials, stores JWT. */
16
+ async login(username, password) {
17
+ const res = await fetch(`${this.serverUrl}/api/auth/token`, {
18
+ method: "POST",
19
+ headers: { "Content-Type": "application/json" },
20
+ body: JSON.stringify({ username, password })
21
+ });
22
+ if (!res.ok) {
23
+ const text = await res.text();
24
+ if (res.status === 401) {
25
+ throw new Error("Invalid credentials. Check username and password.");
26
+ }
27
+ throw new Error(`Login failed (${res.status}): ${text}`);
28
+ }
29
+ const data = await res.json();
30
+ this.jwt = data.token;
31
+ this.userId = data.userId;
32
+ this.username = data.username;
33
+ }
34
+ get isAuthenticated() {
35
+ return this.jwt !== null;
36
+ }
37
+ authHeaders() {
38
+ const h = { "Content-Type": "application/json" };
39
+ if (this.jwt) {
40
+ h["Authorization"] = `Bearer ${this.jwt}`;
41
+ }
42
+ return h;
43
+ }
44
+ // ── Projects ────────────────────────────────────────────────────────
45
+ /** GET /api/projects — list all projects user is member of. */
46
+ async listProjects() {
47
+ const res = await fetch(`${this.serverUrl}/api/projects`, {
48
+ headers: this.authHeaders()
49
+ });
50
+ if (!res.ok) {
51
+ const text = await res.text();
52
+ throw new Error(`Failed to list projects (${res.status}): ${text}`);
53
+ }
54
+ const data = await res.json();
55
+ return data.projects.map((p) => ({
56
+ id: p.id,
57
+ name: p.name,
58
+ description: p.description,
59
+ ablyChannelName: p.ablyChannelName,
60
+ role: p.role
61
+ }));
62
+ }
63
+ // ── Ably token ──────────────────────────────────────────────────────
64
+ /** POST /api/ably/token — get scoped Ably TokenRequest. */
65
+ async getAblyToken() {
66
+ const res = await fetch(`${this.serverUrl}/api/ably/token`, {
67
+ method: "POST",
68
+ headers: this.authHeaders()
69
+ });
70
+ if (!res.ok) {
71
+ const text = await res.text();
72
+ throw new Error(`Failed to get Ably token (${res.status}): ${text}`);
73
+ }
74
+ return res.json();
75
+ }
76
+ // ── Messages ────────────────────────────────────────────────────────
77
+ /**
78
+ * POST /api/projects/{id}/messages — persist a message (idempotent).
79
+ * Passing a client-generated `id` makes the server skip Ably re-publish.
80
+ */
81
+ async persistMessage(projectId, msg) {
82
+ const res = await fetch(
83
+ `${this.serverUrl}/api/projects/${projectId}/messages`,
84
+ {
85
+ method: "POST",
86
+ headers: this.authHeaders(),
87
+ body: JSON.stringify(msg)
88
+ }
89
+ );
90
+ if (!res.ok) {
91
+ const text = await res.text();
92
+ console.error(
93
+ `[sdk] Failed to persist message (${res.status}): ${text}`
94
+ );
95
+ }
96
+ }
97
+ /** GET /api/projects/{id}/messages — fetch recent messages. */
98
+ async fetchMessages(projectId, limit = 20) {
99
+ const res = await fetch(
100
+ `${this.serverUrl}/api/projects/${projectId}/messages?limit=${limit}`,
101
+ { headers: this.authHeaders() }
102
+ );
103
+ if (!res.ok) {
104
+ const text = await res.text();
105
+ throw new Error(`Failed to fetch messages (${res.status}): ${text}`);
106
+ }
107
+ const data = await res.json();
108
+ return data.data;
109
+ }
110
+ // ── Tasks ───────────────────────────────────────────────────────────
111
+ /** PATCH /api/tasks/{taskId} — update task fields. */
112
+ async updateTask(taskId, updates) {
113
+ const res = await fetch(`${this.serverUrl}/api/tasks/${taskId}`, {
114
+ method: "PATCH",
115
+ headers: this.authHeaders(),
116
+ body: JSON.stringify(updates)
117
+ });
118
+ if (!res.ok) {
119
+ const text = await res.text();
120
+ console.error(`[sdk] Failed to update task (${res.status}): ${text}`);
121
+ }
122
+ }
123
+ };
124
+
125
+ // src/ably-manager.ts
126
+ import Ably from "ably";
127
+ var AblyManager = class {
128
+ constructor(client, userId, username) {
129
+ this.client = client;
130
+ this.userId = userId;
131
+ this.username = username;
132
+ }
133
+ ably = null;
134
+ channels = /* @__PURE__ */ new Map();
135
+ presenceChannel = null;
136
+ /** Create Ably Realtime client with token auth callback. */
137
+ async connect() {
138
+ return new Promise((resolve, reject) => {
139
+ this.ably = new Ably.Realtime({
140
+ authCallback: async (_tokenParams, callback) => {
141
+ try {
142
+ const tokenRequest = await this.client.getAblyToken();
143
+ callback(null, tokenRequest);
144
+ } catch (err) {
145
+ callback(err, null);
146
+ }
147
+ },
148
+ clientId: this.userId
149
+ });
150
+ this.ably.connection.once("connected", () => {
151
+ console.log("[sdk] Ably connected");
152
+ resolve();
153
+ });
154
+ this.ably.connection.once("failed", (stateChange) => {
155
+ reject(
156
+ new Error(
157
+ `Ably connection failed: ${stateChange?.reason?.message ?? "unknown"}`
158
+ )
159
+ );
160
+ });
161
+ });
162
+ }
163
+ /** Enter global presence channel (jaibber:presence). */
164
+ async enterGlobalPresence(projectIds) {
165
+ if (!this.ably) throw new Error("Ably not connected");
166
+ this.presenceChannel = this.ably.channels.get("jaibber:presence");
167
+ await this.presenceChannel.presence.enter({
168
+ userId: this.userId,
169
+ username: this.username,
170
+ projectIds
171
+ });
172
+ }
173
+ /**
174
+ * Subscribe to a project channel and enter per-project presence.
175
+ * Returns an unsubscribe function.
176
+ */
177
+ async subscribeToProject(project, presenceData, onMessage, onTask) {
178
+ if (!this.ably) throw new Error("Ably not connected");
179
+ const channel = this.ably.channels.get(project.ablyChannelName);
180
+ this.channels.set(project.ablyChannelName, channel);
181
+ await channel.presence.enter(presenceData);
182
+ const messageHandler = (msg) => {
183
+ if (!msg.data) return;
184
+ const payload = msg.data;
185
+ onMessage(payload);
186
+ };
187
+ const taskHandler = (msg) => {
188
+ if (!msg.data) return;
189
+ onTask(msg.data);
190
+ };
191
+ channel.subscribe("message", messageHandler);
192
+ channel.subscribe("task", taskHandler);
193
+ return () => {
194
+ channel.unsubscribe("message", messageHandler);
195
+ channel.unsubscribe("task", taskHandler);
196
+ };
197
+ }
198
+ /** Publish a message on a project channel. */
199
+ async publish(channelName, eventName, data) {
200
+ const channel = this.channels.get(channelName);
201
+ if (!channel) {
202
+ throw new Error(`Not subscribed to channel: ${channelName}`);
203
+ }
204
+ await channel.publish(eventName, data);
205
+ }
206
+ /** Get the Ably connection ID (used for skip logic). */
207
+ get connectionId() {
208
+ return this.ably?.connection.id;
209
+ }
210
+ /** Leave presence on all channels and close the connection. */
211
+ async disconnect() {
212
+ for (const channel of this.channels.values()) {
213
+ try {
214
+ await channel.presence.leave();
215
+ } catch {
216
+ }
217
+ }
218
+ if (this.presenceChannel) {
219
+ try {
220
+ await this.presenceChannel.presence.leave();
221
+ } catch {
222
+ }
223
+ }
224
+ if (this.ably) {
225
+ this.ably.close();
226
+ this.ably = null;
227
+ }
228
+ this.channels.clear();
229
+ this.presenceChannel = null;
230
+ console.log("[sdk] Ably disconnected");
231
+ }
232
+ };
233
+
234
+ // src/context.ts
235
+ import { v4 as uuidv4 } from "uuid";
236
+ var MessageContext = class {
237
+ /** Formatted conversation history for LLM prompts. */
238
+ conversationHistory;
239
+ /** The project ID this message was received on. */
240
+ projectId;
241
+ responseId;
242
+ ablyManager;
243
+ channelName;
244
+ userId;
245
+ agentName;
246
+ client;
247
+ responseDepth;
248
+ respondingChain;
249
+ chunkBatchMs;
250
+ constructor(opts) {
251
+ this.projectId = opts.projectId;
252
+ this.channelName = opts.channelName;
253
+ this.conversationHistory = opts.conversationHistory;
254
+ this.ablyManager = opts.ablyManager;
255
+ this.userId = opts.userId;
256
+ this.agentName = opts.agentName;
257
+ this.client = opts.client;
258
+ this.responseDepth = opts.incomingDepth + 1;
259
+ this.respondingChain = [
260
+ ...opts.incomingChain,
261
+ opts.agentName.toLowerCase()
262
+ ];
263
+ this.chunkBatchMs = opts.chunkBatchMs;
264
+ this.responseId = uuidv4();
265
+ }
266
+ /** One-shot reply: publishes typing → response in sequence. */
267
+ async reply(text) {
268
+ await this.publishTyping();
269
+ await this.publishResponse(text);
270
+ this.persistAsync(text, "response");
271
+ }
272
+ /**
273
+ * Streaming reply: consumes an async generator, batches chunks to Ably
274
+ * every chunkBatchMs (default 200ms), then publishes the final response.
275
+ *
276
+ * Mirrors useAbly.ts lines 86-102 chunk batching pattern.
277
+ */
278
+ async stream(generator) {
279
+ await this.publishTyping();
280
+ let fullText = "";
281
+ let chunkBuffer = "";
282
+ let flushTimer = null;
283
+ const flushChunks = async () => {
284
+ if (!chunkBuffer) return;
285
+ const text = chunkBuffer;
286
+ chunkBuffer = "";
287
+ await this.publishChunk(text);
288
+ };
289
+ try {
290
+ for await (const chunk of generator()) {
291
+ fullText += chunk;
292
+ chunkBuffer += chunk;
293
+ if (!flushTimer) {
294
+ flushTimer = setTimeout(async () => {
295
+ flushTimer = null;
296
+ await flushChunks();
297
+ }, this.chunkBatchMs);
298
+ }
299
+ }
300
+ if (flushTimer) clearTimeout(flushTimer);
301
+ await flushChunks();
302
+ await this.publishResponse(fullText);
303
+ this.persistAsync(fullText, "response");
304
+ } catch (err) {
305
+ if (flushTimer) clearTimeout(flushTimer);
306
+ const errText = `Agent error: ${err instanceof Error ? err.message : String(err)}`;
307
+ await this.publishError(errText);
308
+ this.persistAsync(errText, "error");
309
+ }
310
+ }
311
+ // ── Internal publish helpers ────────────────────────────────────────
312
+ async publishTyping() {
313
+ await this.ablyManager.publish(this.channelName, "message", {
314
+ from: this.userId,
315
+ fromUsername: this.agentName,
316
+ projectId: this.projectId,
317
+ text: "",
318
+ messageId: uuidv4(),
319
+ responseId: this.responseId,
320
+ type: "typing",
321
+ agentName: this.agentName
322
+ });
323
+ }
324
+ async publishChunk(text) {
325
+ await this.ablyManager.publish(this.channelName, "message", {
326
+ from: this.userId,
327
+ fromUsername: this.agentName,
328
+ projectId: this.projectId,
329
+ text,
330
+ messageId: this.responseId,
331
+ type: "chunk",
332
+ agentName: this.agentName
333
+ });
334
+ }
335
+ async publishResponse(text) {
336
+ await this.ablyManager.publish(this.channelName, "message", {
337
+ from: this.userId,
338
+ fromUsername: this.agentName,
339
+ projectId: this.projectId,
340
+ text,
341
+ messageId: this.responseId,
342
+ type: "response",
343
+ agentName: this.agentName,
344
+ isAgentMessage: true,
345
+ responseDepth: this.responseDepth,
346
+ respondingChain: this.respondingChain
347
+ });
348
+ }
349
+ async publishError(text) {
350
+ await this.ablyManager.publish(this.channelName, "message", {
351
+ from: this.userId,
352
+ fromUsername: this.agentName,
353
+ projectId: this.projectId,
354
+ text,
355
+ messageId: this.responseId,
356
+ type: "error",
357
+ agentName: this.agentName
358
+ });
359
+ }
360
+ /** Fire-and-forget persist to server. */
361
+ persistAsync(text, type) {
362
+ this.client.persistMessage(this.projectId, {
363
+ id: this.responseId,
364
+ senderType: "agent",
365
+ senderName: this.agentName,
366
+ type,
367
+ text
368
+ }).catch((err) => {
369
+ console.error("[sdk] Failed to persist message:", err);
370
+ });
371
+ }
372
+ };
373
+ var TaskContext = class {
374
+ task;
375
+ projectId;
376
+ conversationHistory;
377
+ ablyManager;
378
+ channelName;
379
+ userId;
380
+ agentName;
381
+ client;
382
+ constructor(opts) {
383
+ this.task = opts.task;
384
+ this.projectId = opts.projectId;
385
+ this.channelName = opts.channelName;
386
+ this.conversationHistory = opts.conversationHistory;
387
+ this.ablyManager = opts.ablyManager;
388
+ this.userId = opts.userId;
389
+ this.agentName = opts.agentName;
390
+ this.client = opts.client;
391
+ }
392
+ /** Mark task as completed, optionally publishing a response message. */
393
+ async complete(resultText) {
394
+ await this.client.updateTask(this.task.id, { status: "completed" });
395
+ if (resultText) {
396
+ await this.sendMessage(resultText);
397
+ }
398
+ }
399
+ /** Mark task as failed, optionally publishing an error message. */
400
+ async fail(errorText) {
401
+ await this.client.updateTask(this.task.id, { status: "failed" });
402
+ if (errorText) {
403
+ const msgId = uuidv4();
404
+ await this.ablyManager.publish(this.channelName, "message", {
405
+ from: this.userId,
406
+ fromUsername: this.agentName,
407
+ projectId: this.projectId,
408
+ text: errorText,
409
+ messageId: msgId,
410
+ type: "error",
411
+ agentName: this.agentName
412
+ });
413
+ this.client.persistMessage(this.projectId, {
414
+ id: msgId,
415
+ senderType: "agent",
416
+ senderName: this.agentName,
417
+ type: "error",
418
+ text: errorText
419
+ }).catch((err) => console.error("[sdk] Failed to persist:", err));
420
+ }
421
+ }
422
+ /** Send a chat message (for progress updates). */
423
+ async sendMessage(text) {
424
+ const msgId = uuidv4();
425
+ await this.ablyManager.publish(this.channelName, "message", {
426
+ from: this.userId,
427
+ fromUsername: this.agentName,
428
+ projectId: this.projectId,
429
+ text,
430
+ messageId: msgId,
431
+ type: "response",
432
+ agentName: this.agentName,
433
+ isAgentMessage: true
434
+ });
435
+ this.client.persistMessage(this.projectId, {
436
+ id: msgId,
437
+ senderType: "agent",
438
+ senderName: this.agentName,
439
+ type: "response",
440
+ text
441
+ }).catch((err) => console.error("[sdk] Failed to persist:", err));
442
+ }
443
+ };
444
+
445
+ // src/mentions.ts
446
+ function mentionsAgent(text, agentName) {
447
+ const pattern = new RegExp(`@${escapeRegex(agentName)}(?!\\w)`, "i");
448
+ return pattern.test(text);
449
+ }
450
+ function escapeRegex(s) {
451
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
452
+ }
453
+
454
+ // src/providers/anthropic.ts
455
+ var ANTHROPIC_API_URL = "https://api.anthropic.com/v1/messages";
456
+ var ANTHROPIC_VERSION = "2024-10-22";
457
+ var DEFAULT_MODEL = "claude-sonnet-4-20250514";
458
+ var DEFAULT_MAX_TOKENS = 8192;
459
+ var AnthropicProvider = class {
460
+ apiKey;
461
+ model;
462
+ maxTokens;
463
+ constructor(options) {
464
+ this.apiKey = options.apiKey;
465
+ this.model = options.model ?? DEFAULT_MODEL;
466
+ this.maxTokens = options.maxTokens ?? DEFAULT_MAX_TOKENS;
467
+ }
468
+ async *generate(prompt, systemPrompt, conversationContext) {
469
+ let fullText = "";
470
+ if (conversationContext) {
471
+ fullText += 'Below is the recent conversation history for context. Respond ONLY to the final user message. Be conversational and concise \u2014 reply directly to the user as a chat participant. Do NOT narrate your thought process, planning steps, or internal reasoning. Do NOT describe actions you would take (e.g. "I should...", "Let me...", "I will..."). Just answer.\n\n';
472
+ fullText += conversationContext;
473
+ fullText += "\n\n---\n\n";
474
+ }
475
+ fullText += prompt;
476
+ const body = {
477
+ model: this.model,
478
+ max_tokens: this.maxTokens,
479
+ stream: true,
480
+ messages: [
481
+ {
482
+ role: "user",
483
+ content: fullText
484
+ }
485
+ ]
486
+ };
487
+ if (systemPrompt) {
488
+ body.system = systemPrompt;
489
+ }
490
+ const response = await fetch(ANTHROPIC_API_URL, {
491
+ method: "POST",
492
+ headers: {
493
+ "x-api-key": this.apiKey,
494
+ "anthropic-version": ANTHROPIC_VERSION,
495
+ "content-type": "application/json"
496
+ },
497
+ body: JSON.stringify(body)
498
+ });
499
+ if (!response.ok) {
500
+ const text = await response.text();
501
+ const status = response.status;
502
+ if (status === 401) {
503
+ throw new Error(
504
+ "Invalid Anthropic API key. Check your API key."
505
+ );
506
+ } else if (status === 429) {
507
+ throw new Error(
508
+ "Anthropic API rate limit exceeded. Please wait and try again."
509
+ );
510
+ } else if (status === 400) {
511
+ try {
512
+ const json = JSON.parse(text);
513
+ const msg = json?.error?.message;
514
+ if (msg) throw new Error(`Anthropic API error: ${msg}`);
515
+ } catch (e) {
516
+ if (e instanceof Error && e.message.startsWith("Anthropic")) throw e;
517
+ }
518
+ throw new Error(`Anthropic API returned ${status}: ${text}`);
519
+ } else {
520
+ throw new Error(`Anthropic API returned ${status}: ${text}`);
521
+ }
522
+ }
523
+ if (!response.body) {
524
+ throw new Error("Anthropic API returned no response body");
525
+ }
526
+ const reader = response.body.getReader();
527
+ const decoder = new TextDecoder();
528
+ let buffer = "";
529
+ try {
530
+ while (true) {
531
+ const { done, value } = await reader.read();
532
+ if (done) break;
533
+ buffer += decoder.decode(value, { stream: true });
534
+ while (true) {
535
+ const newlinePos = buffer.indexOf("\n");
536
+ if (newlinePos === -1) break;
537
+ const line = buffer.slice(0, newlinePos).replace(/\r$/, "");
538
+ buffer = buffer.slice(newlinePos + 1);
539
+ if (!line || !line.startsWith("data: ")) continue;
540
+ const data = line.slice(6).trim();
541
+ if (data === "[DONE]") return;
542
+ try {
543
+ const json = JSON.parse(data);
544
+ const eventType = json?.type;
545
+ if (eventType === "content_block_delta") {
546
+ const text = json?.delta?.text;
547
+ if (text) yield text;
548
+ } else if (eventType === "message_stop") {
549
+ return;
550
+ } else if (eventType === "error") {
551
+ const errMsg = json?.error?.message ?? "Unknown Anthropic API error";
552
+ throw new Error(errMsg);
553
+ }
554
+ } catch (e) {
555
+ if (e instanceof Error && e.message !== "Unknown Anthropic API error") {
556
+ if (e instanceof SyntaxError) continue;
557
+ throw e;
558
+ }
559
+ throw e;
560
+ }
561
+ }
562
+ }
563
+ } finally {
564
+ reader.releaseLock();
565
+ }
566
+ }
567
+ };
568
+
569
+ // src/agent.ts
570
+ var DEFAULT_MAX_DEPTH = 3;
571
+ var DEFAULT_CHUNK_BATCH_MS = 200;
572
+ var DEFAULT_CONTEXT_WINDOW = 20;
573
+ var JaibberAgent = class extends EventEmitter {
574
+ config;
575
+ client;
576
+ ablyManager = null;
577
+ messageHandler = null;
578
+ taskHandler = null;
579
+ provider = null;
580
+ connected = false;
581
+ projects = [];
582
+ unsubscribers = [];
583
+ /** In-memory conversation history per project. */
584
+ history = /* @__PURE__ */ new Map();
585
+ /** Track in-flight responses to prevent double-handling. */
586
+ activeResponses = /* @__PURE__ */ new Set();
587
+ constructor(config) {
588
+ super();
589
+ this.config = config;
590
+ this.client = new JaibberClient(config.serverUrl);
591
+ }
592
+ // ── Lifecycle ───────────────────────────────────────────────────────
593
+ /** Authenticate, connect Ably, subscribe to project channels. */
594
+ async connect() {
595
+ if (this.connected) throw new Error("Already connected");
596
+ const { username, password } = this.config.credentials;
597
+ console.log(`[sdk] Logging in as "${username}"...`);
598
+ await this.client.login(username, password);
599
+ const userId = this.client.userId;
600
+ const displayName = this.client.username;
601
+ const allProjects = await this.client.listProjects();
602
+ this.projects = this.config.projectIds ? allProjects.filter((p) => this.config.projectIds.includes(p.id)) : allProjects;
603
+ if (this.projects.length === 0) {
604
+ throw new Error(
605
+ "No projects found. Ensure the agent account is a member of at least one project."
606
+ );
607
+ }
608
+ console.log(
609
+ `[sdk] Found ${this.projects.length} project(s): ${this.projects.map((p) => p.name).join(", ")}`
610
+ );
611
+ this.ablyManager = new AblyManager(this.client, userId, displayName);
612
+ await this.ablyManager.connect();
613
+ await this.ablyManager.enterGlobalPresence(
614
+ this.projects.map((p) => p.id)
615
+ );
616
+ for (const project of this.projects) {
617
+ const presenceData = {
618
+ userId,
619
+ username: this.config.agentName,
620
+ isAgent: true,
621
+ agentName: this.config.agentName,
622
+ agentInstructions: this.config.agentInstructions,
623
+ agents: [
624
+ {
625
+ agentName: this.config.agentName,
626
+ agentInstructions: this.config.agentInstructions
627
+ }
628
+ ],
629
+ machineName: this.config.machineName
630
+ };
631
+ await this.loadHistory(project.id);
632
+ const unsub = await this.ablyManager.subscribeToProject(
633
+ project,
634
+ presenceData,
635
+ (msg) => this.handleIncomingMessage(msg, project),
636
+ (data) => this.handleTaskEvent(data, project)
637
+ );
638
+ this.unsubscribers.push(unsub);
639
+ }
640
+ this.connected = true;
641
+ console.log(`[sdk] Agent "${this.config.agentName}" connected and listening`);
642
+ this.emit("connected", this.projects);
643
+ }
644
+ /** Leave presence, disconnect Ably. */
645
+ async disconnect() {
646
+ if (!this.connected) return;
647
+ for (const unsub of this.unsubscribers) {
648
+ unsub();
649
+ }
650
+ this.unsubscribers = [];
651
+ if (this.ablyManager) {
652
+ await this.ablyManager.disconnect();
653
+ this.ablyManager = null;
654
+ }
655
+ this.connected = false;
656
+ this.emit("disconnected");
657
+ }
658
+ // ── Handler registration ────────────────────────────────────────────
659
+ /** Register a handler for incoming messages. */
660
+ onMessage(handler) {
661
+ this.messageHandler = handler;
662
+ }
663
+ /** Register a handler for assigned tasks. */
664
+ onTask(handler) {
665
+ this.taskHandler = handler;
666
+ }
667
+ /** Use a built-in LLM provider. */
668
+ useProvider(name, options) {
669
+ if (name === "anthropic") {
670
+ this.provider = new AnthropicProvider(options);
671
+ }
672
+ }
673
+ // ── Message handling ────────────────────────────────────────────────
674
+ async handleIncomingMessage(payload, project) {
675
+ const userId = this.client.userId;
676
+ if (payload.from === userId) return;
677
+ if (payload.isTaskNotification) return;
678
+ if (payload.type !== "message" && payload.type !== "response") return;
679
+ this.addToHistory(project.id, {
680
+ sender: payload.isAgentMessage ? "agent" : "user",
681
+ senderName: payload.fromUsername,
682
+ text: payload.text
683
+ });
684
+ const depth = payload.responseDepth ?? 0;
685
+ const chain = payload.respondingChain ?? [];
686
+ if (!this.shouldRespond(payload.text, depth, chain)) return;
687
+ if (this.activeResponses.has(payload.messageId)) return;
688
+ this.activeResponses.add(payload.messageId);
689
+ try {
690
+ await this.respondToMessage(payload, project, depth, chain);
691
+ } catch (err) {
692
+ console.error("[sdk] Error responding to message:", err);
693
+ this.emit("error", err);
694
+ } finally {
695
+ this.activeResponses.delete(payload.messageId);
696
+ }
697
+ }
698
+ /**
699
+ * Should this agent respond to the message?
700
+ * Mirrors useAbly.ts shouldAgentRespond() logic.
701
+ */
702
+ shouldRespond(text, depth, chain) {
703
+ const maxDepth = this.config.maxResponseDepth ?? DEFAULT_MAX_DEPTH;
704
+ if (depth >= maxDepth) return false;
705
+ if (chain.includes(this.config.agentName.toLowerCase())) return false;
706
+ if (!mentionsAgent(text, this.config.agentName)) return false;
707
+ return true;
708
+ }
709
+ async respondToMessage(payload, project, incomingDepth, incomingChain) {
710
+ const userId = this.client.userId;
711
+ const conversationHistory = this.getFormattedHistory(project.id);
712
+ const ctx = new MessageContext({
713
+ projectId: project.id,
714
+ channelName: project.ablyChannelName,
715
+ conversationHistory,
716
+ ablyManager: this.ablyManager,
717
+ userId,
718
+ agentName: this.config.agentName,
719
+ client: this.client,
720
+ incomingDepth,
721
+ incomingChain,
722
+ chunkBatchMs: this.config.chunkBatchMs ?? DEFAULT_CHUNK_BATCH_MS
723
+ });
724
+ if (this.messageHandler) {
725
+ await this.messageHandler(
726
+ {
727
+ id: payload.messageId,
728
+ projectId: project.id,
729
+ from: payload.from,
730
+ fromUsername: payload.fromUsername,
731
+ text: payload.text,
732
+ type: payload.type,
733
+ responseDepth: incomingDepth,
734
+ respondingChain: incomingChain,
735
+ executionMode: payload.executionMode,
736
+ isAgentMessage: payload.isAgentMessage,
737
+ attachments: payload.attachments
738
+ },
739
+ ctx
740
+ );
741
+ return;
742
+ }
743
+ if (this.provider) {
744
+ const systemPrompt = this.config.agentInstructions ?? "";
745
+ await ctx.stream(
746
+ () => this.provider.generate(payload.text, systemPrompt, conversationHistory)
747
+ );
748
+ return;
749
+ }
750
+ console.warn(
751
+ "[sdk] No message handler or provider configured. Ignoring message."
752
+ );
753
+ }
754
+ // ── Task handling ───────────────────────────────────────────────────
755
+ async handleTaskEvent(data, project) {
756
+ if (data.type !== "task-created" && data.type !== "task-updated")
757
+ return;
758
+ const task = data.task;
759
+ if (task.status !== "submitted") return;
760
+ if (!task.assignedAgentName || task.assignedAgentName.toLowerCase() !== this.config.agentName.toLowerCase())
761
+ return;
762
+ console.log(
763
+ `[sdk] Picking up task: "${task.title}" (${task.id})`
764
+ );
765
+ try {
766
+ await this.client.updateTask(task.id, { status: "working" });
767
+ const userId = this.client.userId;
768
+ const announceMsgId = uuidv42();
769
+ await this.ablyManager.publish(
770
+ project.ablyChannelName,
771
+ "message",
772
+ {
773
+ from: userId,
774
+ fromUsername: this.config.agentName,
775
+ projectId: project.id,
776
+ text: `Picking up task: **${task.title}**`,
777
+ messageId: announceMsgId,
778
+ type: "message",
779
+ agentName: this.config.agentName,
780
+ isAgentMessage: true,
781
+ isTaskNotification: true
782
+ }
783
+ );
784
+ const conversationHistory = this.getFormattedHistory(project.id);
785
+ const ctx = new TaskContext({
786
+ task,
787
+ projectId: project.id,
788
+ channelName: project.ablyChannelName,
789
+ conversationHistory,
790
+ ablyManager: this.ablyManager,
791
+ userId,
792
+ agentName: this.config.agentName,
793
+ client: this.client
794
+ });
795
+ if (this.taskHandler) {
796
+ await this.taskHandler(task, ctx);
797
+ return;
798
+ }
799
+ if (this.provider) {
800
+ const taskPrompt = task.description ? `Task: ${task.title}
801
+
802
+ ${task.description}` : `Task: ${task.title}`;
803
+ const systemPrompt = this.config.agentInstructions ?? "";
804
+ const msgCtx = new MessageContext({
805
+ projectId: project.id,
806
+ channelName: project.ablyChannelName,
807
+ conversationHistory,
808
+ ablyManager: this.ablyManager,
809
+ userId,
810
+ agentName: this.config.agentName,
811
+ client: this.client,
812
+ incomingDepth: 0,
813
+ incomingChain: [],
814
+ chunkBatchMs: this.config.chunkBatchMs ?? DEFAULT_CHUNK_BATCH_MS
815
+ });
816
+ try {
817
+ await msgCtx.stream(
818
+ () => this.provider.generate(
819
+ taskPrompt,
820
+ systemPrompt,
821
+ conversationHistory
822
+ )
823
+ );
824
+ await this.client.updateTask(task.id, { status: "completed" });
825
+ } catch {
826
+ await this.client.updateTask(task.id, { status: "failed" });
827
+ }
828
+ return;
829
+ }
830
+ console.warn(
831
+ "[sdk] No task handler or provider configured. Task left as working."
832
+ );
833
+ } catch (err) {
834
+ console.error("[sdk] Error handling task:", err);
835
+ try {
836
+ await this.client.updateTask(task.id, { status: "failed" });
837
+ } catch {
838
+ }
839
+ }
840
+ }
841
+ // ── Conversation history ────────────────────────────────────────────
842
+ async loadHistory(projectId) {
843
+ const contextSize = this.config.contextWindowSize ?? DEFAULT_CONTEXT_WINDOW;
844
+ try {
845
+ const messages = await this.client.fetchMessages(
846
+ projectId,
847
+ contextSize
848
+ );
849
+ const entries = messages.reverse().map((m) => ({
850
+ sender: m.senderType === "user" ? "user" : "agent",
851
+ senderName: m.senderName,
852
+ text: m.text
853
+ }));
854
+ this.history.set(projectId, entries);
855
+ } catch (err) {
856
+ console.error(
857
+ `[sdk] Failed to load history for project ${projectId}:`,
858
+ err
859
+ );
860
+ this.history.set(projectId, []);
861
+ }
862
+ }
863
+ addToHistory(projectId, entry) {
864
+ const contextSize = this.config.contextWindowSize ?? DEFAULT_CONTEXT_WINDOW;
865
+ const entries = this.history.get(projectId) ?? [];
866
+ entries.push(entry);
867
+ if (entries.length > contextSize) {
868
+ entries.splice(0, entries.length - contextSize);
869
+ }
870
+ this.history.set(projectId, entries);
871
+ }
872
+ /**
873
+ * Format conversation history for LLM context.
874
+ * Matches useAbly.ts lines 77-84 format.
875
+ */
876
+ getFormattedHistory(projectId) {
877
+ const entries = this.history.get(projectId) ?? [];
878
+ return entries.map((e) => {
879
+ const role = e.sender === "user" ? "User" : `Assistant (${e.senderName || "Agent"})`;
880
+ return `${role}: ${e.text}`;
881
+ }).join("\n\n");
882
+ }
883
+ };
884
+ export {
885
+ AnthropicProvider,
886
+ JaibberAgent,
887
+ MessageContext,
888
+ TaskContext
889
+ };
890
+ //# sourceMappingURL=index.js.map