@jaibber/sdk 0.3.8 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.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,284 @@ 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
+ }
107
172
  // ── Projects ────────────────────────────────────────────────────────
108
- /** GET /api/projects — list all projects user is member of. */
173
+ /**
174
+ * GET /api/projects — with a session: projects the user is a member of
175
+ * (plus org-admin-visible ones with role "org-admin"); with an agent key:
176
+ * the agent's assigned projects.
177
+ */
109
178
  async listProjects() {
110
- const res = await fetch(`${this.serverUrl}/api/projects`, {
111
- headers: this.authHeaders()
179
+ const res = await this.request("GET", "/api/projects", void 0, "Failed to list projects");
180
+ const json = await res.json();
181
+ const rows = json.projects ?? json.data ?? [];
182
+ return rows.map((p) => mapProject(p, this.apiKey ? "agent" : "member"));
183
+ }
184
+ /** POST /api/projects — create a new project (session only), returns it. */
185
+ async createProject(name, description, orgId) {
186
+ const res = await this.request(
187
+ "POST",
188
+ "/api/projects",
189
+ { name, description, ...orgId ? { orgId } : {} },
190
+ "Failed to create project"
191
+ );
192
+ const json = await res.json();
193
+ const p = json.project ?? json.data;
194
+ if (!p) throw new Error("Failed to create project: malformed response");
195
+ return mapProject(p, "admin");
196
+ }
197
+ // ── Agents (/api/me/agents) ─────────────────────────────────────────
198
+ /**
199
+ * POST /api/me/agents — idempotent upsert of an agent hosted by the
200
+ * logged-in user, keyed by (org, lower(name)). Session only.
201
+ */
202
+ async ensureAgent(input) {
203
+ const body = { name: input.name, kind: input.kind };
204
+ if (input.instructions !== void 0) body.instructions = input.instructions;
205
+ if (input.provider) body.provider = input.provider;
206
+ if (input.machineName) body.machineName = input.machineName;
207
+ if (input.projectId) body.projectId = input.projectId;
208
+ if (input.orgId) body.orgId = input.orgId;
209
+ const res = await fetch(`${this.serverUrl}/api/me/agents`, {
210
+ method: "POST",
211
+ headers: this.authHeaders(),
212
+ body: JSON.stringify(body)
112
213
  });
113
214
  if (!res.ok) {
114
- const text = await res.text();
115
- throw new Error(`Failed to list projects (${res.status}): ${text}`);
215
+ const text = await readError(res);
216
+ if (res.status === 404) {
217
+ throw new Error(
218
+ "This Jaibber server does not support agent registration (POST /api/me/agents \u2192 404). Upgrade the server, or use @jaibber/sdk 0.3.x."
219
+ );
220
+ }
221
+ throw new Error(`Failed to register agent (${res.status}): ${text}`);
116
222
  }
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`, {
223
+ const json = await res.json();
224
+ return json.data;
225
+ }
226
+ /** GET /api/me/agents — agents hosted by the logged-in user (with assignments). */
227
+ async listMyAgents() {
228
+ const res = await this.request("GET", "/api/me/agents", void 0, "Failed to list agents");
229
+ const json = await res.json();
230
+ return json.data;
231
+ }
232
+ /** POST /api/me/agents/:id/assignments — assign an agent to a project (idempotent). */
233
+ async assignAgent(agentId, projectId) {
234
+ const res = await fetch(`${this.serverUrl}/api/me/agents/${agentId}/assignments`, {
129
235
  method: "POST",
130
236
  headers: this.authHeaders(),
131
- body: JSON.stringify({ name, description })
237
+ body: JSON.stringify({ projectId })
132
238
  });
133
- if (!res.ok) {
134
- const text = await res.text();
135
- throw new Error(`Failed to create project (${res.status}): ${text}`);
239
+ if (!res.ok && res.status !== 409) {
240
+ const text = await readError(res);
241
+ throw new Error(`Failed to assign agent to project ${projectId} (${res.status}): ${text}`);
136
242
  }
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
- };
243
+ }
244
+ /** DELETE /api/me/agents/:id/assignments?projectId= — remove an assignment. */
245
+ async unassignAgent(agentId, projectId) {
246
+ const res = await this.request(
247
+ "DELETE",
248
+ `/api/me/agents/${agentId}/assignments?projectId=${encodeURIComponent(projectId)}`,
249
+ void 0,
250
+ "Failed to unassign agent"
251
+ );
252
+ const json = await res.json().catch(() => ({}));
253
+ return json.data?.removed ?? true;
254
+ }
255
+ /** POST /api/me/agents/:id/keys — mint an agent-bound API key. The raw key is returned once. */
256
+ async createAgentKey(agentId, name) {
257
+ const res = await this.request(
258
+ "POST",
259
+ `/api/me/agents/${agentId}/keys`,
260
+ name ? { name } : {},
261
+ "Failed to create agent API key"
262
+ );
263
+ const json = await res.json();
264
+ return json.data;
265
+ }
266
+ /** POST /api/agents/:id/heartbeat — refresh lastSeenAt (host session or the agent's own key). */
267
+ async heartbeat(agentId) {
268
+ const res = await this.request(
269
+ "POST",
270
+ `/api/agents/${agentId}/heartbeat`,
271
+ void 0,
272
+ "Heartbeat"
273
+ );
274
+ const json = await res.json();
275
+ return json.data;
145
276
  }
146
277
  // ── Ably token ──────────────────────────────────────────────────────
147
278
  /** POST /api/ably/token — get scoped Ably TokenRequest. */
148
279
  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
- }
280
+ const res = await this.request("POST", "/api/ably/token", void 0, "Failed to get Ably token");
157
281
  return res.json();
158
282
  }
159
283
  // ── Messages ────────────────────────────────────────────────────────
160
284
  /**
161
- * POST /api/projects/{id}/messages — persist a message (idempotent).
162
- * Passing a client-generated `id` makes the server skip Ably re-publish.
285
+ * POST /api/projects/{id}/messages — persist a message. This is the only
286
+ * write path for final messages: the server publishes the echo to Ably
287
+ * itself. Idempotent on `id` (201 on create, 200 if it already existed).
288
+ *
289
+ * Identity is derived server-side: in session mode pass `agentId` to post
290
+ * as that hosted agent; with an agent key it is implied.
291
+ *
292
+ * Retries once on network errors / 5xx (safe: ids are idempotent).
163
293
  */
164
294
  async persistMessage(projectId, msg) {
165
- const res = await fetch(
166
- `${this.serverUrl}/api/projects/${projectId}/messages`,
167
- {
295
+ const body = { text: msg.text };
296
+ if (msg.id) body.id = msg.id;
297
+ if (msg.agentId) body.agentId = msg.agentId;
298
+ if (msg.type) body.type = msg.type;
299
+ if (msg.parentMessageId) body.parentMessageId = msg.parentMessageId;
300
+ if (msg.mentions?.length) body.mentions = msg.mentions;
301
+ const attempt = async () => {
302
+ const res = await fetch(`${this.serverUrl}/api/projects/${projectId}/messages`, {
168
303
  method: "POST",
169
304
  headers: this.authHeaders(),
170
- body: JSON.stringify(msg)
305
+ body: JSON.stringify(body)
306
+ });
307
+ if (!res.ok) {
308
+ const text = await readError(res);
309
+ const err = new Error(`Failed to persist message (${res.status}): ${text}`);
310
+ err.status = res.status;
311
+ throw err;
171
312
  }
172
- );
173
- if (!res.ok) {
174
- const text = await res.text();
175
- console.error(
176
- `[sdk] Failed to persist message (${res.status}): ${text}`
177
- );
313
+ const json = await res.json();
314
+ return json.data;
315
+ };
316
+ try {
317
+ return await attempt();
318
+ } catch (err) {
319
+ const status = err.status;
320
+ const retryable = status === void 0 || status >= 500 || status === 429;
321
+ if (!retryable) throw err;
322
+ await new Promise((r) => setTimeout(r, 1e3));
323
+ return attempt();
178
324
  }
179
325
  }
180
- /** GET /api/projects/{id}/messages — fetch recent messages. */
326
+ /** GET /api/projects/{id}/messages — fetch recent messages (oldest first). */
181
327
  async fetchMessages(projectId, limit = 20) {
182
- const res = await fetch(
183
- `${this.serverUrl}/api/projects/${projectId}/messages?limit=${limit}`,
184
- { headers: this.authHeaders() }
328
+ const res = await this.request(
329
+ "GET",
330
+ `/api/projects/${projectId}/messages?limit=${limit}`,
331
+ void 0,
332
+ "Failed to fetch messages"
185
333
  );
186
- if (!res.ok) {
187
- const text = await res.text();
188
- throw new Error(`Failed to fetch messages (${res.status}): ${text}`);
189
- }
190
334
  const data = await res.json();
191
335
  return data.data;
192
336
  }
193
337
  // ── Tasks ───────────────────────────────────────────────────────────
194
338
  /** POST /api/projects/{id}/tasks — create a task. */
195
339
  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
- }
340
+ const res = await this.request(
341
+ "POST",
342
+ `/api/projects/${projectId}/tasks`,
343
+ data,
344
+ "Failed to create task"
203
345
  );
204
- if (!res.ok) {
205
- const text = await res.text();
206
- throw new Error(`Failed to create task (${res.status}): ${text}`);
207
- }
208
346
  const result = await res.json();
209
347
  return result.data;
210
348
  }
211
- /** PATCH /api/tasks/{taskId} — update task fields. */
349
+ /** PATCH /api/tasks/{taskId} — update task fields. Returns the updated task. */
212
350
  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
- }
351
+ const res = await this.request(
352
+ "PATCH",
353
+ `/api/tasks/${taskId}`,
354
+ updates,
355
+ "Failed to update task"
356
+ );
357
+ const result = await res.json();
358
+ return result.data;
222
359
  }
223
360
  };
224
361
 
225
362
  // src/ably-manager.ts
226
363
  var import_ably = __toESM(require("ably"), 1);
364
+ var CONNECT_TIMEOUT_MS = 3e4;
227
365
  var AblyManager = class {
228
- constructor(client, userId, username) {
366
+ constructor(client, opts) {
229
367
  this.client = client;
230
- this.userId = userId;
231
- this.username = username;
368
+ this.opts = opts;
232
369
  }
233
370
  ably = null;
234
371
  channels = /* @__PURE__ */ new Map();
235
372
  presenceChannel = null;
236
373
  /** Create Ably Realtime client with token auth callback. */
237
- async connect() {
374
+ async connect(timeoutMs = CONNECT_TIMEOUT_MS) {
238
375
  return new Promise((resolve, reject) => {
376
+ let lastAuthError = null;
377
+ let settled = false;
378
+ const finish = (fn) => {
379
+ if (settled) return;
380
+ settled = true;
381
+ clearTimeout(timer);
382
+ fn();
383
+ };
384
+ const timer = setTimeout(() => {
385
+ finish(() => {
386
+ this.ably?.close();
387
+ this.ably = null;
388
+ reject(
389
+ new Error(
390
+ `Ably connection timed out after ${Math.round(timeoutMs / 1e3)}s` + (lastAuthError ? ` (last auth error: ${lastAuthError.message})` : "")
391
+ )
392
+ );
393
+ });
394
+ }, timeoutMs);
239
395
  this.ably = new import_ably.default.Realtime({
240
396
  authCallback: async (_tokenParams, callback) => {
241
397
  try {
242
398
  const tokenRequest = await this.client.getAblyToken();
243
399
  callback(null, tokenRequest);
244
400
  } catch (err) {
245
- callback(err, null);
401
+ lastAuthError = err instanceof Error ? err : new Error(String(err));
402
+ callback(lastAuthError.message, null);
246
403
  }
247
404
  },
248
- clientId: this.userId,
405
+ ...this.opts.clientId ? { clientId: this.opts.clientId } : {},
249
406
  disconnectedRetryTimeout: 5e3,
250
407
  // 5s initial retry on disconnect
251
408
  suspendedRetryTimeout: 3e4
252
409
  // 30s retry when suspended
253
410
  });
254
411
  this.ably.connection.once("connected", () => {
255
- resolve();
412
+ finish(resolve);
256
413
  });
257
414
  this.ably.connection.once("failed", (stateChange) => {
258
- reject(
259
- new Error(
260
- `Ably connection failed: ${stateChange?.reason?.message ?? "unknown"}`
415
+ finish(
416
+ () => reject(
417
+ new Error(
418
+ `Ably connection failed: ${stateChange?.reason?.message ?? lastAuthError?.message ?? "unknown"}`
419
+ )
261
420
  )
262
421
  );
263
422
  });
@@ -275,20 +434,22 @@ var AblyManager = class {
275
434
  });
276
435
  }
277
436
  /** Enter global presence channel (jaibber:presence). */
278
- async enterGlobalPresence(projectIds) {
437
+ async enterGlobalPresence(data) {
279
438
  if (!this.ably) throw new Error("Ably not connected");
280
439
  this.presenceChannel = this.ably.channels.get("jaibber:presence");
281
440
  await this.presenceChannel.presence.enter({
282
- userId: this.userId,
283
- username: this.username,
284
- projectIds
441
+ ...data.userId ? { userId: data.userId } : {},
442
+ ...data.agentId ? { agentId: data.agentId } : {},
443
+ username: data.username,
444
+ projectIds: data.projectIds
285
445
  });
286
446
  }
287
447
  /**
288
- * Subscribe to a project channel and enter per-project presence.
448
+ * Subscribe to a project channel (`message`, `task` and server-published
449
+ * `agent-control` events) and enter per-project presence.
289
450
  * Returns an unsubscribe function.
290
451
  */
291
- async subscribeToProject(project, presenceData, onMessage, onTask) {
452
+ async subscribeToProject(project, presenceData, onMessage, onTask, onControl) {
292
453
  if (!this.ably) throw new Error("Ably not connected");
293
454
  const channel = this.ably.channels.get(project.ablyChannelName);
294
455
  this.channels.set(project.ablyChannelName, channel);
@@ -297,20 +458,31 @@ var AblyManager = class {
297
458
  if (!msg.data) return;
298
459
  const payload = msg.data;
299
460
  payload._connectionId = msg.connectionId ?? void 0;
461
+ payload._clientId = msg.clientId ?? void 0;
300
462
  onMessage(payload);
301
463
  };
302
464
  const taskHandler = (msg) => {
303
465
  if (!msg.data) return;
304
466
  onTask(msg.data);
305
467
  };
468
+ const controlHandler = (msg) => {
469
+ if (!msg.data || typeof msg.data !== "object") return;
470
+ onControl?.(msg.data);
471
+ };
306
472
  channel.subscribe("message", messageHandler);
307
473
  channel.subscribe("task", taskHandler);
474
+ channel.subscribe("agent-control", controlHandler);
308
475
  return () => {
309
476
  channel.unsubscribe("message", messageHandler);
310
477
  channel.unsubscribe("task", taskHandler);
478
+ channel.unsubscribe("agent-control", controlHandler);
311
479
  };
312
480
  }
313
- /** Publish a message on a project channel. */
481
+ /**
482
+ * Publish a client-side event on a project channel. Only `typing` and
483
+ * `chunk` are client-published; final messages go through the REST API
484
+ * and are echoed by the server.
485
+ */
314
486
  async publish(channelName, eventName, data) {
315
487
  const channel = this.channels.get(channelName);
316
488
  if (!channel) {
@@ -322,6 +494,10 @@ var AblyManager = class {
322
494
  get connectionId() {
323
495
  return this.ably?.connection.id;
324
496
  }
497
+ /** The clientId this connection authenticated as (from the token in API-key mode). */
498
+ get clientId() {
499
+ return this.ably?.auth.clientId ?? void 0;
500
+ }
325
501
  /** Leave presence on all channels and close the connection. */
326
502
  async disconnect() {
327
503
  for (const channel of this.channels.values()) {
@@ -352,44 +528,69 @@ var MessageContext = class {
352
528
  conversationHistory;
353
529
  /** The project ID this message was received on. */
354
530
  projectId;
355
- responseId;
531
+ /** The agent's server-side id (sent as `agentId` on every save). */
532
+ agentId;
533
+ /** The agent's display name. */
534
+ agentName;
535
+ /** Id of the message being responded to (if any). */
536
+ incomingMessageId;
537
+ /**
538
+ * The id the final reply will be stored under. Also the `responseId` sent
539
+ * with `typing` so clients can pre-create the bubble.
540
+ */
541
+ messageId;
356
542
  ablyManager;
357
543
  channelName;
358
- userId;
359
- agentName;
544
+ from;
360
545
  client;
361
546
  responseDepth;
362
547
  respondingChain;
363
548
  chunkBatchMs;
549
+ tracker;
364
550
  constructor(opts) {
365
551
  this.projectId = opts.projectId;
366
552
  this.channelName = opts.channelName;
367
553
  this.conversationHistory = opts.conversationHistory;
368
554
  this.ablyManager = opts.ablyManager;
369
- this.userId = opts.userId;
555
+ this.from = opts.from;
556
+ this.agentId = opts.agentId;
370
557
  this.agentName = opts.agentName;
371
558
  this.client = opts.client;
559
+ this.incomingMessageId = opts.incomingMessageId;
372
560
  this.responseDepth = opts.incomingDepth + 1;
373
561
  this.respondingChain = [
374
562
  ...opts.incomingChain,
375
563
  opts.agentName.toLowerCase()
376
564
  ];
377
565
  this.chunkBatchMs = opts.chunkBatchMs;
378
- this.responseId = (0, import_uuid.v4)();
566
+ this.tracker = opts.tracker;
567
+ this.messageId = (0, import_uuid.v4)();
379
568
  }
380
- /** One-shot reply: publishes typing → response in sequence. */
381
- async reply(text) {
569
+ /** Agent-to-agent hop count this reply will carry (informational). */
570
+ get depth() {
571
+ return this.responseDepth;
572
+ }
573
+ /** Agents that have already responded in this chain, including this one. */
574
+ get chain() {
575
+ return [...this.respondingChain];
576
+ }
577
+ /** One-shot reply: publishes `typing`, then POSTs the final message. */
578
+ async reply(text, opts) {
382
579
  await this.publishTyping();
383
- await this.publishResponse(text);
384
- this.persistAsync(text, "response");
580
+ return this.persist(this.messageId, text, "response", this.parentFor(opts));
581
+ }
582
+ /** Replies thread under the answered message unless overridden. */
583
+ parentFor(opts) {
584
+ return opts?.parentMessageId ?? this.incomingMessageId;
385
585
  }
386
586
  /**
387
587
  * Streaming reply: consumes an async generator, batches chunks to Ably
388
- * every chunkBatchMs (default 200ms), then publishes the final response.
588
+ * every chunkBatchMs (default 200ms), then POSTs the final message.
589
+ * Resolves with the full response text.
389
590
  *
390
- * Mirrors useAbly.ts lines 86-102 chunk batching pattern.
591
+ * Mirrors useAbly.ts chunk batching pattern.
391
592
  */
392
- async stream(generator) {
593
+ async stream(generator, opts) {
393
594
  await this.publishTyping();
394
595
  let fullText = "";
395
596
  let chunkBuffer = "";
@@ -413,162 +614,141 @@ var MessageContext = class {
413
614
  }
414
615
  if (flushTimer) clearTimeout(flushTimer);
415
616
  await flushChunks();
416
- await this.publishResponse(fullText);
417
- this.persistAsync(fullText, "response");
418
617
  } catch (err) {
419
618
  if (flushTimer) clearTimeout(flushTimer);
420
619
  const errText = `Agent error: ${err instanceof Error ? err.message : String(err)}`;
421
- await this.publishError(errText);
422
- this.persistAsync(errText, "error");
620
+ await this.persist(this.messageId, errText, "error", this.parentFor(opts)).catch((e) => {
621
+ console.error("[sdk] Failed to persist error message:", e);
622
+ });
623
+ throw err;
423
624
  }
625
+ await this.persist(this.messageId, fullText, "response", this.parentFor(opts));
626
+ return fullText;
424
627
  }
425
628
  // ── Internal publish helpers ────────────────────────────────────────
426
629
  async publishTyping() {
427
630
  await this.ablyManager.publish(this.channelName, "message", {
428
- from: this.userId,
631
+ from: this.from,
429
632
  fromUsername: this.agentName,
430
633
  projectId: this.projectId,
431
634
  text: "",
432
635
  messageId: (0, import_uuid.v4)(),
433
- responseId: this.responseId,
636
+ responseId: this.messageId,
434
637
  type: "typing",
435
- agentName: this.agentName
638
+ agentName: this.agentName,
639
+ agentId: this.agentId
436
640
  });
437
641
  }
438
642
  async publishChunk(text) {
439
643
  await this.ablyManager.publish(this.channelName, "message", {
440
- from: this.userId,
644
+ from: this.from,
441
645
  fromUsername: this.agentName,
442
646
  projectId: this.projectId,
443
647
  text,
444
- messageId: this.responseId,
648
+ messageId: this.messageId,
445
649
  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
650
  agentName: this.agentName,
458
- isAgentMessage: true,
459
- responseDepth: this.responseDepth,
460
- respondingChain: this.respondingChain
651
+ agentId: this.agentId
461
652
  });
462
653
  }
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
- });
473
- }
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
- });
654
+ /** POST the final message. Throws if the server rejects it. */
655
+ async persist(id, text, type, parentMessageId) {
656
+ this.tracker?.begin(id, this.projectId, text, type, parentMessageId);
657
+ try {
658
+ const saved = await this.client.persistMessage(this.projectId, {
659
+ id,
660
+ agentId: this.agentId,
661
+ type,
662
+ text,
663
+ parentMessageId
664
+ });
665
+ this.tracker?.posted(id);
666
+ return saved;
667
+ } catch (err) {
668
+ this.tracker?.failed(id);
669
+ throw err;
670
+ }
485
671
  }
486
672
  };
487
673
  var TaskContext = class {
488
674
  task;
489
675
  projectId;
490
676
  conversationHistory;
491
- ablyManager;
492
- channelName;
493
- userId;
677
+ agentId;
494
678
  agentName;
495
679
  client;
680
+ tracker;
496
681
  constructor(opts) {
497
682
  this.task = opts.task;
498
683
  this.projectId = opts.projectId;
499
- this.channelName = opts.channelName;
500
684
  this.conversationHistory = opts.conversationHistory;
501
- this.ablyManager = opts.ablyManager;
502
- this.userId = opts.userId;
685
+ this.agentId = opts.agentId;
503
686
  this.agentName = opts.agentName;
504
687
  this.client = opts.client;
688
+ this.tracker = opts.tracker;
505
689
  }
506
- /** Mark task as completed, optionally publishing a response message. */
690
+ /** Mark task as completed, optionally posting a response message. */
507
691
  async complete(resultText) {
508
692
  await this.client.updateTask(this.task.id, { status: "completed" });
509
693
  if (resultText) {
510
694
  await this.sendMessage(resultText);
511
695
  }
512
696
  }
513
- /** Mark task as failed, optionally publishing an error message. */
697
+ /** Mark task as failed, optionally posting an error message. */
514
698
  async fail(errorText) {
515
699
  await this.client.updateTask(this.task.id, { status: "failed" });
516
700
  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));
701
+ await this.sendMessage(errorText, { type: "error" });
534
702
  }
535
703
  }
536
704
  /**
537
705
  * Create a follow-up task assigned to another agent.
538
- * Automatically sets parentTaskId to the current task's ID.
706
+ * Automatically sets parentTaskId to the current task's ID and attributes
707
+ * creation to this agent.
539
708
  */
540
709
  async createFollowUpTask(data) {
541
710
  return this.client.createTask(this.projectId, {
542
711
  ...data,
543
712
  parentTaskId: this.task.id,
544
713
  createdByType: "agent",
545
- createdByName: this.agentName
714
+ createdByName: this.agentName,
715
+ createdByAgentId: this.agentId
546
716
  });
547
717
  }
548
- /** Send a chat message (for progress updates). */
549
- async sendMessage(text) {
718
+ /**
719
+ * Post a chat message (for progress updates). Returns the stored message.
720
+ * `type` defaults to "response"; use "message" for notices that must never
721
+ * trigger other agents (agent-to-agent chaining only flows through responses).
722
+ */
723
+ async sendMessage(text, opts) {
550
724
  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));
725
+ const type = opts?.type ?? "response";
726
+ this.tracker?.begin(msgId, this.projectId, text, type, opts?.parentMessageId);
727
+ try {
728
+ const saved = await this.client.persistMessage(this.projectId, {
729
+ id: msgId,
730
+ agentId: this.agentId,
731
+ type,
732
+ text,
733
+ parentMessageId: opts?.parentMessageId
734
+ });
735
+ this.tracker?.posted(msgId);
736
+ return saved;
737
+ } catch (err) {
738
+ this.tracker?.failed(msgId);
739
+ throw err;
740
+ }
568
741
  }
569
742
  };
570
743
 
571
744
  // src/mentions.ts
745
+ function parseMentions(text) {
746
+ const mentions = [];
747
+ for (const match of text.matchAll(/@(\w+(?:\s+\w+)*)/g)) {
748
+ mentions.push(match[1].toLowerCase());
749
+ }
750
+ return mentions;
751
+ }
572
752
  function mentionsAgent(text, agentName) {
573
753
  const pattern = new RegExp(`@${escapeRegex(agentName)}(?!\\w)`, "i");
574
754
  return pattern.test(text);
@@ -969,6 +1149,11 @@ ${systemPrompt}
969
1149
  var DEFAULT_MAX_DEPTH = 3;
970
1150
  var DEFAULT_CHUNK_BATCH_MS = 200;
971
1151
  var DEFAULT_CONTEXT_WINDOW = 20;
1152
+ var DEFAULT_HEARTBEAT_MS = 12e4;
1153
+ var OWN_MESSAGE_MEMORY = 1e3;
1154
+ var MESSAGE_INDEX_SIZE = 500;
1155
+ var META_TTL_MS = 5 * 60 * 1e3;
1156
+ 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.";
972
1157
  var JaibberAgent = class extends import_events.EventEmitter {
973
1158
  config;
974
1159
  client;
@@ -976,75 +1161,189 @@ var JaibberAgent = class extends import_events.EventEmitter {
976
1161
  messageHandler = null;
977
1162
  taskHandler = null;
978
1163
  provider = null;
1164
+ providerKind = null;
979
1165
  connected = false;
980
1166
  projects = [];
981
1167
  unsubscribers = [];
1168
+ heartbeatTimer = null;
1169
+ agentId = null;
1170
+ agentRecord = null;
982
1171
  /** In-memory conversation history per project. */
983
1172
  history = /* @__PURE__ */ new Map();
1173
+ /** Recent messages per project (id → author/parent) for chain reconstruction. */
1174
+ messageIndex = /* @__PURE__ */ new Map();
984
1175
  /** Track in-flight responses to prevent double-handling. */
985
1176
  activeResponses = /* @__PURE__ */ new Set();
986
1177
  /** Session IDs per project for Claude --resume. */
987
1178
  sessionIds = /* @__PURE__ */ new Map();
1179
+ /** Messages we POSTed ourselves, keyed by id — for echo dedupe + own-reply history. */
1180
+ ownMessages = /* @__PURE__ */ new Map();
1181
+ /** `meta` hints waiting for their server echo. */
1182
+ pendingMeta = /* @__PURE__ */ new Map();
1183
+ /**
1184
+ * Safety valve: unthreaded agent responses (no `parentMessageId`) seen per
1185
+ * project since the last human message. Threaded chains are bounded by the
1186
+ * `parentMessageId` walk; this catches agents that post without threading,
1187
+ * which would otherwise look like a fresh depth-1 chain every time.
1188
+ */
1189
+ unthreadedHops = /* @__PURE__ */ new Map();
988
1190
  constructor(config) {
989
1191
  super();
990
1192
  this.config = config;
991
1193
  this.client = new JaibberClient(config.serverUrl);
992
1194
  }
1195
+ // ── Accessors ───────────────────────────────────────────────────────
1196
+ /** The agent's server-side id (available after `connect()`). */
1197
+ get id() {
1198
+ return this.agentId;
1199
+ }
1200
+ /** The agent record returned by the server (session mode only). */
1201
+ get record() {
1202
+ return this.agentRecord;
1203
+ }
1204
+ /** The underlying REST client (authenticated after `connect()`). */
1205
+ get api() {
1206
+ return this.client;
1207
+ }
1208
+ /** Projects this agent has joined. */
1209
+ get joinedProjects() {
1210
+ return [...this.projects];
1211
+ }
1212
+ /** Sender id used on client-published typing/chunk events. */
1213
+ get senderId() {
1214
+ return this.client.userId ?? `agent:${this.agentId ?? "unknown"}`;
1215
+ }
1216
+ get maxDepth() {
1217
+ return this.config.maxResponseDepth ?? DEFAULT_MAX_DEPTH;
1218
+ }
993
1219
  // ── Lifecycle ───────────────────────────────────────────────────────
994
- /** Authenticate, connect Ably, subscribe to project channels. */
1220
+ /** Authenticate, register/resolve the agent, connect Ably, subscribe to project channels. */
995
1221
  async connect() {
996
1222
  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;
1223
+ const creds = this.config.credentials;
1224
+ const apiKeyMode = "apiKey" in creds;
1225
+ if (apiKeyMode) {
1226
+ this.client.setApiKey(creds.apiKey);
1227
+ this.agentId = this.config.agentId ?? null;
1228
+ console.log(`[sdk] Authenticating with agent API key ${creds.apiKey.slice(0, 11)}\u2026`);
1229
+ } else {
1230
+ console.log(`[sdk] Logging in as "${creds.username}"...`);
1231
+ await this.client.login(creds.username, creds.password);
1232
+ const record = await this.client.ensureAgent({
1233
+ name: this.config.agentName,
1234
+ instructions: this.config.agentInstructions,
1235
+ provider: this.resolveProviderKind(),
1236
+ kind: "sdk",
1237
+ machineName: this.config.machineName,
1238
+ orgId: this.config.orgId
1239
+ });
1240
+ this.agentId = record.id;
1241
+ this.agentRecord = record;
1242
+ this.config.agentId = record.id;
1243
+ console.log(`[sdk] Agent "${record.name}" registered (id ${record.id})`);
1244
+ }
1002
1245
  const allProjects = await this.client.listProjects();
1003
- this.projects = this.config.projectIds ? allProjects.filter((p) => this.config.projectIds.includes(p.id)) : allProjects;
1246
+ if (this.config.projectIds) {
1247
+ const wanted = new Set(this.config.projectIds);
1248
+ this.projects = allProjects.filter((p) => wanted.has(p.id));
1249
+ const missing = this.config.projectIds.filter(
1250
+ (id) => !this.projects.some((p) => p.id === id)
1251
+ );
1252
+ if (missing.length > 0) {
1253
+ console.warn(`[sdk] Project(s) not accessible, skipping: ${missing.join(", ")}`);
1254
+ }
1255
+ } else {
1256
+ this.projects = allProjects.filter((p) => p.role !== "org-admin");
1257
+ }
1004
1258
  if (this.projects.length === 0) {
1005
1259
  throw new Error(
1006
- "No projects found. Ensure the agent account is a member of at least one project."
1260
+ 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
1261
  );
1008
1262
  }
1009
1263
  console.log(
1010
1264
  `[sdk] Found ${this.projects.length} project(s): ${this.projects.map((p) => p.name).join(", ")}`
1011
1265
  );
1012
- this.ablyManager = new AblyManager(this.client, userId, displayName);
1266
+ if (!apiKeyMode) {
1267
+ for (const project of this.projects) {
1268
+ try {
1269
+ await this.client.assignAgent(this.agentId, project.id);
1270
+ } catch (err) {
1271
+ console.warn(
1272
+ `[sdk] Could not assign agent to "${project.name}": ${err instanceof Error ? err.message : err}`
1273
+ );
1274
+ }
1275
+ }
1276
+ }
1277
+ this.ablyManager = new AblyManager(this.client, {
1278
+ clientId: apiKeyMode ? void 0 : this.client.userId,
1279
+ username: this.config.agentName
1280
+ });
1013
1281
  await this.ablyManager.connect();
1014
- await this.ablyManager.enterGlobalPresence(
1015
- this.projects.map((p) => p.id)
1016
- );
1017
- for (const project of this.projects) {
1282
+ try {
1283
+ if (!this.agentId) {
1284
+ const cid = this.ablyManager.clientId;
1285
+ if (cid && cid.startsWith("agent:")) {
1286
+ this.agentId = cid.slice("agent:".length);
1287
+ this.config.agentId = this.agentId;
1288
+ } else {
1289
+ throw new Error(
1290
+ `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\`.`
1291
+ );
1292
+ }
1293
+ }
1294
+ this.startHeartbeat();
1295
+ await this.ablyManager.enterGlobalPresence({
1296
+ userId: this.client.userId ?? void 0,
1297
+ agentId: this.agentId,
1298
+ username: this.config.agentName,
1299
+ projectIds: this.projects.map((p) => p.id)
1300
+ });
1018
1301
  const presenceData = {
1019
- userId,
1302
+ userId: this.client.userId ?? void 0,
1020
1303
  username: this.config.agentName,
1021
1304
  isAgent: true,
1022
1305
  agentName: this.config.agentName,
1306
+ agentId: this.agentId,
1023
1307
  agentInstructions: this.config.agentInstructions,
1024
1308
  agents: [
1025
1309
  {
1310
+ agentId: this.agentId,
1026
1311
  agentName: this.config.agentName,
1027
1312
  agentInstructions: this.config.agentInstructions
1028
1313
  }
1029
1314
  ],
1030
1315
  machineName: this.config.machineName
1031
1316
  };
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);
1317
+ for (const project of this.projects) {
1318
+ await this.loadHistory(project.id);
1319
+ const unsub = await this.ablyManager.subscribeToProject(
1320
+ project,
1321
+ presenceData,
1322
+ (msg) => this.handleIncomingMessage(msg, project),
1323
+ (data) => this.handleTaskEvent(data, project),
1324
+ (data) => this.handleControlEvent(data, project)
1325
+ );
1326
+ this.unsubscribers.push(unsub);
1327
+ }
1328
+ } catch (err) {
1329
+ this.stopHeartbeat();
1330
+ for (const unsub of this.unsubscribers) unsub();
1331
+ this.unsubscribers = [];
1332
+ await this.ablyManager.disconnect().catch(() => {
1333
+ });
1334
+ this.ablyManager = null;
1335
+ throw err;
1040
1336
  }
