@jaibber/sdk 0.3.8 → 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
@@ -35,27 +35,71 @@ __export(index_exports, {
35
35
  ClaudeCLIProvider: () => ClaudeCLIProvider,
36
36
  GoogleProvider: () => GoogleProvider,
37
37
  JaibberAgent: () => JaibberAgent,
38
+ JaibberClient: () => JaibberClient,
38
39
  MessageContext: () => MessageContext,
39
40
  OpenAIProvider: () => OpenAIProvider,
40
41
  TaskContext: () => TaskContext,
41
- getTemplate: () => getTemplate
42
+ getTemplate: () => getTemplate,
43
+ mentionsAgent: () => mentionsAgent,
44
+ parseMentions: () => parseMentions
42
45
  });
43
46
  module.exports = __toCommonJS(index_exports);
44
47
 
45
48
  // src/agent.ts
46
49
  var import_events = require("events");
47
- var import_uuid2 = require("uuid");
48
50
 
49
51
  // src/client.ts
52
+ var API_KEY_PREFIX = "jb_";
53
+ async function readError(res) {
54
+ const text = await res.text().catch(() => "");
55
+ try {
56
+ const json = JSON.parse(text);
57
+ const err = json?.error;
58
+ if (typeof err === "string") return err;
59
+ if (err && typeof err === "object") {
60
+ const e = err;
61
+ if (typeof e.message === "string") {
62
+ return e.code ? `${e.code}: ${e.message}` : e.message;
63
+ }
64
+ }
65
+ } catch {
66
+ }
67
+ return text || res.statusText || "Unknown error";
68
+ }
69
+ function mapProject(p, fallbackRole = "member") {
70
+ return {
71
+ id: p.id,
72
+ name: p.name,
73
+ description: p.description ?? null,
74
+ orgId: p.orgId ?? null,
75
+ ablyChannelName: p.ablyChannelName,
76
+ role: p.role ?? fallbackRole
77
+ };
78
+ }
50
79
  var JaibberClient = class {
51
80
  serverUrl;
52
81
  jwt = null;
82
+ apiKey = null;
53
83
  userId = null;
54
84
  username = null;
55
- constructor(serverUrl) {
85
+ constructor(serverUrl, opts) {
56
86
  this.serverUrl = serverUrl.replace(/\/+$/, "");
87
+ if (opts?.apiKey) this.setApiKey(opts.apiKey);
88
+ if (opts?.token) this.jwt = opts.token;
57
89
  }
58
90
  // ── Auth ────────────────────────────────────────────────────────────
91
+ /** Use an API key (`jb_…`) for all requests. An agent-bound key authenticates AS that agent. */
92
+ setApiKey(apiKey) {
93
+ const key = apiKey.trim();
94
+ if (!key.startsWith(API_KEY_PREFIX)) {
95
+ throw new Error(`Invalid Jaibber API key: expected it to start with "${API_KEY_PREFIX}".`);
96
+ }
97
+ this.apiKey = key;
98
+ }
99
+ /** Use an existing session JWT for all requests. */
100
+ setToken(token) {
101
+ this.jwt = token;
102
+ }
59
103
  /** POST /api/auth/register — create a new account, stores JWT. */
60
104
  async register(username, password) {
61
105
  const res = await fetch(`${this.serverUrl}/api/auth/register`, {
@@ -64,7 +108,7 @@ var JaibberClient = class {
64
108
  body: JSON.stringify({ username, password })
65
109
  });
66
110
  if (!res.ok) {
67
- const text = await res.text();
111
+ const text = await readError(res);
68
112
  if (res.status === 409) {
69
113
  throw new Error(`Username "${username}" is already taken.`);
70
114
  }
@@ -83,7 +127,7 @@ var JaibberClient = class {
83
127
  body: JSON.stringify({ username, password })
84
128
  });
85
129
  if (!res.ok) {
86
- const text = await res.text();
130
+ const text = await readError(res);
87
131
  if (res.status === 401) {
88
132
  throw new Error("Invalid credentials. Check username and password.");
89
133
  }
@@ -95,169 +139,300 @@ var JaibberClient = class {
95
139
  this.username = data.username;
96
140
  }
97
141
  get isAuthenticated() {
98
- return this.jwt !== null;
142
+ return this.jwt !== null || this.apiKey !== null;
143
+ }
144
+ /** Which credential requests will carry. */
145
+ get authMode() {
146
+ if (this.apiKey) return "apiKey";
147
+ if (this.jwt) return "session";
148
+ return "none";
99
149
  }
100
150
  authHeaders() {
101
151
  const h = { "Content-Type": "application/json" };
102
- if (this.jwt) {
152
+ if (this.apiKey) {
153
+ h["X-API-Key"] = this.apiKey;
154
+ } else if (this.jwt) {
103
155
  h["Authorization"] = `Bearer ${this.jwt}`;
104
156
  }
105
157
  return h;
106
158
  }
159
+ /** Authenticated fetch with uniform error reporting. */
160
+ async request(method, path, body, what) {
161
+ const res = await fetch(`${this.serverUrl}${path}`, {
162
+ method,
163
+ headers: this.authHeaders(),
164
+ ...body !== void 0 ? { body: JSON.stringify(body) } : {}
165
+ });
166
+ if (!res.ok) {
167
+ const text = await readError(res);
168
+ throw new Error(`${what ?? `${method} ${path}`} failed (${res.status}): ${text}`);
169
+ }
170
+ return res;
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
+ }
107
188
  // ── Projects ────────────────────────────────────────────────────────
108
- /** GET /api/projects — list all projects user is member of. */
189
+ /**
190
+ * GET /api/projects — with a session: projects the user is a member of
191
+ * (plus org-admin-visible ones with role "org-admin"); with an agent key:
192
+ * the agent's assigned projects.
193
+ */
109
194
  async listProjects() {
110
- const res = await fetch(`${this.serverUrl}/api/projects`, {
111
- headers: this.authHeaders()
195
+ const res = await this.request("GET", "/api/projects", void 0, "Failed to list projects");
196
+ const json = await res.json();
197
+ const rows = json.projects ?? json.data ?? [];
198
+ return rows.map((p) => mapProject(p, this.apiKey ? "agent" : "member"));
199
+ }
200
+ /** POST /api/projects — create a new project (session only), returns it. */
201
+ async createProject(name, description, orgId) {
202
+ const res = await this.request(
203
+ "POST",
204
+ "/api/projects",
205
+ { name, description, ...orgId ? { orgId } : {} },
206
+ "Failed to create project"
207
+ );
208
+ const json = await res.json();
209
+ const p = json.project ?? json.data;
210
+ if (!p) throw new Error("Failed to create project: malformed response");
211
+ return mapProject(p, "admin");
212
+ }
213
+ // ── Agents (/api/me/agents) ─────────────────────────────────────────
214
+ /**
215
+ * POST /api/me/agents — idempotent upsert of an agent hosted by the
216
+ * logged-in user, keyed by (org, lower(name)). Session only.
217
+ */
218
+ async ensureAgent(input) {
219
+ const body = { name: input.name, kind: input.kind };
220
+ if (input.instructions !== void 0) body.instructions = input.instructions;
221
+ if (input.provider) body.provider = input.provider;
222
+ if (input.machineName) body.machineName = input.machineName;
223
+ if (input.projectId) body.projectId = input.projectId;
224
+ if (input.orgId) body.orgId = input.orgId;
225
+ const res = await fetch(`${this.serverUrl}/api/me/agents`, {
226
+ method: "POST",
227
+ headers: this.authHeaders(),
228
+ body: JSON.stringify(body)
112
229
  });
113
230
  if (!res.ok) {
114
- const text = await res.text();
115
- throw new Error(`Failed to list projects (${res.status}): ${text}`);
231
+ const text = await readError(res);
232
+ if (res.status === 404) {
233
+ throw new Error(
234
+ "This Jaibber server does not support agent registration (POST /api/me/agents \u2192 404). Upgrade the server, or use @jaibber/sdk 0.3.x."
235
+ );
236
+ }
237
+ throw new Error(`Failed to register agent (${res.status}): ${text}`);
116
238
  }
117
- const data = await res.json();
118
- return data.projects.map((p) => ({
119
- id: p.id,
120
- name: p.name,
121
- description: p.description,
122
- ablyChannelName: p.ablyChannelName,
123
- role: p.role
124
- }));
125
- }
126
- /** POST /api/projects — create a new project, returns it. */
127
- async createProject(name, description) {
128
- const res = await fetch(`${this.serverUrl}/api/projects`, {
239
+ const json = await res.json();
240
+ return json.data;
241
+ }
242
+ /** GET /api/me/agents — agents hosted by the logged-in user (with assignments). */
243
+ async listMyAgents() {
244
+ const res = await this.request("GET", "/api/me/agents", void 0, "Failed to list agents");
245
+ const json = await res.json();
246
+ return json.data;
247
+ }
248
+ /** POST /api/me/agents/:id/assignments — assign an agent to a project (idempotent). */
249
+ async assignAgent(agentId, projectId) {
250
+ const res = await fetch(`${this.serverUrl}/api/me/agents/${agentId}/assignments`, {
129
251
  method: "POST",
130
252
  headers: this.authHeaders(),
131
- body: JSON.stringify({ name, description })
253
+ body: JSON.stringify({ projectId })
132
254
  });
133
- if (!res.ok) {
134
- const text = await res.text();
135
- throw new Error(`Failed to create project (${res.status}): ${text}`);
255
+ if (!res.ok && res.status !== 409) {
256
+ const text = await readError(res);
257
+ throw new Error(`Failed to assign agent to project ${projectId} (${res.status}): ${text}`);
136
258
  }
137
- const data = await res.json();
138
- return {
139
- id: data.project.id,
140
- name: data.project.name,
141
- description: data.project.description,
142
- ablyChannelName: data.project.ablyChannelName,
143
- role: "admin"
144
- };
259
+ }
260
+ /** DELETE /api/me/agents/:id/assignments?projectId= — remove an assignment. */
261
+ async unassignAgent(agentId, projectId) {
262
+ const res = await this.request(
263
+ "DELETE",
264
+ `/api/me/agents/${agentId}/assignments?projectId=${encodeURIComponent(projectId)}`,
265
+ void 0,
266
+ "Failed to unassign agent"
267
+ );
268
+ const json = await res.json().catch(() => ({}));
269
+ return json.data?.removed ?? true;
270
+ }
271
+ /** POST /api/me/agents/:id/keys — mint an agent-bound API key. The raw key is returned once. */
272
+ async createAgentKey(agentId, name) {
273
+ const res = await this.request(
274
+ "POST",
275
+ `/api/me/agents/${agentId}/keys`,
276
+ name ? { name } : {},
277
+ "Failed to create agent API key"
278
+ );
279
+ const json = await res.json();
280
+ return json.data;
281
+ }
282
+ /** POST /api/agents/:id/heartbeat — refresh lastSeenAt (host session or the agent's own key). */
283
+ async heartbeat(agentId) {
284
+ const res = await this.request(
285
+ "POST",
286
+ `/api/agents/${agentId}/heartbeat`,
287
+ void 0,
288
+ "Heartbeat"
289
+ );
290
+ const json = await res.json();
291
+ return json.data;
145
292
  }
146
293
  // ── Ably token ──────────────────────────────────────────────────────
147
294
  /** POST /api/ably/token — get scoped Ably TokenRequest. */
148
295
  async getAblyToken() {
149
- const res = await fetch(`${this.serverUrl}/api/ably/token`, {
150
- method: "POST",
151
- headers: this.authHeaders()
152
- });
153
- if (!res.ok) {
154
- const text = await res.text();
155
- throw new Error(`Failed to get Ably token (${res.status}): ${text}`);
156
- }
296
+ const res = await this.request("POST", "/api/ably/token", void 0, "Failed to get Ably token");
157
297
  return res.json();
158
298
  }
159
299
  // ── Messages ────────────────────────────────────────────────────────
160
300
  /**
161
- * POST /api/projects/{id}/messages — persist a message (idempotent).
162
- * Passing a client-generated `id` makes the server skip Ably re-publish.
301
+ * POST /api/projects/{id}/messages — persist a message. This is the only
302
+ * write path for final messages: the server publishes the echo to Ably
303
+ * itself. Idempotent on `id` (201 on create, 200 if it already existed).
304
+ *
305
+ * Identity is derived server-side: in session mode pass `agentId` to post
306
+ * as that hosted agent; with an agent key it is implied.
307
+ *
308
+ * Retries once on network errors / 5xx (safe: ids are idempotent).
163
309
  */
164
310
  async persistMessage(projectId, msg) {
165
- const res = await fetch(
166
- `${this.serverUrl}/api/projects/${projectId}/messages`,
167
- {
311
+ const body = { text: msg.text };
312
+ if (msg.id) body.id = msg.id;
313
+ if (msg.agentId) body.agentId = msg.agentId;
314
+ if (msg.type) body.type = msg.type;
315
+ if (msg.parentMessageId) body.parentMessageId = msg.parentMessageId;
316
+ if (msg.mentions?.length) body.mentions = msg.mentions;
317
+ const attempt = async () => {
318
+ const res = await fetch(`${this.serverUrl}/api/projects/${projectId}/messages`, {
168
319
  method: "POST",
169
320
  headers: this.authHeaders(),
170
- body: JSON.stringify(msg)
321
+ body: JSON.stringify(body)
322
+ });
323
+ if (!res.ok) {
324
+ const text = await readError(res);
325
+ const err = new Error(`Failed to persist message (${res.status}): ${text}`);
326
+ err.status = res.status;
327
+ throw err;
171
328
  }
172
- );
173
- if (!res.ok) {
174
- const text = await res.text();
175
- console.error(
176
- `[sdk] Failed to persist message (${res.status}): ${text}`
177
- );
329
+ const json = await res.json();
330
+ return json.data;
331
+ };
332
+ try {
333
+ return await attempt();
334
+ } catch (err) {
335
+ const status = err.status;
336
+ const retryable = status === void 0 || status >= 500 || status === 429;
337
+ if (!retryable) throw err;
338
+ await new Promise((r) => setTimeout(r, 1e3));
339
+ return attempt();
178
340
  }
179
341
  }
180
- /** GET /api/projects/{id}/messages — fetch recent messages. */
342
+ /** GET /api/projects/{id}/messages — fetch recent messages (oldest first). */
181
343
  async fetchMessages(projectId, limit = 20) {
182
- const res = await fetch(
183
- `${this.serverUrl}/api/projects/${projectId}/messages?limit=${limit}`,
184
- { headers: this.authHeaders() }
344
+ const res = await this.request(
345
+ "GET",
346
+ `/api/projects/${projectId}/messages?limit=${limit}`,
347
+ void 0,
348
+ "Failed to fetch messages"
185
349
  );
186
- if (!res.ok) {
187
- const text = await res.text();
188
- throw new Error(`Failed to fetch messages (${res.status}): ${text}`);
189
- }
190
350
  const data = await res.json();
191
351
  return data.data;
192
352
  }
193
353
  // ── Tasks ───────────────────────────────────────────────────────────
194
354
  /** POST /api/projects/{id}/tasks — create a task. */
195
355
  async createTask(projectId, data) {
196
- const res = await fetch(
197
- `${this.serverUrl}/api/projects/${projectId}/tasks`,
198
- {
199
- method: "POST",
200
- headers: this.authHeaders(),
201
- body: JSON.stringify(data)
202
- }
356
+ const res = await this.request(
357
+ "POST",
358
+ `/api/projects/${projectId}/tasks`,
359
+ data,
360
+ "Failed to create task"
203
361
  );
204
- if (!res.ok) {
205
- const text = await res.text();
206
- throw new Error(`Failed to create task (${res.status}): ${text}`);
207
- }
208
362
  const result = await res.json();
209
363
  return result.data;
210
364
  }
211
- /** PATCH /api/tasks/{taskId} — update task fields. */
365
+ /** PATCH /api/tasks/{taskId} — update task fields. Returns the updated task. */
212
366
  async updateTask(taskId, updates) {
213
- const res = await fetch(`${this.serverUrl}/api/tasks/${taskId}`, {
214
- method: "PATCH",
215
- headers: this.authHeaders(),
216
- body: JSON.stringify(updates)
217
- });
218
- if (!res.ok) {
219
- const text = await res.text();
220
- console.error(`[sdk] Failed to update task (${res.status}): ${text}`);
221
- }
367
+ const res = await this.request(
368
+ "PATCH",
369
+ `/api/tasks/${taskId}`,
370
+ updates,
371
+ "Failed to update task"
372
+ );
373
+ const result = await res.json();
374
+ return result.data;
222
375
  }
223
376
  };
224
377
 
225
378
  // src/ably-manager.ts
226
379
  var import_ably = __toESM(require("ably"), 1);
380
+ var CONNECT_TIMEOUT_MS = 3e4;
227
381
  var AblyManager = class {
228
- constructor(client, userId, username) {
382
+ constructor(client, opts) {
229
383
  this.client = client;
230
- this.userId = userId;
231
- this.username = username;
384
+ this.opts = opts;
232
385
  }
233
386
  ably = null;
234
387
  channels = /* @__PURE__ */ new Map();
235
388
  presenceChannel = null;
236
389
  /** Create Ably Realtime client with token auth callback. */
237
- async connect() {
390
+ async connect(timeoutMs = CONNECT_TIMEOUT_MS) {
238
391
  return new Promise((resolve, reject) => {
392
+ let lastAuthError = null;
393
+ let settled = false;
394
+ const finish = (fn) => {
395
+ if (settled) return;
396
+ settled = true;
397
+ clearTimeout(timer);
398
+ fn();
399
+ };
400
+ const timer = setTimeout(() => {
401
+ finish(() => {
402
+ this.ably?.close();
403
+ this.ably = null;
404
+ reject(
405
+ new Error(
406
+ `Ably connection timed out after ${Math.round(timeoutMs / 1e3)}s` + (lastAuthError ? ` (last auth error: ${lastAuthError.message})` : "")
407
+ )
408
+ );
409
+ });
410
+ }, timeoutMs);
239
411
  this.ably = new import_ably.default.Realtime({
240
412
  authCallback: async (_tokenParams, callback) => {
241
413
  try {
242
414
  const tokenRequest = await this.client.getAblyToken();
243
415
  callback(null, tokenRequest);
244
416
  } catch (err) {
245
- callback(err, null);
417
+ lastAuthError = err instanceof Error ? err : new Error(String(err));
418
+ callback(lastAuthError.message, null);
246
419
  }
247
420
  },
248
- clientId: this.userId,
421
+ ...this.opts.clientId ? { clientId: this.opts.clientId } : {},
249
422
  disconnectedRetryTimeout: 5e3,
250
423
  // 5s initial retry on disconnect
251
424
  suspendedRetryTimeout: 3e4
252
425
  // 30s retry when suspended
253
426
  });
254
427
  this.ably.connection.once("connected", () => {
255
- resolve();
428
+ finish(resolve);
256
429
  });
257
430
  this.ably.connection.once("failed", (stateChange) => {
258
- reject(
259
- new Error(
260
- `Ably connection failed: ${stateChange?.reason?.message ?? "unknown"}`
431
+ finish(
432
+ () => reject(
433
+ new Error(
434
+ `Ably connection failed: ${stateChange?.reason?.message ?? lastAuthError?.message ?? "unknown"}`
435
+ )
261
436
  )
262
437
  );
263
438
  });
@@ -275,42 +450,62 @@ var AblyManager = class {
275
450
  });
276
451
  }
277
452
  /** Enter global presence channel (jaibber:presence). */
278
- async enterGlobalPresence(projectIds) {
453
+ async enterGlobalPresence(data) {
279
454
  if (!this.ably) throw new Error("Ably not connected");
280
455
  this.presenceChannel = this.ably.channels.get("jaibber:presence");
281
456
  await this.presenceChannel.presence.enter({
282
- userId: this.userId,
283
- username: this.username,
284
- projectIds
457
+ ...data.userId ? { userId: data.userId } : {},
458
+ ...data.agentId ? { agentId: data.agentId } : {},
459
+ username: data.username,
460
+ projectIds: data.projectIds
285
461
  });
286
462
  }
287
463
  /**
288
- * Subscribe to a project channel and enter per-project presence.
464
+ * Subscribe to a project channel (`message`, `task` and server-published
465
+ * `agent-control` events) and enter per-project presence.
289
466
  * Returns an unsubscribe function.
290
467
  */
291
- async subscribeToProject(project, presenceData, onMessage, onTask) {
468
+ async subscribeToProject(project, presenceData, onMessage, onTask, onControl, onError = (err, event) => console.error(`[sdk] Unhandled error in ${event} handler:`, err)) {
292
469
  if (!this.ably) throw new Error("Ably not connected");
293
470
  const channel = this.ably.channels.get(project.ablyChannelName);
294
471
  this.channels.set(project.ablyChannelName, channel);
295
472
  await channel.presence.enter(presenceData);
296
- const messageHandler = (msg) => {
297
- 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;
298
482
  const payload = msg.data;
299
483
  payload._connectionId = msg.connectionId ?? void 0;
300
- onMessage(payload);
301
- };
302
- const taskHandler = (msg) => {
303
- if (!msg.data) return;
304
- onTask(msg.data);
305
- };
484
+ payload._clientId = msg.clientId ?? void 0;
485
+ return onMessage(payload);
486
+ });
487
+ const taskHandler = (msg) => safely("task", () => {
488
+ if (!msg.data || typeof msg.data !== "object") return;
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
+ });
306
495
  channel.subscribe("message", messageHandler);
307
496
  channel.subscribe("task", taskHandler);
497
+ channel.subscribe("agent-control", controlHandler);
308
498
  return () => {
309
499
  channel.unsubscribe("message", messageHandler);
310
500
  channel.unsubscribe("task", taskHandler);
501
+ channel.unsubscribe("agent-control", controlHandler);
311
502
  };
312
503
  }
313
- /** Publish a message on a project channel. */
504
+ /**
505
+ * Publish a client-side event on a project channel. Only `typing` and
506
+ * `chunk` are client-published; final messages go through the REST API
507
+ * and are echoed by the server.
508
+ */
314
509
  async publish(channelName, eventName, data) {
315
510
  const channel = this.channels.get(channelName);
316
511
  if (!channel) {
@@ -322,6 +517,10 @@ var AblyManager = class {
322
517
  get connectionId() {
323
518
  return this.ably?.connection.id;
324
519
  }
520
+ /** The clientId this connection authenticated as (from the token in API-key mode). */
521
+ get clientId() {
522
+ return this.ably?.auth.clientId ?? void 0;
523
+ }
325
524
  /** Leave presence on all channels and close the connection. */
326
525
  async disconnect() {
327
526
  for (const channel of this.channels.values()) {
@@ -352,44 +551,90 @@ var MessageContext = class {
352
551
  conversationHistory;
353
552
  /** The project ID this message was received on. */
354
553
  projectId;
355
- responseId;
554
+ /** The agent's server-side id (sent as `agentId` on every save). */
555
+ agentId;
556
+ /** The agent's display name. */
557
+ agentName;
558
+ /** Id of the message being responded to (if any). */
559
+ incomingMessageId;
560
+ /**
561
+ * The id the final reply will be stored under. Also the `responseId` sent
562
+ * with `typing` so clients can pre-create the bubble.
563
+ */
564
+ messageId;
356
565
  ablyManager;
357
566
  channelName;
358
- userId;
359
- agentName;
567
+ from;
360
568
  client;
361
569
  responseDepth;
362
570
  respondingChain;
363
571
  chunkBatchMs;
572
+ tracker;
573
+ /** Set by `stream()` when its generator threw. */
574
+ streamError = void 0;
364
575
  constructor(opts) {
365
576
  this.projectId = opts.projectId;
366
577
  this.channelName = opts.channelName;
367
578
  this.conversationHistory = opts.conversationHistory;
368
579
  this.ablyManager = opts.ablyManager;
369
- this.userId = opts.userId;
580
+ this.from = opts.from;
581
+ this.agentId = opts.agentId;
370
582
  this.agentName = opts.agentName;
371
583
  this.client = opts.client;
584
+ this.incomingMessageId = opts.incomingMessageId;
372
585
  this.responseDepth = opts.incomingDepth + 1;
373
586
  this.respondingChain = [
374
587
  ...opts.incomingChain,
375
588
  opts.agentName.toLowerCase()
376
589
  ];
377
590
  this.chunkBatchMs = opts.chunkBatchMs;
378
- this.responseId = (0, import_uuid.v4)();
591
+ this.tracker = opts.tracker;
592
+ this.messageId = (0, import_uuid.v4)();
593
+ }
594
+ /** Agent-to-agent hop count this reply will carry (informational). */
595
+ get depth() {
596
+ return this.responseDepth;
597
+ }
598
+ /** Agents that have already responded in this chain, including this one. */
599
+ get chain() {
600
+ return [...this.respondingChain];
379
601
  }
380
- /** One-shot reply: publishes typing → response in sequence. */
381
- async reply(text) {
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
+ */
616
+ async reply(text, opts) {
382
617
  await this.publishTyping();
383
- await this.publishResponse(text);
384
- this.persistAsync(text, "response");
618
+ return this.deliver(text, "response", this.parentFor(opts));
619
+ }
620
+ /** Replies thread under the answered message unless overridden. */
621
+ parentFor(opts) {
622
+ return opts?.parentMessageId ?? this.incomingMessageId;
385
623
  }
386
624
  /**
387
625
  * Streaming reply: consumes an async generator, batches chunks to Ably
388
- * every chunkBatchMs (default 200ms), then publishes the final response.
626
+ * every chunkBatchMs (default 200ms), then POSTs the final message.
627
+ * Resolves with the full response text.
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.
389
634
  *
390
- * Mirrors useAbly.ts lines 86-102 chunk batching pattern.
635
+ * Mirrors useAbly.ts chunk batching pattern.
391
636
  */
392
- async stream(generator) {
637
+ async stream(generator, opts) {
393
638
  await this.publishTyping();
394
639
  let fullText = "";
395
640
  let chunkBuffer = "";
@@ -398,177 +643,201 @@ var MessageContext = class {
398
643
  if (!chunkBuffer) return;
399
644
  const text = chunkBuffer;
400
645
  chunkBuffer = "";
401
- 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
+ }
402
651
  };
403
652
  try {
404
653
  for await (const chunk of generator()) {
405
654
  fullText += chunk;
406
655
  chunkBuffer += chunk;
407
656
  if (!flushTimer) {
408
- flushTimer = setTimeout(async () => {
657
+ flushTimer = setTimeout(() => {
409
658
  flushTimer = null;
410
- await flushChunks();
659
+ void flushChunks();
411
660
  }, this.chunkBatchMs);
412
661
  }
413
662
  }
414
663
  if (flushTimer) clearTimeout(flushTimer);
415
664
  await flushChunks();
416
- await this.publishResponse(fullText);
417
- this.persistAsync(fullText, "response");
418
665
  } catch (err) {
419
666
  if (flushTimer) clearTimeout(flushTimer);
667
+ this.streamError = err;
420
668
  const errText = `Agent error: ${err instanceof Error ? err.message : String(err)}`;
421
- await this.publishError(errText);
422
- this.persistAsync(errText, "error");
669
+ try {
670
+ await this.deliver(errText, "error", this.parentFor(opts));
671
+ } catch (e) {
672
+ console.error("[sdk] Failed to persist error message:", e);
673
+ }
674
+ return fullText;
423
675
  }
676
+ await this.deliver(fullText, "response", this.parentFor(opts));
677
+ return fullText;
424
678
  }
425
679
  // ── Internal publish helpers ────────────────────────────────────────
426
680
  async publishTyping() {
427
681
  await this.ablyManager.publish(this.channelName, "message", {
428
- from: this.userId,
682
+ from: this.from,
429
683
  fromUsername: this.agentName,
430
684
  projectId: this.projectId,
431
685
  text: "",
432
686
  messageId: (0, import_uuid.v4)(),
433
- responseId: this.responseId,
687
+ responseId: this.messageId,
434
688
  type: "typing",
435
- agentName: this.agentName
689
+ agentName: this.agentName,
690
+ agentId: this.agentId
436
691
  });
437
692
  }
438
693
  async publishChunk(text) {
439
694
  await this.ablyManager.publish(this.channelName, "message", {
440
- from: this.userId,
695
+ from: this.from,
441
696
  fromUsername: this.agentName,
442
697
  projectId: this.projectId,
443
698
  text,
444
- messageId: this.responseId,
699
+ messageId: this.messageId,
445
700
  type: "chunk",
446
- agentName: this.agentName
447
- });
448
- }
449
- async publishResponse(text) {
450
- await this.ablyManager.publish(this.channelName, "message", {
451
- from: this.userId,
452
- fromUsername: this.agentName,
453
- projectId: this.projectId,
454
- text,
455
- messageId: this.responseId,
456
- type: "response",
457
701
  agentName: this.agentName,
458
- isAgentMessage: true,
459
- responseDepth: this.responseDepth,
460
- respondingChain: this.respondingChain
702
+ agentId: this.agentId
461
703
  });
462
704
  }
463
- async publishError(text) {
464
- await this.ablyManager.publish(this.channelName, "message", {
465
- from: this.userId,
466
- fromUsername: this.agentName,
467
- projectId: this.projectId,
468
- text,
469
- messageId: this.responseId,
470
- type: "error",
471
- agentName: this.agentName
472
- });
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
+ }
473
723
  }
474
- /** Fire-and-forget persist to server. */
475
- persistAsync(text, type) {
476
- this.client.persistMessage(this.projectId, {
477
- id: this.responseId,
478
- senderType: "agent",
479
- senderName: this.agentName,
480
- type,
481
- text
482
- }).catch((err) => {
483
- console.error("[sdk] Failed to persist message:", err);
484
- });
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
+ }
743
+ /** POST the final message. Throws if the server rejects it. */
744
+ async persist(id, text, type, parentMessageId) {
745
+ this.tracker?.begin(id, this.projectId, text, type, parentMessageId);
746
+ try {
747
+ const saved = await this.client.persistMessage(this.projectId, {
748
+ id,
749
+ agentId: this.agentId,
750
+ type,
751
+ text,
752
+ parentMessageId
753
+ });
754
+ this.tracker?.posted(id);
755
+ return saved;
756
+ } catch (err) {
757
+ this.tracker?.failed(id);
758
+ throw err;
759
+ }
485
760
  }
486
761
  };
487
762
  var TaskContext = class {
488
763
  task;
489
764
  projectId;
490
765
  conversationHistory;
491
- ablyManager;
492
- channelName;
493
- userId;
766
+ agentId;
494
767
  agentName;
495
768
  client;
769
+ tracker;
496
770
  constructor(opts) {
497
771
  this.task = opts.task;
498
772
  this.projectId = opts.projectId;
499
- this.channelName = opts.channelName;
500
773
  this.conversationHistory = opts.conversationHistory;
501
- this.ablyManager = opts.ablyManager;
502
- this.userId = opts.userId;
774
+ this.agentId = opts.agentId;
503
775
  this.agentName = opts.agentName;
504
776
  this.client = opts.client;
777
+ this.tracker = opts.tracker;
505
778
  }
506
- /** Mark task as completed, optionally publishing a response message. */
779
+ /** Mark task as completed, optionally posting a response message. */
507
780
  async complete(resultText) {
508
781
  await this.client.updateTask(this.task.id, { status: "completed" });
509
782
  if (resultText) {
510
783
  await this.sendMessage(resultText);
511
784
  }
512
785
  }
513
- /** Mark task as failed, optionally publishing an error message. */
786
+ /** Mark task as failed, optionally posting an error message. */
514
787
  async fail(errorText) {
515
788
  await this.client.updateTask(this.task.id, { status: "failed" });
516
789
  if (errorText) {
517
- const msgId = (0, import_uuid.v4)();
518
- await this.ablyManager.publish(this.channelName, "message", {
519
- from: this.userId,
520
- fromUsername: this.agentName,
521
- projectId: this.projectId,
522
- text: errorText,
523
- messageId: msgId,
524
- type: "error",
525
- agentName: this.agentName
526
- });
527
- this.client.persistMessage(this.projectId, {
528
- id: msgId,
529
- senderType: "agent",
530
- senderName: this.agentName,
531
- type: "error",
532
- text: errorText
533
- }).catch((err) => console.error("[sdk] Failed to persist:", err));
790
+ await this.sendMessage(errorText, { type: "error" });
534
791
  }
535
792
  }
536
793
  /**
537
794
  * Create a follow-up task assigned to another agent.
538
- * Automatically sets parentTaskId to the current task's ID.
795
+ * Automatically sets parentTaskId to the current task's ID and attributes
796
+ * creation to this agent.
539
797
  */
540
798
  async createFollowUpTask(data) {
541
799
  return this.client.createTask(this.projectId, {
542
800
  ...data,
543
801
  parentTaskId: this.task.id,
544
802
  createdByType: "agent",
545
- createdByName: this.agentName
803
+ createdByName: this.agentName,
804
+ createdByAgentId: this.agentId
546
805
  });
547
806
  }
548
- /** Send a chat message (for progress updates). */
549
- async sendMessage(text) {
807
+ /**
808
+ * Post a chat message (for progress updates). Returns the stored message.
809
+ * `type` defaults to "response"; use "message" for notices that must never
810
+ * trigger other agents (agent-to-agent chaining only flows through responses).
811
+ */
812
+ async sendMessage(text, opts) {
550
813
  const msgId = (0, import_uuid.v4)();
551
- await this.ablyManager.publish(this.channelName, "message", {
552
- from: this.userId,
553
- fromUsername: this.agentName,
554
- projectId: this.projectId,
555
- text,
556
- messageId: msgId,
557
- type: "response",
558
- agentName: this.agentName,
559
- isAgentMessage: true
560
- });
561
- this.client.persistMessage(this.projectId, {
562
- id: msgId,
563
- senderType: "agent",
564
- senderName: this.agentName,
565
- type: "response",
566
- text
567
- }).catch((err) => console.error("[sdk] Failed to persist:", err));
814
+ const type = opts?.type ?? "response";
815
+ this.tracker?.begin(msgId, this.projectId, text, type, opts?.parentMessageId);
816
+ try {
817
+ const saved = await this.client.persistMessage(this.projectId, {
818
+ id: msgId,
819
+ agentId: this.agentId,
820
+ type,
821
+ text,
822
+ parentMessageId: opts?.parentMessageId
823
+ });
824
+ this.tracker?.posted(msgId);
825
+ return saved;
826
+ } catch (err) {
827
+ this.tracker?.failed(msgId);
828
+ throw err;
829
+ }
568
830
  }
569
831
  };
570
832
 
571
833
  // src/mentions.ts
834
+ function parseMentions(text) {
835
+ const mentions = [];
836
+ for (const match of text.matchAll(/@(\w+(?:\s+\w+)*)/g)) {
837
+ mentions.push(match[1].toLowerCase());
838
+ }
839
+ return mentions;
840
+ }
572
841
  function mentionsAgent(text, agentName) {
573
842
  const pattern = new RegExp(`@${escapeRegex(agentName)}(?!\\w)`, "i");
574
843
  return pattern.test(text);
@@ -580,7 +849,7 @@ function escapeRegex(s) {
580
849
  // src/providers/anthropic.ts
581
850
  var ANTHROPIC_API_URL = "https://api.anthropic.com/v1/messages";
582
851
  var ANTHROPIC_VERSION = "2024-10-22";
583
- var DEFAULT_MODEL = "claude-sonnet-4-6";
852
+ var DEFAULT_MODEL = "claude-sonnet-5";
584
853
  var DEFAULT_MAX_TOKENS = 8192;
585
854
  var AnthropicProvider = class {
586
855
  apiKey;
@@ -969,82 +1238,262 @@ ${systemPrompt}
969
1238
  var DEFAULT_MAX_DEPTH = 3;
970
1239
  var DEFAULT_CHUNK_BATCH_MS = 200;
971
1240
  var DEFAULT_CONTEXT_WINDOW = 20;
972
- var JaibberAgent = class extends import_events.EventEmitter {
1241
+ var DEFAULT_HEARTBEAT_MS = 12e4;
1242
+ var OWN_MESSAGE_MEMORY = 1e3;
1243
+ var MESSAGE_INDEX_SIZE = 500;
1244
+ var META_TTL_MS = 5 * 60 * 1e3;
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.";
1246
+ var JaibberAgent = class _JaibberAgent extends import_events.EventEmitter {
973
1247
  config;
974
1248
  client;
975
1249
  ablyManager = null;
976
1250
  messageHandler = null;
977
1251
  taskHandler = null;
978
1252
  provider = null;
1253
+ providerKind = null;
979
1254
  connected = false;
980
1255
  projects = [];
981
1256
  unsubscribers = [];
1257
+ heartbeatTimer = null;
1258
+ agentId = null;
1259
+ agentRecord = null;
1260
+ keyIdentity = null;
982
1261
  /** In-memory conversation history per project. */
983
1262
  history = /* @__PURE__ */ new Map();
1263
+ /** Recent messages per project (id → author/parent) for chain reconstruction. */
1264
+ messageIndex = /* @__PURE__ */ new Map();
984
1265
  /** Track in-flight responses to prevent double-handling. */
985
1266
  activeResponses = /* @__PURE__ */ new Set();
986
1267
  /** Session IDs per project for Claude --resume. */
987
1268
  sessionIds = /* @__PURE__ */ new Map();
1269
+ /** Messages we POSTed ourselves, keyed by id — for echo dedupe + own-reply history. */
1270
+ ownMessages = /* @__PURE__ */ new Map();
1271
+ /** `meta` hints waiting for their server echo. */
1272
+ pendingMeta = /* @__PURE__ */ new Map();
1273
+ /**
1274
+ * Safety valve: unthreaded agent responses (no `parentMessageId`) seen per
1275
+ * project since the last human message. Threaded chains are bounded by the
1276
+ * `parentMessageId` walk; this catches agents that post without threading,
1277
+ * which would otherwise look like a fresh depth-1 chain every time.
1278
+ */
1279
+ unthreadedHops = /* @__PURE__ */ new Map();
988
1280
  constructor(config) {
989
1281
  super();
990
1282
  this.config = config;
991
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);
1301
+ }
1302
+ // ── Accessors ───────────────────────────────────────────────────────
1303
+ /** The agent's server-side id (available after `connect()`). */
1304
+ get id() {
1305
+ return this.agentId;
1306
+ }
1307
+ /** The agent record returned by the server (session mode only). */
1308
+ get record() {
1309
+ return this.agentRecord;
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
+ }
1315
+ /** The underlying REST client (authenticated after `connect()`). */
1316
+ get api() {
1317
+ return this.client;
1318
+ }
1319
+ /** Projects this agent has joined. */
1320
+ get joinedProjects() {
1321
+ return [...this.projects];
1322
+ }
1323
+ /** Sender id used on client-published typing/chunk events. */
1324
+ get senderId() {
1325
+ return this.client.userId ?? `agent:${this.agentId ?? "unknown"}`;
1326
+ }
1327
+ get maxDepth() {
1328
+ return this.config.maxResponseDepth ?? DEFAULT_MAX_DEPTH;
992
1329
  }
993
1330
  // ── Lifecycle ───────────────────────────────────────────────────────
994
- /** Authenticate, connect Ably, subscribe to project channels. */
1331
+ /** Authenticate, register/resolve the agent, connect Ably, subscribe to project channels. */
995
1332
  async connect() {
996
1333
  if (this.connected) throw new Error("Already connected");
997
- const { username, password } = this.config.credentials;
998
- console.log(`[sdk] Logging in as "${username}"...`);
999
- await this.client.login(username, password);
1000
- const userId = this.client.userId;
1001
- const displayName = this.client.username;
1334
+ const creds = this.config.credentials;
1335
+ const apiKeyMode = "apiKey" in creds;
1336
+ if (apiKeyMode) {
1337
+ this.client.setApiKey(creds.apiKey);
1338
+ this.agentId = this.config.agentId ?? null;
1339
+ console.log(`[sdk] Authenticating with agent API key ${creds.apiKey.slice(0, 11)}\u2026`);
1340
+ await this.resolveKeyIdentity();
1341
+ } else {
1342
+ console.log(`[sdk] Logging in as "${creds.username}"...`);
1343
+ await this.client.login(creds.username, creds.password);
1344
+ const record = await this.client.ensureAgent({
1345
+ name: this.config.agentName,
1346
+ instructions: this.config.agentInstructions,
1347
+ provider: this.resolveProviderKind(),
1348
+ kind: "sdk",
1349
+ machineName: this.config.machineName,
1350
+ orgId: this.config.orgId
1351
+ });
1352
+ this.agentId = record.id;
1353
+ this.agentRecord = record;
1354
+ this.config.agentId = record.id;
1355
+ console.log(`[sdk] Agent "${record.name}" registered (id ${record.id})`);
1356
+ }
1002
1357
  const allProjects = await this.client.listProjects();
1003
- this.projects = this.config.projectIds ? allProjects.filter((p) => this.config.projectIds.includes(p.id)) : allProjects;
1358
+ if (this.config.projectIds) {
1359
+ const wanted = new Set(this.config.projectIds);
1360
+ this.projects = allProjects.filter((p) => wanted.has(p.id));
1361
+ const missing = this.config.projectIds.filter(
1362
+ (id) => !this.projects.some((p) => p.id === id)
1363
+ );
1364
+ if (missing.length > 0) {
1365
+ console.warn(`[sdk] Project(s) not accessible, skipping: ${missing.join(", ")}`);
1366
+ }
1367
+ } else {
1368
+ this.projects = allProjects.filter((p) => p.role !== "org-admin");
1369
+ }
1004
1370
  if (this.projects.length === 0) {
1005
1371
  throw new Error(
1006
- "No projects found. Ensure the agent account is a member of at least one project."
1372
+ apiKeyMode ? "No projects found. Assign this agent to at least one project first (POST /api/me/agents/:id/assignments, or run with --projects when minting the key)." : "No projects found. Ensure the account is a member of at least one project."
1007
1373
  );
1008
1374
  }
1009
1375
  console.log(
1010
1376
  `[sdk] Found ${this.projects.length} project(s): ${this.projects.map((p) => p.name).join(", ")}`
1011
1377
  );
1012
- this.ablyManager = new AblyManager(this.client, userId, displayName);
1378
+ if (!apiKeyMode) {
1379
+ for (const project of this.projects) {
1380
+ try {
1381
+ await this.client.assignAgent(this.agentId, project.id);
1382
+ } catch (err) {
1383
+ console.warn(
1384
+ `[sdk] Could not assign agent to "${project.name}": ${err instanceof Error ? err.message : err}`
1385
+ );
1386
+ }
1387
+ }
1388
+ }
1389
+ this.ablyManager = new AblyManager(this.client, {
1390
+ clientId: apiKeyMode ? void 0 : this.client.userId,
1391
+ username: this.config.agentName
1392
+ });
1013
1393
  await this.ablyManager.connect();
1014
- await this.ablyManager.enterGlobalPresence(
1015
- this.projects.map((p) => p.id)
1016
- );
1017
- for (const project of this.projects) {
1394
+ try {
1395
+ if (!this.agentId) {
1396
+ const cid = this.ablyManager.clientId;
1397
+ if (cid && cid.startsWith("agent:")) {
1398
+ this.agentId = cid.slice("agent:".length);
1399
+ this.config.agentId = this.agentId;
1400
+ } else {
1401
+ throw new Error(
1402
+ `Could not resolve the agent id from the API key (Ably clientId was ${JSON.stringify(cid ?? null)}). The key must be bound to an agent \u2014 mint one with POST /api/me/agents/:id/keys or \`jaibber-agent --create-key\`.`
1403
+ );
1404
+ }
1405
+ }
1406
+ this.startHeartbeat();
1407
+ await this.ablyManager.enterGlobalPresence({
1408
+ userId: this.client.userId ?? void 0,
1409
+ agentId: this.agentId,
1410
+ username: this.config.agentName,
1411
+ projectIds: this.projects.map((p) => p.id)
1412
+ });
1018
1413
  const presenceData = {
1019
- userId,
1414
+ userId: this.client.userId ?? void 0,
1020
1415
  username: this.config.agentName,
1021
1416
  isAgent: true,
1022
1417
  agentName: this.config.agentName,
1418
+ agentId: this.agentId,
1023
1419
  agentInstructions: this.config.agentInstructions,
1024
1420
  agents: [
1025
1421
  {
1422
+ agentId: this.agentId,
1026
1423
  agentName: this.config.agentName,
1027
1424
  agentInstructions: this.config.agentInstructions
1028
1425
  }
1029
1426
  ],
1030
1427
  machineName: this.config.machineName
1031
1428
  };
1032
- await this.loadHistory(project.id);
1033
- const unsub = await this.ablyManager.subscribeToProject(
1034
- project,
1035
- presenceData,
1036
- (msg) => this.handleIncomingMessage(msg, project),
1037
- (data) => this.handleTaskEvent(data, project)
1038
- );
1039
- this.unsubscribers.push(unsub);
1429
+ for (const project of this.projects) {
1430
+ await this.loadHistory(project.id);
1431
+ const unsub = await this.ablyManager.subscribeToProject(
1432
+ project,
1433
+ presenceData,
1434
+ (msg) => this.handleIncomingMessage(msg, project),
1435
+ (data) => this.handleTaskEvent(data, project),
1436
+ (data) => this.handleControlEvent(data, project),
1437
+ (err) => this.emitError(err)
1438
+ );
1439
+ this.unsubscribers.push(unsub);
1440
+ }
1441
+ } catch (err) {
1442
+ this.stopHeartbeat();
1443
+ for (const unsub of this.unsubscribers) unsub();
1444
+ this.unsubscribers = [];
1445
+ await this.ablyManager.disconnect().catch(() => {
1446
+ });
1447
+ this.ablyManager = null;
1448
+ throw err;
1040
1449
  }
1041
1450
  this.connected = true;
1042
- console.log(`[sdk] Agent "${this.config.agentName}" connected and listening`);
1451
+ console.log(
1452
+ `[sdk] Agent "${this.config.agentName}" (${this.agentId}) connected and listening`
1453
+ );
1043
1454
  this.emit("connected", this.projects);
1044
1455
  }
1045
- /** Leave presence, disconnect Ably. */
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
+ }
1493
+ /** Stop heartbeats, leave presence, disconnect Ably. */
1046
1494
  async disconnect() {
1047
1495
  if (!this.connected) return;
1496
+ this.stopHeartbeat();
1048
1497
  for (const unsub of this.unsubscribers) {
1049
1498
  unsub();
1050
1499
  }
@@ -1069,51 +1518,192 @@ var JaibberAgent = class extends import_events.EventEmitter {
1069
1518
  switch (name) {
1070
1519
  case "anthropic":
1071
1520
  this.provider = new AnthropicProvider(options);
1521
+ this.providerKind = "claude";
1072
1522
  break;
1073
1523
  case "openai":
1074
1524
  this.provider = new OpenAIProvider(options);
1525
+ this.providerKind = "openai";
1075
1526
  break;
1076
1527
  case "google":
1077
1528
  this.provider = new GoogleProvider(options);
1529
+ this.providerKind = "google";
1078
1530
  break;
1079
1531
  case "claude-cli":
1080
1532
  this.provider = new ClaudeCLIProvider(options);
1533
+ this.providerKind = "claude";
1081
1534
  break;
1082
1535
  }
1083
1536
  }
1537
+ /** Provider label stored on the agent record. */
1538
+ resolveProviderKind() {
1539
+ return this.config.provider ?? this.providerKind ?? "custom";
1540
+ }
1541
+ // ── Heartbeat ───────────────────────────────────────────────────────
1542
+ startHeartbeat() {
1543
+ this.stopHeartbeat();
1544
+ const beat = async () => {
1545
+ if (!this.agentId) return;
1546
+ try {
1547
+ await this.client.heartbeat(this.agentId);
1548
+ } catch (err) {
1549
+ console.warn(`[sdk] Heartbeat failed: ${err instanceof Error ? err.message : err}`);
1550
+ }
1551
+ };
1552
+ void beat();
1553
+ this.heartbeatTimer = setInterval(beat, this.config.heartbeatMs ?? DEFAULT_HEARTBEAT_MS);
1554
+ this.heartbeatTimer.unref?.();
1555
+ }
1556
+ stopHeartbeat() {
1557
+ if (this.heartbeatTimer) {
1558
+ clearInterval(this.heartbeatTimer);
1559
+ this.heartbeatTimer = null;
1560
+ }
1561
+ }
1562
+ // ── Message index / chain reconstruction ────────────────────────────
1563
+ indexMessage(projectId, id, entry) {
1564
+ const idx = this.messageIndex.get(projectId) ?? /* @__PURE__ */ new Map();
1565
+ idx.delete(id);
1566
+ idx.set(id, entry);
1567
+ while (idx.size > MESSAGE_INDEX_SIZE) {
1568
+ const oldest = idx.keys().next().value;
1569
+ if (oldest === void 0) break;
1570
+ idx.delete(oldest);
1571
+ }
1572
+ this.messageIndex.set(projectId, idx);
1573
+ }
1574
+ /**
1575
+ * Loop prevention for agent-to-agent chains. The server echo carries no
1576
+ * chain metadata, so the chain is reconstructed from `parentMessageId`
1577
+ * links: every agent response is posted as a reply to the message it
1578
+ * answered. Returns the number of consecutive agent hops ending at
1579
+ * `payload` (the depth) and the lowercased names of the agents in that run.
1580
+ * Mirrors useAbly.ts agentChainFor().
1581
+ */
1582
+ agentChainFor(projectId, payload) {
1583
+ const idx = this.messageIndex.get(projectId);
1584
+ const chain = [(payload.agentName ?? payload.fromUsername).toLowerCase()];
1585
+ let parentId = payload.parentMessageId;
1586
+ let guard = 0;
1587
+ while (parentId && guard++ < 50) {
1588
+ const parent = idx?.get(parentId);
1589
+ if (!parent?.agentId) break;
1590
+ chain.push(parent.senderName.toLowerCase());
1591
+ parentId = parent.parentMessageId;
1592
+ }
1593
+ return { depth: chain.length, chain };
1594
+ }
1595
+ // ── `meta` hints ────────────────────────────────────────────────────
1596
+ rememberMeta(messageId, meta) {
1597
+ const cutoff = Date.now() - META_TTL_MS;
1598
+ for (const [id, m] of this.pendingMeta) {
1599
+ if (m.receivedAt < cutoff) this.pendingMeta.delete(id);
1600
+ }
1601
+ this.pendingMeta.set(messageId, meta);
1602
+ }
1603
+ takeMeta(messageId, senderId) {
1604
+ const meta = this.pendingMeta.get(messageId);
1605
+ if (!meta) return void 0;
1606
+ this.pendingMeta.delete(messageId);
1607
+ return meta.clientId === senderId ? meta : void 0;
1608
+ }
1609
+ // ── Own-message tracking (echo dedupe + own replies in history) ─────
1610
+ tracker = {
1611
+ begin: (id, projectId, text, type, parentMessageId) => {
1612
+ this.ownMessages.set(id, { projectId, text, type, recorded: false });
1613
+ while (this.ownMessages.size > OWN_MESSAGE_MEMORY) {
1614
+ const oldest = this.ownMessages.keys().next().value;
1615
+ if (oldest === void 0) break;
1616
+ this.ownMessages.delete(oldest);
1617
+ }
1618
+ this.indexMessage(projectId, id, {
1619
+ agentId: this.agentId ?? void 0,
1620
+ senderName: this.config.agentName,
1621
+ parentMessageId
1622
+ });
1623
+ },
1624
+ posted: (id) => this.recordOwnMessage(id),
1625
+ failed: (id) => {
1626
+ this.ownMessages.delete(id);
1627
+ }
1628
+ };
1629
+ /**
1630
+ * Add one of our own messages to history exactly once — whichever arrives
1631
+ * first: the server's Ably echo or the POST response.
1632
+ */
1633
+ recordOwnMessage(id) {
1634
+ const own = this.ownMessages.get(id);
1635
+ if (!own || own.recorded) return;
1636
+ own.recorded = true;
1637
+ if (own.type === "error") return;
1638
+ this.addToHistory(own.projectId, {
1639
+ sender: "agent",
1640
+ senderName: this.config.agentName,
1641
+ text: own.text,
1642
+ agentId: this.agentId ?? void 0
1643
+ });
1644
+ }
1084
1645
  // ── Message handling ────────────────────────────────────────────────
1085
1646
  async handleIncomingMessage(payload, project) {
1086
1647
  if (payload._connectionId && payload._connectionId === this.ablyManager?.connectionId) return;
1087
- if (payload.type === "deregister") {
1088
- const targetName = payload.agentName?.toLowerCase();
1089
- if (!targetName || targetName === this.config.agentName.toLowerCase()) {
1090
- console.log(`[sdk] Received deregister command. Shutting down...`);
1091
- await this.disconnect();
1092
- process.exit(0);
1093
- }
1648
+ if (payload.type === "meta") {
1649
+ if (!payload._clientId) return;
1650
+ this.rememberMeta(payload.messageId, {
1651
+ clientId: payload._clientId,
1652
+ executionMode: payload.executionMode,
1653
+ attachments: payload.attachments,
1654
+ receivedAt: Date.now()
1655
+ });
1094
1656
  return;
1095
1657
  }
1096
- if (payload.isTaskNotification) return;
1097
1658
  if (payload.type !== "message" && payload.type !== "response") return;
1659
+ if (this.ownMessages.has(payload.messageId)) {
1660
+ this.recordOwnMessage(payload.messageId);
1661
+ return;
1662
+ }
1098
1663
  if (payload.text && payload.text.length > 1e5) {
1099
1664
  console.warn(`[sdk] Ignoring oversized message (${payload.text.length} chars)`);
1100
1665
  return;
1101
1666
  }
1667
+ const isAgent = payload.isAgentMessage === true || !!payload.agentId;
1668
+ const isSelf = !!this.agentId && payload.agentId === this.agentId;
1669
+ this.indexMessage(project.id, payload.messageId, {
1670
+ agentId: payload.agentId,
1671
+ senderName: payload.agentName ?? payload.fromUsername,
1672
+ parentMessageId: payload.parentMessageId
1673
+ });
1674
+ if (!isAgent) this.unthreadedHops.set(project.id, 0);
1102
1675
  this.addToHistory(project.id, {
1103
- sender: payload.isAgentMessage ? "agent" : "user",
1676
+ sender: isAgent ? "agent" : "user",
1104
1677
  senderName: payload.fromUsername,
1105
- text: payload.text
1678
+ text: payload.text,
1679
+ agentId: payload.agentId
1106
1680
  });
1107
- const depth = payload.responseDepth ?? 0;
1108
- const chain = payload.respondingChain ?? [];
1681
+ if (isSelf) return;
1682
+ if (payload.isTaskNotification) return;
1683
+ let depth = 0;
1684
+ let chain = [];
1685
+ let executionMode = payload.executionMode;
1686
+ let attachments = payload.attachments;
1687
+ if (isAgent) {
1688
+ if (payload.type !== "response") return;
1689
+ ({ depth, chain } = this.agentChainFor(project.id, payload));
1690
+ if (!payload.parentMessageId) {
1691
+ const n = (this.unthreadedHops.get(project.id) ?? 0) + 1;
1692
+ this.unthreadedHops.set(project.id, n);
1693
+ if (n > this.maxDepth) return;
1694
+ }
1695
+ } else {
1696
+ const meta = this.takeMeta(payload.messageId, payload.from);
1697
+ executionMode = executionMode ?? meta?.executionMode;
1698
+ attachments = attachments ?? meta?.attachments;
1699
+ }
1109
1700
  if (!this.shouldRespond(payload.text, depth, chain)) return;
1110
1701
  if (this.activeResponses.has(payload.messageId)) return;
1111
1702
  this.activeResponses.add(payload.messageId);
1112
1703
  try {
1113
- await this.respondToMessage(payload, project, depth, chain);
1704
+ await this.respondToMessage(payload, project, depth, chain, executionMode, attachments);
1114
1705
  } catch (err) {
1115
- console.error("[sdk] Error responding to message:", err);
1116
- this.emit("error", err);
1706
+ this.emitError(err);
1117
1707
  } finally {
1118
1708
  this.activeResponses.delete(payload.messageId);
1119
1709
  }
@@ -1123,26 +1713,27 @@ var JaibberAgent = class extends import_events.EventEmitter {
1123
1713
  * Mirrors useAbly.ts shouldAgentRespond() logic.
1124
1714
  */
1125
1715
  shouldRespond(text, depth, chain) {
1126
- const maxDepth = this.config.maxResponseDepth ?? DEFAULT_MAX_DEPTH;
1127
- if (depth >= maxDepth) return false;
1716
+ if (depth >= this.maxDepth) return false;
1128
1717
  if (chain.includes(this.config.agentName.toLowerCase())) return false;
1129
1718
  if (!mentionsAgent(text, this.config.agentName)) return false;
1130
1719
  return true;
1131
1720
  }
1132
- async respondToMessage(payload, project, incomingDepth, incomingChain) {
1133
- const userId = this.client.userId;
1721
+ async respondToMessage(payload, project, incomingDepth, incomingChain, executionMode, attachments) {
1134
1722
  const conversationHistory = this.getFormattedHistory(project.id);
1135
1723
  const ctx = new MessageContext({
1136
1724
  projectId: project.id,
1137
1725
  channelName: project.ablyChannelName,
1138
1726
  conversationHistory,
1139
1727
  ablyManager: this.ablyManager,
1140
- userId,
1728
+ from: this.senderId,
1729
+ agentId: this.agentId,
1141
1730
  agentName: this.config.agentName,
1142
1731
  client: this.client,
1732
+ incomingMessageId: payload.messageId,
1143
1733
  incomingDepth,
1144
1734
  incomingChain,
1145
- chunkBatchMs: this.config.chunkBatchMs ?? DEFAULT_CHUNK_BATCH_MS
1735
+ chunkBatchMs: this.config.chunkBatchMs ?? DEFAULT_CHUNK_BATCH_MS,
1736
+ tracker: this.tracker
1146
1737
  });
1147
1738
  if (this.messageHandler) {
1148
1739
  await this.messageHandler(
@@ -1155,20 +1746,30 @@ var JaibberAgent = class extends import_events.EventEmitter {
1155
1746
  type: payload.type,
1156
1747
  responseDepth: incomingDepth,
1157
1748
  respondingChain: incomingChain,
1158
- executionMode: payload.executionMode,
1749
+ executionMode,
1159
1750
  isAgentMessage: payload.isAgentMessage,
1160
- attachments: payload.attachments
1751
+ agentId: payload.agentId,
1752
+ agentName: payload.agentName,
1753
+ mentions: payload.mentions,
1754
+ parentMessageId: payload.parentMessageId,
1755
+ attachments,
1756
+ createdAt: payload.createdAt
1161
1757
  },
1162
1758
  ctx
1163
1759
  );
1760
+ if (ctx.error !== void 0) this.emitError(ctx.error);
1164
1761
  return;
1165
1762
  }
1166
1763
  if (this.provider) {
1167
1764
  this.updateProviderSession(project.id);
1168
- const systemPrompt = this.config.agentInstructions ?? "";
1765
+ const systemPrompt = this.systemPromptFor(executionMode);
1169
1766
  await ctx.stream(
1170
1767
  () => this.provider.generate(payload.text, systemPrompt, conversationHistory)
1171
1768
  );
1769
+ if (ctx.error !== void 0) {
1770
+ this.emitError(ctx.error);
1771
+ return;
1772
+ }
1172
1773
  this.captureProviderSession(project.id);
1173
1774
  return;
1174
1775
  }
@@ -1176,36 +1777,54 @@ var JaibberAgent = class extends import_events.EventEmitter {
1176
1777
  "[sdk] No message handler or provider configured. Ignoring message."
1177
1778
  );
1178
1779
  }
1780
+ /** Agent instructions, prefixed with the plan-mode directive when requested. */
1781
+ systemPromptFor(executionMode) {
1782
+ const instructions = this.config.agentInstructions ?? "";
1783
+ if (executionMode !== "plan") return instructions;
1784
+ return instructions ? `${PLAN_MODE_PREFIX}
1785
+
1786
+ ${instructions}` : PLAN_MODE_PREFIX;
1787
+ }
1788
+ // ── Agent control (server-published lifecycle commands) ─────────────
1789
+ /** Is a server control event addressed to this agent? */
1790
+ isControlForMe(data) {
1791
+ if (this.agentId) return data.agentId === this.agentId;
1792
+ return !!data.agentName && data.agentName.toLowerCase() === this.config.agentName.toLowerCase();
1793
+ }
1794
+ /**
1795
+ * `agent-control` events are published by the server on project channels,
1796
+ * e.g. `{action: "deregister", agentId, agentName}` when an agent is revoked
1797
+ * via the API. Events for other agents are ignored.
1798
+ */
1799
+ async handleControlEvent(data, project) {
1800
+ if (!data || data.action !== "deregister") return;
1801
+ if (!this.isControlForMe(data)) return;
1802
+ console.log(
1803
+ `[sdk] Agent "${this.config.agentName}" was deregistered by the server (via project "${project.name}"). Shutting down...`
1804
+ );
1805
+ try {
1806
+ await this.disconnect();
1807
+ } catch (err) {
1808
+ console.error("[sdk] Error during deregister shutdown:", err);
1809
+ }
1810
+ this.emit("deregistered", data);
1811
+ if (this.config.exitOnDeregister !== false) {
1812
+ process.exit(0);
1813
+ }
1814
+ }
1179
1815
  // ── Task handling ───────────────────────────────────────────────────
1180
1816
  async handleTaskEvent(data, project) {
1181
1817
  if (data.type !== "task-created" && data.type !== "task-updated")
1182
1818
  return;
1183
1819
  const task = data.task;
1184
1820
  if (task.status !== "submitted") return;
1185
- if (!task.assignedAgentName || task.assignedAgentName.toLowerCase() !== this.config.agentName.toLowerCase())
1186
- 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;
1187
1823
  console.log(
1188
1824
  `[sdk] Picking up task: "${task.title}" (${task.id})`
1189
1825
  );
1190
1826
  try {
1191
1827
  await this.client.updateTask(task.id, { status: "working" });
1192
- const userId = this.client.userId;
1193
- const announceMsgId = (0, import_uuid2.v4)();
1194
- await this.ablyManager.publish(
1195
- project.ablyChannelName,
1196
- "message",
1197
- {
1198
- from: userId,
1199
- fromUsername: this.config.agentName,
1200
- projectId: project.id,
1201
- text: `Picking up task: **${task.title}**`,
1202
- messageId: announceMsgId,
1203
- type: "message",
1204
- agentName: this.config.agentName,
1205
- isAgentMessage: true,
1206
- isTaskNotification: true
1207
- }
1208
- );
1209
1828
  const conversationHistory = this.getFormattedHistory(project.id);
1210
1829
  const ctx = new TaskContext({
1211
1830
  task,
@@ -1213,10 +1832,19 @@ var JaibberAgent = class extends import_events.EventEmitter {
1213
1832
  channelName: project.ablyChannelName,
1214
1833
  conversationHistory,
1215
1834
  ablyManager: this.ablyManager,
1216
- userId,
1835
+ from: this.senderId,
1836
+ agentId: this.agentId,
1217
1837
  agentName: this.config.agentName,
1218
- client: this.client
1838
+ client: this.client,
1839
+ tracker: this.tracker
1219
1840
  });
1841
+ try {
1842
+ await ctx.sendMessage(`Picking up task: **${task.title}**`, { type: "message" });
1843
+ } catch (err) {
1844
+ console.warn(
1845
+ `[sdk] Could not announce task pickup: ${err instanceof Error ? err.message : err}`
1846
+ );
1847
+ }
1220
1848
  if (this.taskHandler) {
1221
1849
  await this.taskHandler(task, ctx);
1222
1850
  return;
@@ -1232,33 +1860,36 @@ ${task.description}` : `Task: ${task.title}`;
1232
1860
  channelName: project.ablyChannelName,
1233
1861
  conversationHistory,
1234
1862
  ablyManager: this.ablyManager,
1235
- userId,
1863
+ from: this.senderId,
1864
+ agentId: this.agentId,
1236
1865
  agentName: this.config.agentName,
1237
1866
  client: this.client,
1238
1867
  incomingDepth: 0,
1239
1868
  incomingChain: [],
1240
- chunkBatchMs: this.config.chunkBatchMs ?? DEFAULT_CHUNK_BATCH_MS
1869
+ chunkBatchMs: this.config.chunkBatchMs ?? DEFAULT_CHUNK_BATCH_MS,
1870
+ tracker: this.tracker
1241
1871
  });
1242
- try {
1243
- await msgCtx.stream(
1244
- () => this.provider.generate(
1245
- taskPrompt,
1246
- systemPrompt,
1247
- conversationHistory
1248
- )
1249
- );
1250
- this.captureProviderSession(project.id);
1251
- await this.client.updateTask(task.id, { status: "completed" });
1252
- } 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);
1253
1881
  await this.client.updateTask(task.id, { status: "failed" });
1882
+ return;
1254
1883
  }
1884
+ this.captureProviderSession(project.id);
1885
+ await this.client.updateTask(task.id, { status: "completed" });
1255
1886
  return;
1256
1887
  }
1257
1888
  console.warn(
1258
1889
  "[sdk] No task handler or provider configured. Task left as working."
1259
1890
  );
1260
1891
  } catch (err) {
1261
- console.error("[sdk] Error handling task:", err);
1892
+ this.emitError(err);
1262
1893
  try {
1263
1894
  await this.client.updateTask(task.id, { status: "failed" });
1264
1895
  } catch {
@@ -1287,6 +1918,11 @@ ${task.description}` : `Task: ${task.title}`;
1287
1918
  }
1288
1919
  }
1289
1920
  // ── Conversation history ────────────────────────────────────────────
1921
+ /** Is this stored message one of this agent's own prior replies? */
1922
+ isOwnServerMessage(m) {
1923
+ if (this.agentId && m.senderAgentId === this.agentId) return true;
1924
+ return m.senderType === "agent" && m.senderName.toLowerCase() === this.config.agentName.toLowerCase();
1925
+ }
1290
1926
  async loadHistory(projectId) {
1291
1927
  const contextSize = this.config.contextWindowSize ?? DEFAULT_CONTEXT_WINDOW;
1292
1928
  try {
@@ -1294,12 +1930,30 @@ ${task.description}` : `Task: ${task.title}`;
1294
1930
  projectId,
1295
1931
  contextSize
1296
1932
  );
1297
- const entries = messages.reverse().map((m) => ({
1298
- sender: m.senderType === "user" ? "user" : "agent",
1299
- senderName: m.senderName,
1300
- text: m.text
1301
- }));
1302
- this.history.set(projectId, entries);
1933
+ const first = messages[0];
1934
+ const last = messages[messages.length - 1];
1935
+ if (first && last && first !== last && first.createdAt > last.createdAt) {
1936
+ messages.reverse();
1937
+ }
1938
+ const entries = [];
1939
+ for (const m of messages) {
1940
+ const own = this.isOwnServerMessage(m);
1941
+ const agentId = m.senderAgentId ?? (own ? this.agentId ?? void 0 : void 0);
1942
+ this.indexMessage(projectId, m.id, {
1943
+ agentId,
1944
+ senderName: own ? this.config.agentName : m.senderName,
1945
+ parentMessageId: m.parentMessageId ?? void 0
1946
+ });
1947
+ if (m.type === "system" || !m.text) continue;
1948
+ const sender = own || m.senderType === "agent" ? "agent" : "user";
1949
+ entries.push({
1950
+ sender,
1951
+ senderName: own ? this.config.agentName : m.senderName,
1952
+ text: m.text,
1953
+ agentId
1954
+ });
1955
+ }
1956
+ this.history.set(projectId, entries.slice(-contextSize));
1303
1957
  } catch (err) {
1304
1958
  console.error(
1305
1959
  `[sdk] Failed to load history for project ${projectId}:`,
@@ -1319,7 +1973,7 @@ ${task.description}` : `Task: ${task.title}`;
1319
1973
  }
1320
1974
  /**
1321
1975
  * Format conversation history for LLM context.
1322
- * Matches useAbly.ts lines 77-84 format.
1976
+ * Matches useAbly.ts format: `User: text` / `Assistant (Name): text`.
1323
1977
  */
1324
1978
  getFormattedHistory(projectId) {
1325
1979
  const entries = this.history.get(projectId) ?? [];
@@ -1385,9 +2039,12 @@ function getTemplate(id) {
1385
2039
  ClaudeCLIProvider,
1386
2040
  GoogleProvider,
1387
2041
  JaibberAgent,
2042
+ JaibberClient,
1388
2043
  MessageContext,
1389
2044
  OpenAIProvider,
1390
2045
  TaskContext,
1391
- getTemplate
2046
+ getTemplate,
2047
+ mentionsAgent,
2048
+ parseMentions
1392
2049
  });
1393
2050
  //# sourceMappingURL=index.cjs.map