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