1041
1337
  this.connected = true;
1042
- console.log(`[sdk] Agent "${this.config.agentName}" connected and listening`);
1338
+ console.log(
1339
+ `[sdk] Agent "${this.config.agentName}" (${this.agentId}) connected and listening`
1340
+ );
1043
1341
  this.emit("connected", this.projects);
1044
1342
  }
1045
- /** Leave presence, disconnect Ably. */
1343
+ /** Stop heartbeats, leave presence, disconnect Ably. */
1046
1344
  async disconnect() {
1047
1345
  if (!this.connected) return;
1346
+ this.stopHeartbeat();
1048
1347
  for (const unsub of this.unsubscribers) {
1049
1348
  unsub();
1050
1349
  }
@@ -1069,48 +1368,190 @@ var JaibberAgent = class extends import_events.EventEmitter {
1069
1368
  switch (name) {
1070
1369
  case "anthropic":
1071
1370
  this.provider = new AnthropicProvider(options);
1371
+ this.providerKind = "claude";
1072
1372
  break;
1073
1373
  case "openai":
1074
1374
  this.provider = new OpenAIProvider(options);
1375
+ this.providerKind = "openai";
1075
1376
  break;
1076
1377
  case "google":
1077
1378
  this.provider = new GoogleProvider(options);
1379
+ this.providerKind = "google";
1078
1380
  break;
1079
1381
  case "claude-cli":
1080
1382
  this.provider = new ClaudeCLIProvider(options);
1383
+ this.providerKind = "claude";
1081
1384
  break;
1082
1385
  }
1083
1386
  }
1387
+ /** Provider label stored on the agent record. */
1388
+ resolveProviderKind() {
1389
+ return this.config.provider ?? this.providerKind ?? "custom";
1390
+ }
1391
+ // ── Heartbeat ───────────────────────────────────────────────────────
1392
+ startHeartbeat() {
1393
+ this.stopHeartbeat();
1394
+ const beat = async () => {
1395
+ if (!this.agentId) return;
1396
+ try {
1397
+ await this.client.heartbeat(this.agentId);
1398
+ } catch (err) {
1399
+ console.warn(`[sdk] Heartbeat failed: ${err instanceof Error ? err.message : err}`);
1400
+ }
1401
+ };
1402
+ void beat();
1403
+ this.heartbeatTimer = setInterval(beat, this.config.heartbeatMs ?? DEFAULT_HEARTBEAT_MS);
1404
+ this.heartbeatTimer.unref?.();
1405
+ }
1406
+ stopHeartbeat() {
1407
+ if (this.heartbeatTimer) {
1408
+ clearInterval(this.heartbeatTimer);
1409
+ this.heartbeatTimer = null;
1410
+ }
1411
+ }
1412
+ // ── Message index / chain reconstruction ────────────────────────────
1413
+ indexMessage(projectId, id, entry) {
1414
+ const idx = this.messageIndex.get(projectId) ?? /* @__PURE__ */ new Map();
1415
+ idx.delete(id);
1416
+ idx.set(id, entry);
1417
+ while (idx.size > MESSAGE_INDEX_SIZE) {
1418
+ const oldest = idx.keys().next().value;
1419
+ if (oldest === void 0) break;
1420
+ idx.delete(oldest);
1421
+ }
1422
+ this.messageIndex.set(projectId, idx);
1423
+ }
1424
+ /**
1425
+ * Loop prevention for agent-to-agent chains. The server echo carries no
1426
+ * chain metadata, so the chain is reconstructed from `parentMessageId`
1427
+ * links: every agent response is posted as a reply to the message it
1428
+ * answered. Returns the number of consecutive agent hops ending at
1429
+ * `payload` (the depth) and the lowercased names of the agents in that run.
1430
+ * Mirrors useAbly.ts agentChainFor().
1431
+ */
1432
+ agentChainFor(projectId, payload) {
1433
+ const idx = this.messageIndex.get(projectId);
1434
+ const chain = [(payload.agentName ?? payload.fromUsername).toLowerCase()];
1435
+ let parentId = payload.parentMessageId;
1436
+ let guard = 0;
1437
+ while (parentId && guard++ < 50) {
1438
+ const parent = idx?.get(parentId);
1439
+ if (!parent?.agentId) break;
1440
+ chain.push(parent.senderName.toLowerCase());
1441
+ parentId = parent.parentMessageId;
1442
+ }
1443
+ return { depth: chain.length, chain };
1444
+ }
1445
+ // ── `meta` hints ────────────────────────────────────────────────────
1446
+ rememberMeta(messageId, meta) {
1447
+ const cutoff = Date.now() - META_TTL_MS;
1448
+ for (const [id, m] of this.pendingMeta) {
1449
+ if (m.receivedAt < cutoff) this.pendingMeta.delete(id);
1450
+ }
1451
+ this.pendingMeta.set(messageId, meta);
1452
+ }
1453
+ takeMeta(messageId, senderId) {
1454
+ const meta = this.pendingMeta.get(messageId);
1455
+ if (!meta) return void 0;
1456
+ this.pendingMeta.delete(messageId);
1457
+ return meta.clientId === senderId ? meta : void 0;
1458
+ }
1459
+ // ── Own-message tracking (echo dedupe + own replies in history) ─────
1460
+ tracker = {
1461
+ begin: (id, projectId, text, type, parentMessageId) => {
1462
+ this.ownMessages.set(id, { projectId, text, type, recorded: false });
1463
+ while (this.ownMessages.size > OWN_MESSAGE_MEMORY) {
1464
+ const oldest = this.ownMessages.keys().next().value;
1465
+ if (oldest === void 0) break;
1466
+ this.ownMessages.delete(oldest);
1467
+ }
1468
+ this.indexMessage(projectId, id, {
1469
+ agentId: this.agentId ?? void 0,
1470
+ senderName: this.config.agentName,
1471
+ parentMessageId
1472
+ });
1473
+ },
1474
+ posted: (id) => this.recordOwnMessage(id),
1475
+ failed: (id) => {
1476
+ this.ownMessages.delete(id);
1477
+ }
1478
+ };
1479
+ /**
1480
+ * Add one of our own messages to history exactly once — whichever arrives
1481
+ * first: the server's Ably echo or the POST response.
1482
+ */
1483
+ recordOwnMessage(id) {
1484
+ const own = this.ownMessages.get(id);
1485
+ if (!own || own.recorded) return;
1486
+ own.recorded = true;
1487
+ if (own.type === "error") return;
1488
+ this.addToHistory(own.projectId, {
1489
+ sender: "agent",
1490
+ senderName: this.config.agentName,
1491
+ text: own.text,
1492
+ agentId: this.agentId ?? void 0
1493
+ });
1494
+ }
1084
1495
  // ── Message handling ────────────────────────────────────────────────
1085
1496
  async handleIncomingMessage(payload, project) {
1086
1497
  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
- }
1498
+ if (payload.type === "meta") {
1499
+ if (!payload._clientId) return;
1500
+ this.rememberMeta(payload.messageId, {
1501
+ clientId: payload._clientId,
1502
+ executionMode: payload.executionMode,
1503
+ attachments: payload.attachments,
1504
+ receivedAt: Date.now()
1505
+ });
1094
1506
  return;
1095
1507
  }
1096
- if (payload.isTaskNotification) return;
1097
1508
  if (payload.type !== "message" && payload.type !== "response") return;
1509
+ if (this.ownMessages.has(payload.messageId)) {
1510
+ this.recordOwnMessage(payload.messageId);
1511
+ return;
1512
+ }
1098
1513
  if (payload.text && payload.text.length > 1e5) {
1099
1514
  console.warn(`[sdk] Ignoring oversized message (${payload.text.length} chars)`);
1100
1515
  return;
1101
1516
  }
1517
+ const isAgent = payload.isAgentMessage === true || !!payload.agentId;
1518
+ const isSelf = !!this.agentId && payload.agentId === this.agentId;
1519
+ this.indexMessage(project.id, payload.messageId, {
1520
+ agentId: payload.agentId,
1521
+ senderName: payload.agentName ?? payload.fromUsername,
1522
+ parentMessageId: payload.parentMessageId
1523
+ });
1524
+ if (!isAgent) this.unthreadedHops.set(project.id, 0);
1102
1525
  this.addToHistory(project.id, {
1103
- sender: payload.isAgentMessage ? "agent" : "user",
1526
+ sender: isAgent ? "agent" : "user",
1104
1527
  senderName: payload.fromUsername,
1105
- text: payload.text
1528
+ text: payload.text,
1529
+ agentId: payload.agentId
1106
1530
  });
1107
- const depth = payload.responseDepth ?? 0;
1108
- const chain = payload.respondingChain ?? [];
1531
+ if (isSelf) return;
1532
+ if (payload.isTaskNotification) return;
1533
+ let depth = 0;
1534
+ let chain = [];
1535
+ let executionMode = payload.executionMode;
1536
+ let attachments = payload.attachments;
1537
+ if (isAgent) {
1538
+ if (payload.type !== "response") return;
1539
+ ({ depth, chain } = this.agentChainFor(project.id, payload));
1540
+ if (!payload.parentMessageId) {
1541
+ const n = (this.unthreadedHops.get(project.id) ?? 0) + 1;
1542
+ this.unthreadedHops.set(project.id, n);
1543
+ if (n > this.maxDepth) return;
1544
+ }
1545
+ } else {
1546
+ const meta = this.takeMeta(payload.messageId, payload.from);
1547
+ executionMode = executionMode ?? meta?.executionMode;
1548
+ attachments = attachments ?? meta?.attachments;
1549
+ }
1109
1550
  if (!this.shouldRespond(payload.text, depth, chain)) return;
1110
1551
  if (this.activeResponses.has(payload.messageId)) return;
1111
1552
  this.activeResponses.add(payload.messageId);
1112
1553
  try {
1113
- await this.respondToMessage(payload, project, depth, chain);
1554
+ await this.respondToMessage(payload, project, depth, chain, executionMode, attachments);
1114
1555
  } catch (err) {
1115
1556
  console.error("[sdk] Error responding to message:", err);
1116
1557
  this.emit("error", err);
@@ -1123,26 +1564,27 @@ var JaibberAgent = class extends import_events.EventEmitter {
1123
1564
  * Mirrors useAbly.ts shouldAgentRespond() logic.
1124
1565
  */
1125
1566
  shouldRespond(text, depth, chain) {
1126
- const maxDepth = this.config.maxResponseDepth ?? DEFAULT_MAX_DEPTH;
1127
- if (depth >= maxDepth) return false;
1567
+ if (depth >= this.maxDepth) return false;
1128
1568
  if (chain.includes(this.config.agentName.toLowerCase())) return false;
1129
1569
  if (!mentionsAgent(text, this.config.agentName)) return false;
1130
1570
  return true;
1131
1571
  }
1132
- async respondToMessage(payload, project, incomingDepth, incomingChain) {
1133
- const userId = this.client.userId;
1572
+ async respondToMessage(payload, project, incomingDepth, incomingChain, executionMode, attachments) {
1134
1573
  const conversationHistory = this.getFormattedHistory(project.id);
1135
1574
  const ctx = new MessageContext({
1136
1575
  projectId: project.id,
1137
1576
  channelName: project.ablyChannelName,
1138
1577
  conversationHistory,
1139
1578
  ablyManager: this.ablyManager,
1140
- userId,
1579
+ from: this.senderId,
1580
+ agentId: this.agentId,
1141
1581
  agentName: this.config.agentName,
1142
1582
  client: this.client,
1583
+ incomingMessageId: payload.messageId,
1143
1584
  incomingDepth,
1144
1585
  incomingChain,
1145
- chunkBatchMs: this.config.chunkBatchMs ?? DEFAULT_CHUNK_BATCH_MS
1586
+ chunkBatchMs: this.config.chunkBatchMs ?? DEFAULT_CHUNK_BATCH_MS,
1587
+ tracker: this.tracker
1146
1588
  });
1147
1589
  if (this.messageHandler) {
1148
1590
  await this.messageHandler(
@@ -1155,9 +1597,14 @@ var JaibberAgent = class extends import_events.EventEmitter {
1155
1597
  type: payload.type,
1156
1598
  responseDepth: incomingDepth,
1157
1599
  respondingChain: incomingChain,
1158
- executionMode: payload.executionMode,
1600
+ executionMode,
1159
1601
  isAgentMessage: payload.isAgentMessage,
1160
- attachments: payload.attachments
1602
+ agentId: payload.agentId,
1603
+ agentName: payload.agentName,
1604
+ mentions: payload.mentions,
1605
+ parentMessageId: payload.parentMessageId,
1606
+ attachments,
1607
+ createdAt: payload.createdAt
1161
1608
  },
1162
1609
  ctx
1163
1610
  );
@@ -1165,7 +1612,7 @@ var JaibberAgent = class extends import_events.EventEmitter {
1165
1612
  }
1166
1613
  if (this.provider) {
1167
1614
  this.updateProviderSession(project.id);
1168
- const systemPrompt = this.config.agentInstructions ?? "";
1615
+ const systemPrompt = this.systemPromptFor(executionMode);
1169
1616
  await ctx.stream(
1170
1617
  () => this.provider.generate(payload.text, systemPrompt, conversationHistory)
1171
1618
  );
@@ -1176,36 +1623,55 @@ var JaibberAgent = class extends import_events.EventEmitter {
1176
1623
  "[sdk] No message handler or provider configured. Ignoring message."
1177
1624
  );
1178
1625
  }
1626
+ /** Agent instructions, prefixed with the plan-mode directive when requested. */
1627
+ systemPromptFor(executionMode) {
1628
+ const instructions = this.config.agentInstructions ?? "";
1629
+ if (executionMode !== "plan") return instructions;
1630
+ return instructions ? `${PLAN_MODE_PREFIX}
1631
+
1632
+ ${instructions}` : PLAN_MODE_PREFIX;
1633
+ }
1634
+ // ── Agent control (server-published lifecycle commands) ─────────────
1635
+ /** Is a server control event addressed to this agent? */
1636
+ isControlForMe(data) {
1637
+ if (this.agentId) return data.agentId === this.agentId;
1638
+ return !!data.agentName && data.agentName.toLowerCase() === this.config.agentName.toLowerCase();
1639
+ }
1640
+ /**
1641
+ * `agent-control` events are published by the server on project channels,
1642
+ * e.g. `{action: "deregister", agentId, agentName}` when an agent is revoked
1643
+ * via the API. Events for other agents are ignored.
1644
+ */
1645
+ async handleControlEvent(data, project) {
1646
+ if (!data || data.action !== "deregister") return;
1647
+ if (!this.isControlForMe(data)) return;
1648
+ console.log(
1649
+ `[sdk] Agent "${this.config.agentName}" was deregistered by the server (via project "${project.name}"). Shutting down...`
1650
+ );
1651
+ try {
1652
+ await this.disconnect();
1653
+ } catch (err) {
1654
+ console.error("[sdk] Error during deregister shutdown:", err);
1655
+ }
1656
+ this.emit("deregistered", data);
1657
+ if (this.config.exitOnDeregister !== false) {
1658
+ process.exit(0);
1659
+ }
1660
+ }
1179
1661
  // ── Task handling ───────────────────────────────────────────────────
1180
1662
  async handleTaskEvent(data, project) {
1181
1663
  if (data.type !== "task-created" && data.type !== "task-updated")
1182
1664
  return;
1183
1665
  const task = data.task;
1184
1666
  if (task.status !== "submitted") return;
1185
- if (!task.assignedAgentName || task.assignedAgentName.toLowerCase() !== this.config.agentName.toLowerCase())
1186
- return;
1667
+ const assignedById = !!task.assignedAgentId && !!this.agentId && task.assignedAgentId === this.agentId;
1668
+ const assignedByName = !!task.assignedAgentName && task.assignedAgentName.toLowerCase() === this.config.agentName.toLowerCase();
1669
+ if (!assignedById && !assignedByName) return;
1187
1670
  console.log(
1188
1671
  `[sdk] Picking up task: "${task.title}" (${task.id})`
1189
1672
  );
1190
1673
  try {
1191
1674
  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
1675
  const conversationHistory = this.getFormattedHistory(project.id);
1210
1676
  const ctx = new TaskContext({
1211
1677
  task,
@@ -1213,10 +1679,19 @@ var JaibberAgent = class extends import_events.EventEmitter {
1213
1679
  channelName: project.ablyChannelName,
1214
1680
  conversationHistory,
1215
1681
  ablyManager: this.ablyManager,
1216
- userId,
1682
+ from: this.senderId,
1683
+ agentId: this.agentId,
1217
1684
  agentName: this.config.agentName,
1218
- client: this.client
1685
+ client: this.client,
1686
+ tracker: this.tracker
1219
1687
  });
1688
+ try {
1689
+ await ctx.sendMessage(`Picking up task: **${task.title}**`, { type: "message" });
1690
+ } catch (err) {
1691
+ console.warn(
1692
+ `[sdk] Could not announce task pickup: ${err instanceof Error ? err.message : err}`
1693
+ );
1694
+ }
1220
1695
  if (this.taskHandler) {
1221
1696
  await this.taskHandler(task, ctx);
1222
1697
  return;
@@ -1232,12 +1707,14 @@ ${task.description}` : `Task: ${task.title}`;
1232
1707
  channelName: project.ablyChannelName,
1233
1708
  conversationHistory,
1234
1709
  ablyManager: this.ablyManager,
1235
- userId,
1710
+ from: this.senderId,
1711
+ agentId: this.agentId,
1236
1712
  agentName: this.config.agentName,
1237
1713
  client: this.client,
1238
1714
  incomingDepth: 0,
1239
1715
  incomingChain: [],
1240
- chunkBatchMs: this.config.chunkBatchMs ?? DEFAULT_CHUNK_BATCH_MS
1716
+ chunkBatchMs: this.config.chunkBatchMs ?? DEFAULT_CHUNK_BATCH_MS,
1717
+ tracker: this.tracker
1241
1718
  });
1242
1719
  try {
1243
1720
  await msgCtx.stream(
@@ -1287,6 +1764,11 @@ ${task.description}` : `Task: ${task.title}`;
1287
1764
  }
1288
1765
  }
1289
1766
  // ── Conversation history ────────────────────────────────────────────
1767
+ /** Is this stored message one of this agent's own prior replies? */
1768
+ isOwnServerMessage(m) {
1769
+ if (this.agentId && m.senderAgentId === this.agentId) return true;
1770
+ return m.senderType === "agent" && m.senderName.toLowerCase() === this.config.agentName.toLowerCase();
1771
+ }
1290
1772
  async loadHistory(projectId) {
1291
1773
  const contextSize = this.config.contextWindowSize ?? DEFAULT_CONTEXT_WINDOW;
1292
1774
  try {
@@ -1294,12 +1776,30 @@ ${task.description}` : `Task: ${task.title}`;
1294
1776
  projectId,
1295
1777
  contextSize
1296
1778
  );
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);
1779
+ const first = messages[0];
1780
+ const last = messages[messages.length - 1];
1781
+ if (first && last && first !== last && first.createdAt > last.createdAt) {
1782
+ messages.reverse();
1783
+ }
1784
+ const entries = [];
1785
+ for (const m of messages) {
1786
+ const own = this.isOwnServerMessage(m);
1787
+ const agentId = m.senderAgentId ?? (own ? this.agentId ?? void 0 : void 0);
1788
+ this.indexMessage(projectId, m.id, {
1789
+ agentId,
1790
+ senderName: own ? this.config.agentName : m.senderName,
1791
+ parentMessageId: m.parentMessageId ?? void 0
1792
+ });
1793
+ if (m.type === "system" || !m.text) continue;
1794
+ const sender = own || m.senderType === "agent" ? "agent" : "user";
1795
+ entries.push({
1796
+ sender,
1797
+ senderName: own ? this.config.agentName : m.senderName,
1798
+ text: m.text,
1799
+ agentId
1800
+ });
1801
+ }
1802
+ this.history.set(projectId, entries.slice(-contextSize));
1303
1803
  } catch (err) {
1304
1804
  console.error(
1305
1805
  `[sdk] Failed to load history for project ${projectId}:`,
@@ -1319,7 +1819,7 @@ ${task.description}` : `Task: ${task.title}`;
1319
1819
  }
1320
1820
  /**
1321
1821
  * Format conversation history for LLM context.
1322
- * Matches useAbly.ts lines 77-84 format.
1822
+ * Matches useAbly.ts format: `User: text` / `Assistant (Name): text`.
1323
1823
  */
1324
1824
  getFormattedHistory(projectId) {
1325
1825
  const entries = this.history.get(projectId) ?? [];
@@ -1385,9 +1885,12 @@ function getTemplate(id) {
1385
1885
  ClaudeCLIProvider,
1386
1886
  GoogleProvider,
1387
1887
  JaibberAgent,
1888
+ JaibberClient,
1388
1889
  MessageContext,
1389
1890
  OpenAIProvider,
1390
1891
  TaskContext,
1391
- getTemplate
1892
+ getTemplate,
1893
+ mentionsAgent,
1894
+ parseMentions
1392
1895
  });
1393
1896
  //# sourceMappingURL=index.cjs.map