@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.js CHANGED
@@ -1,17 +1,58 @@
1
1
  // src/agent.ts
2
2
  import { EventEmitter } from "events";
3
- import { v4 as uuidv42 } from "uuid";
4
3
 
5
4
  // src/client.ts
5
+ var API_KEY_PREFIX = "jb_";
6
+ async function readError(res) {
7
+ const text = await res.text().catch(() => "");
8
+ try {
9
+ const json = JSON.parse(text);
10
+ const err = json?.error;
11
+ if (typeof err === "string") return err;
12
+ if (err && typeof err === "object") {
13
+ const e = err;
14
+ if (typeof e.message === "string") {
15
+ return e.code ? `${e.code}: ${e.message}` : e.message;
16
+ }
17
+ }
18
+ } catch {
19
+ }
20
+ return text || res.statusText || "Unknown error";
21
+ }
22
+ function mapProject(p, fallbackRole = "member") {
23
+ return {
24
+ id: p.id,
25
+ name: p.name,
26
+ description: p.description ?? null,
27
+ orgId: p.orgId ?? null,
28
+ ablyChannelName: p.ablyChannelName,
29
+ role: p.role ?? fallbackRole
30
+ };
31
+ }
6
32
  var JaibberClient = class {
7
33
  serverUrl;
8
34
  jwt = null;
35
+ apiKey = null;
9
36
  userId = null;
10
37
  username = null;
11
- constructor(serverUrl) {
38
+ constructor(serverUrl, opts) {
12
39
  this.serverUrl = serverUrl.replace(/\/+$/, "");
40
+ if (opts?.apiKey) this.setApiKey(opts.apiKey);
41
+ if (opts?.token) this.jwt = opts.token;
13
42
  }
14
43
  // ── Auth ────────────────────────────────────────────────────────────
44
+ /** Use an API key (`jb_…`) for all requests. An agent-bound key authenticates AS that agent. */
45
+ setApiKey(apiKey) {
46
+ const key = apiKey.trim();
47
+ if (!key.startsWith(API_KEY_PREFIX)) {
48
+ throw new Error(`Invalid Jaibber API key: expected it to start with "${API_KEY_PREFIX}".`);
49
+ }
50
+ this.apiKey = key;
51
+ }
52
+ /** Use an existing session JWT for all requests. */
53
+ setToken(token) {
54
+ this.jwt = token;
55
+ }
15
56
  /** POST /api/auth/register — create a new account, stores JWT. */
16
57
  async register(username, password) {
17
58
  const res = await fetch(`${this.serverUrl}/api/auth/register`, {
@@ -20,7 +61,7 @@ var JaibberClient = class {
20
61
  body: JSON.stringify({ username, password })
21
62
  });
22
63
  if (!res.ok) {
23
- const text = await res.text();
64
+ const text = await readError(res);
24
65
  if (res.status === 409) {
25
66
  throw new Error(`Username "${username}" is already taken.`);
26
67
  }
@@ -39,7 +80,7 @@ var JaibberClient = class {
39
80
  body: JSON.stringify({ username, password })
40
81
  });
41
82
  if (!res.ok) {
42
- const text = await res.text();
83
+ const text = await readError(res);
43
84
  if (res.status === 401) {
44
85
  throw new Error("Invalid credentials. Check username and password.");
45
86
  }
@@ -51,169 +92,284 @@ var JaibberClient = class {
51
92
  this.username = data.username;
52
93
  }
53
94
  get isAuthenticated() {
54
- return this.jwt !== null;
95
+ return this.jwt !== null || this.apiKey !== null;
96
+ }
97
+ /** Which credential requests will carry. */
98
+ get authMode() {
99
+ if (this.apiKey) return "apiKey";
100
+ if (this.jwt) return "session";
101
+ return "none";
55
102
  }
56
103
  authHeaders() {
57
104
  const h = { "Content-Type": "application/json" };
58
- if (this.jwt) {
105
+ if (this.apiKey) {
106
+ h["X-API-Key"] = this.apiKey;
107
+ } else if (this.jwt) {
59
108
  h["Authorization"] = `Bearer ${this.jwt}`;
60
109
  }
61
110
  return h;
62
111
  }
112
+ /** Authenticated fetch with uniform error reporting. */
113
+ async request(method, path, body, what) {
114
+ const res = await fetch(`${this.serverUrl}${path}`, {
115
+ method,
116
+ headers: this.authHeaders(),
117
+ ...body !== void 0 ? { body: JSON.stringify(body) } : {}
118
+ });
119
+ if (!res.ok) {
120
+ const text = await readError(res);
121
+ throw new Error(`${what ?? `${method} ${path}`} failed (${res.status}): ${text}`);
122
+ }
123
+ return res;
124
+ }
63
125
  // ── Projects ────────────────────────────────────────────────────────
64
- /** GET /api/projects — list all projects user is member of. */
126
+ /**
127
+ * GET /api/projects — with a session: projects the user is a member of
128
+ * (plus org-admin-visible ones with role "org-admin"); with an agent key:
129
+ * the agent's assigned projects.
130
+ */
65
131
  async listProjects() {
66
- const res = await fetch(`${this.serverUrl}/api/projects`, {
67
- headers: this.authHeaders()
132
+ const res = await this.request("GET", "/api/projects", void 0, "Failed to list projects");
133
+ const json = await res.json();
134
+ const rows = json.projects ?? json.data ?? [];
135
+ return rows.map((p) => mapProject(p, this.apiKey ? "agent" : "member"));
136
+ }
137
+ /** POST /api/projects — create a new project (session only), returns it. */
138
+ async createProject(name, description, orgId) {
139
+ const res = await this.request(
140
+ "POST",
141
+ "/api/projects",
142
+ { name, description, ...orgId ? { orgId } : {} },
143
+ "Failed to create project"
144
+ );
145
+ const json = await res.json();
146
+ const p = json.project ?? json.data;
147
+ if (!p) throw new Error("Failed to create project: malformed response");
148
+ return mapProject(p, "admin");
149
+ }
150
+ // ── Agents (/api/me/agents) ─────────────────────────────────────────
151
+ /**
152
+ * POST /api/me/agents — idempotent upsert of an agent hosted by the
153
+ * logged-in user, keyed by (org, lower(name)). Session only.
154
+ */
155
+ async ensureAgent(input) {
156
+ const body = { name: input.name, kind: input.kind };
157
+ if (input.instructions !== void 0) body.instructions = input.instructions;
158
+ if (input.provider) body.provider = input.provider;
159
+ if (input.machineName) body.machineName = input.machineName;
160
+ if (input.projectId) body.projectId = input.projectId;
161
+ if (input.orgId) body.orgId = input.orgId;
162
+ const res = await fetch(`${this.serverUrl}/api/me/agents`, {
163
+ method: "POST",
164
+ headers: this.authHeaders(),
165
+ body: JSON.stringify(body)
68
166
  });
69
167
  if (!res.ok) {
70
- const text = await res.text();
71
- throw new Error(`Failed to list projects (${res.status}): ${text}`);
168
+ const text = await readError(res);
169
+ if (res.status === 404) {
170
+ throw new Error(
171
+ "This Jaibber server does not support agent registration (POST /api/me/agents \u2192 404). Upgrade the server, or use @jaibber/sdk 0.3.x."
172
+ );
173
+ }
174
+ throw new Error(`Failed to register agent (${res.status}): ${text}`);
72
175
  }
73
- const data = await res.json();
74
- return data.projects.map((p) => ({
75
- id: p.id,
76
- name: p.name,
77
- description: p.description,
78
- ablyChannelName: p.ablyChannelName,
79
- role: p.role
80
- }));
81
- }
82
- /** POST /api/projects — create a new project, returns it. */
83
- async createProject(name, description) {
84
- const res = await fetch(`${this.serverUrl}/api/projects`, {
176
+ const json = await res.json();
177
+ return json.data;
178
+ }
179
+ /** GET /api/me/agents — agents hosted by the logged-in user (with assignments). */
180
+ async listMyAgents() {
181
+ const res = await this.request("GET", "/api/me/agents", void 0, "Failed to list agents");
182
+ const json = await res.json();
183
+ return json.data;
184
+ }
185
+ /** POST /api/me/agents/:id/assignments — assign an agent to a project (idempotent). */
186
+ async assignAgent(agentId, projectId) {
187
+ const res = await fetch(`${this.serverUrl}/api/me/agents/${agentId}/assignments`, {
85
188
  method: "POST",
86
189
  headers: this.authHeaders(),
87
- body: JSON.stringify({ name, description })
190
+ body: JSON.stringify({ projectId })
88
191
  });
89
- if (!res.ok) {
90
- const text = await res.text();
91
- throw new Error(`Failed to create project (${res.status}): ${text}`);
192
+ if (!res.ok && res.status !== 409) {
193
+ const text = await readError(res);
194
+ throw new Error(`Failed to assign agent to project ${projectId} (${res.status}): ${text}`);
92
195
  }
93
- const data = await res.json();
94
- return {
95
- id: data.project.id,
96
- name: data.project.name,
97
- description: data.project.description,
98
- ablyChannelName: data.project.ablyChannelName,
99
- role: "admin"
100
- };
196
+ }
197
+ /** DELETE /api/me/agents/:id/assignments?projectId= — remove an assignment. */
198
+ async unassignAgent(agentId, projectId) {
199
+ const res = await this.request(
200
+ "DELETE",
201
+ `/api/me/agents/${agentId}/assignments?projectId=${encodeURIComponent(projectId)}`,
202
+ void 0,
203
+ "Failed to unassign agent"
204
+ );
205
+ const json = await res.json().catch(() => ({}));
206
+ return json.data?.removed ?? true;
207
+ }
208
+ /** POST /api/me/agents/:id/keys — mint an agent-bound API key. The raw key is returned once. */
209
+ async createAgentKey(agentId, name) {
210
+ const res = await this.request(
211
+ "POST",
212
+ `/api/me/agents/${agentId}/keys`,
213
+ name ? { name } : {},
214
+ "Failed to create agent API key"
215
+ );
216
+ const json = await res.json();
217
+ return json.data;
218
+ }
219
+ /** POST /api/agents/:id/heartbeat — refresh lastSeenAt (host session or the agent's own key). */
220
+ async heartbeat(agentId) {
221
+ const res = await this.request(
222
+ "POST",
223
+ `/api/agents/${agentId}/heartbeat`,
224
+ void 0,
225
+ "Heartbeat"
226
+ );
227
+ const json = await res.json();
228
+ return json.data;
101
229
  }
102
230
  // ── Ably token ──────────────────────────────────────────────────────
103
231
  /** POST /api/ably/token — get scoped Ably TokenRequest. */
104
232
  async getAblyToken() {
105
- const res = await fetch(`${this.serverUrl}/api/ably/token`, {
106
- method: "POST",
107
- headers: this.authHeaders()
108
- });
109
- if (!res.ok) {
110
- const text = await res.text();
111
- throw new Error(`Failed to get Ably token (${res.status}): ${text}`);
112
- }
233
+ const res = await this.request("POST", "/api/ably/token", void 0, "Failed to get Ably token");
113
234
  return res.json();
114
235
  }
115
236
  // ── Messages ────────────────────────────────────────────────────────
116
237
  /**
117
- * POST /api/projects/{id}/messages — persist a message (idempotent).
118
- * Passing a client-generated `id` makes the server skip Ably re-publish.
238
+ * POST /api/projects/{id}/messages — persist a message. This is the only
239
+ * write path for final messages: the server publishes the echo to Ably
240
+ * itself. Idempotent on `id` (201 on create, 200 if it already existed).
241
+ *
242
+ * Identity is derived server-side: in session mode pass `agentId` to post
243
+ * as that hosted agent; with an agent key it is implied.
244
+ *
245
+ * Retries once on network errors / 5xx (safe: ids are idempotent).
119
246
  */
120
247
  async persistMessage(projectId, msg) {
121
- const res = await fetch(
122
- `${this.serverUrl}/api/projects/${projectId}/messages`,
123
- {
248
+ const body = { text: msg.text };
249
+ if (msg.id) body.id = msg.id;
250
+ if (msg.agentId) body.agentId = msg.agentId;
251
+ if (msg.type) body.type = msg.type;
252
+ if (msg.parentMessageId) body.parentMessageId = msg.parentMessageId;
253
+ if (msg.mentions?.length) body.mentions = msg.mentions;
254
+ const attempt = async () => {
255
+ const res = await fetch(`${this.serverUrl}/api/projects/${projectId}/messages`, {
124
256
  method: "POST",
125
257
  headers: this.authHeaders(),
126
- body: JSON.stringify(msg)
258
+ body: JSON.stringify(body)
259
+ });
260
+ if (!res.ok) {
261
+ const text = await readError(res);
262
+ const err = new Error(`Failed to persist message (${res.status}): ${text}`);
263
+ err.status = res.status;
264
+ throw err;
127
265
  }
128
- );
129
- if (!res.ok) {
130
- const text = await res.text();
131
- console.error(
132
- `[sdk] Failed to persist message (${res.status}): ${text}`
133
- );
266
+ const json = await res.json();
267
+ return json.data;
268
+ };
269
+ try {
270
+ return await attempt();
271
+ } catch (err) {
272
+ const status = err.status;
273
+ const retryable = status === void 0 || status >= 500 || status === 429;
274
+ if (!retryable) throw err;
275
+ await new Promise((r) => setTimeout(r, 1e3));
276
+ return attempt();
134
277
  }
135
278
  }
136
- /** GET /api/projects/{id}/messages — fetch recent messages. */
279
+ /** GET /api/projects/{id}/messages — fetch recent messages (oldest first). */
137
280
  async fetchMessages(projectId, limit = 20) {
138
- const res = await fetch(
139
- `${this.serverUrl}/api/projects/${projectId}/messages?limit=${limit}`,
140
- { headers: this.authHeaders() }
281
+ const res = await this.request(
282
+ "GET",
283
+ `/api/projects/${projectId}/messages?limit=${limit}`,
284
+ void 0,
285
+ "Failed to fetch messages"
141
286
  );
142
- if (!res.ok) {
143
- const text = await res.text();
144
- throw new Error(`Failed to fetch messages (${res.status}): ${text}`);
145
- }
146
287
  const data = await res.json();
147
288
  return data.data;
148
289
  }
149
290
  // ── Tasks ───────────────────────────────────────────────────────────
150
291
  /** POST /api/projects/{id}/tasks — create a task. */
151
292
  async createTask(projectId, data) {
152
- const res = await fetch(
153
- `${this.serverUrl}/api/projects/${projectId}/tasks`,
154
- {
155
- method: "POST",
156
- headers: this.authHeaders(),
157
- body: JSON.stringify(data)
158
- }
293
+ const res = await this.request(
294
+ "POST",
295
+ `/api/projects/${projectId}/tasks`,
296
+ data,
297
+ "Failed to create task"
159
298
  );
160
- if (!res.ok) {
161
- const text = await res.text();
162
- throw new Error(`Failed to create task (${res.status}): ${text}`);
163
- }
164
299
  const result = await res.json();
165
300
  return result.data;
166
301
  }
167
- /** PATCH /api/tasks/{taskId} — update task fields. */
302
+ /** PATCH /api/tasks/{taskId} — update task fields. Returns the updated task. */
168
303
  async updateTask(taskId, updates) {
169
- const res = await fetch(`${this.serverUrl}/api/tasks/${taskId}`, {
170
- method: "PATCH",
171
- headers: this.authHeaders(),
172
- body: JSON.stringify(updates)
173
- });
174
- if (!res.ok) {
175
- const text = await res.text();
176
- console.error(`[sdk] Failed to update task (${res.status}): ${text}`);
177
- }
304
+ const res = await this.request(
305
+ "PATCH",
306
+ `/api/tasks/${taskId}`,
307
+ updates,
308
+ "Failed to update task"
309
+ );
310
+ const result = await res.json();
311
+ return result.data;
178
312
  }
179
313
  };
180
314
 
181
315
  // src/ably-manager.ts
182
316
  import Ably from "ably";
317
+ var CONNECT_TIMEOUT_MS = 3e4;
183
318
  var AblyManager = class {
184
- constructor(client, userId, username) {
319
+ constructor(client, opts) {
185
320
  this.client = client;
186
- this.userId = userId;
187
- this.username = username;
321
+ this.opts = opts;
188
322
  }
189
323
  ably = null;
190
324
  channels = /* @__PURE__ */ new Map();
191
325
  presenceChannel = null;
192
326
  /** Create Ably Realtime client with token auth callback. */
193
- async connect() {
327
+ async connect(timeoutMs = CONNECT_TIMEOUT_MS) {
194
328
  return new Promise((resolve, reject) => {
329
+ let lastAuthError = null;
330
+ let settled = false;
331
+ const finish = (fn) => {
332
+ if (settled) return;
333
+ settled = true;
334
+ clearTimeout(timer);
335
+ fn();
336
+ };
337
+ const timer = setTimeout(() => {
338
+ finish(() => {
339
+ this.ably?.close();
340
+ this.ably = null;
341
+ reject(
342
+ new Error(
343
+ `Ably connection timed out after ${Math.round(timeoutMs / 1e3)}s` + (lastAuthError ? ` (last auth error: ${lastAuthError.message})` : "")
344
+ )
345
+ );
346
+ });
347
+ }, timeoutMs);
195
348
  this.ably = new Ably.Realtime({
196
349
  authCallback: async (_tokenParams, callback) => {
197
350
  try {
198
351
  const tokenRequest = await this.client.getAblyToken();
199
352
  callback(null, tokenRequest);
200
353
  } catch (err) {
201
- callback(err, null);
354
+ lastAuthError = err instanceof Error ? err : new Error(String(err));
355
+ callback(lastAuthError.message, null);
202
356
  }
203
357
  },
204
- clientId: this.userId,
358
+ ...this.opts.clientId ? { clientId: this.opts.clientId } : {},
205
359
  disconnectedRetryTimeout: 5e3,
206
360
  // 5s initial retry on disconnect
207
361
  suspendedRetryTimeout: 3e4
208
362
  // 30s retry when suspended
209
363
  });
210
364
  this.ably.connection.once("connected", () => {
211
- resolve();
365
+ finish(resolve);
212
366
  });
213
367
  this.ably.connection.once("failed", (stateChange) => {
214
- reject(
215
- new Error(
216
- `Ably connection failed: ${stateChange?.reason?.message ?? "unknown"}`
368
+ finish(
369
+ () => reject(
370
+ new Error(
371
+ `Ably connection failed: ${stateChange?.reason?.message ?? lastAuthError?.message ?? "unknown"}`
372
+ )
217
373
  )
218
374
  );
219
375
  });
@@ -231,20 +387,22 @@ var AblyManager = class {
231
387
  });
232
388
  }
233
389
  /** Enter global presence channel (jaibber:presence). */
234
- async enterGlobalPresence(projectIds) {
390
+ async enterGlobalPresence(data) {
235
391
  if (!this.ably) throw new Error("Ably not connected");
236
392
  this.presenceChannel = this.ably.channels.get("jaibber:presence");
237
393
  await this.presenceChannel.presence.enter({
238
- userId: this.userId,
239
- username: this.username,
240
- projectIds
394
+ ...data.userId ? { userId: data.userId } : {},
395
+ ...data.agentId ? { agentId: data.agentId } : {},
396
+ username: data.username,
397
+ projectIds: data.projectIds
241
398
  });
242
399
  }
243
400
  /**
244
- * Subscribe to a project channel and enter per-project presence.
401
+ * Subscribe to a project channel (`message`, `task` and server-published
402
+ * `agent-control` events) and enter per-project presence.
245
403
  * Returns an unsubscribe function.
246
404
  */
247
- async subscribeToProject(project, presenceData, onMessage, onTask) {
405
+ async subscribeToProject(project, presenceData, onMessage, onTask, onControl) {
248
406
  if (!this.ably) throw new Error("Ably not connected");
249
407
  const channel = this.ably.channels.get(project.ablyChannelName);
250
408
  this.channels.set(project.ablyChannelName, channel);
@@ -253,20 +411,31 @@ var AblyManager = class {
253
411
  if (!msg.data) return;
254
412
  const payload = msg.data;
255
413
  payload._connectionId = msg.connectionId ?? void 0;
414
+ payload._clientId = msg.clientId ?? void 0;
256
415
  onMessage(payload);
257
416
  };
258
417
  const taskHandler = (msg) => {
259
418
  if (!msg.data) return;
260
419
  onTask(msg.data);
261
420
  };
421
+ const controlHandler = (msg) => {
422
+ if (!msg.data || typeof msg.data !== "object") return;
423
+ onControl?.(msg.data);
424
+ };
262
425
  channel.subscribe("message", messageHandler);
263
426
  channel.subscribe("task", taskHandler);
427
+ channel.subscribe("agent-control", controlHandler);
264
428
  return () => {
265
429
  channel.unsubscribe("message", messageHandler);
266
430
  channel.unsubscribe("task", taskHandler);
431
+ channel.unsubscribe("agent-control", controlHandler);
267
432
  };
268
433
  }
269
- /** Publish a message on a project channel. */
434
+ /**
435
+ * Publish a client-side event on a project channel. Only `typing` and
436
+ * `chunk` are client-published; final messages go through the REST API
437
+ * and are echoed by the server.
438
+ */
270
439
  async publish(channelName, eventName, data) {
271
440
  const channel = this.channels.get(channelName);
272
441
  if (!channel) {
@@ -278,6 +447,10 @@ var AblyManager = class {
278
447
  get connectionId() {
279
448
  return this.ably?.connection.id;
280
449
  }
450
+ /** The clientId this connection authenticated as (from the token in API-key mode). */
451
+ get clientId() {
452
+ return this.ably?.auth.clientId ?? void 0;
453
+ }
281
454
  /** Leave presence on all channels and close the connection. */
282
455
  async disconnect() {
283
456
  for (const channel of this.channels.values()) {
@@ -308,44 +481,69 @@ var MessageContext = class {
308
481
  conversationHistory;
309
482
  /** The project ID this message was received on. */
310
483
  projectId;
311
- responseId;
484
+ /** The agent's server-side id (sent as `agentId` on every save). */
485
+ agentId;
486
+ /** The agent's display name. */
487
+ agentName;
488
+ /** Id of the message being responded to (if any). */
489
+ incomingMessageId;
490
+ /**
491
+ * The id the final reply will be stored under. Also the `responseId` sent
492
+ * with `typing` so clients can pre-create the bubble.
493
+ */
494
+ messageId;
312
495
  ablyManager;
313
496
  channelName;
314
- userId;
315
- agentName;
497
+ from;
316
498
  client;
317
499
  responseDepth;
318
500
  respondingChain;
319
501
  chunkBatchMs;
502
+ tracker;
320
503
  constructor(opts) {
321
504
  this.projectId = opts.projectId;
322
505
  this.channelName = opts.channelName;
323
506
  this.conversationHistory = opts.conversationHistory;
324
507
  this.ablyManager = opts.ablyManager;
325
- this.userId = opts.userId;
508
+ this.from = opts.from;
509
+ this.agentId = opts.agentId;
326
510
  this.agentName = opts.agentName;
327
511
  this.client = opts.client;
512
+ this.incomingMessageId = opts.incomingMessageId;
328
513
  this.responseDepth = opts.incomingDepth + 1;
329
514
  this.respondingChain = [
330
515
  ...opts.incomingChain,
331
516
  opts.agentName.toLowerCase()
332
517
  ];
333
518
  this.chunkBatchMs = opts.chunkBatchMs;
334
- this.responseId = uuidv4();
519
+ this.tracker = opts.tracker;
520
+ this.messageId = uuidv4();
335
521
  }
336
- /** One-shot reply: publishes typing → response in sequence. */
337
- async reply(text) {
522
+ /** Agent-to-agent hop count this reply will carry (informational). */
523
+ get depth() {
524
+ return this.responseDepth;
525
+ }
526
+ /** Agents that have already responded in this chain, including this one. */
527
+ get chain() {
528
+ return [...this.respondingChain];
529
+ }
530
+ /** One-shot reply: publishes `typing`, then POSTs the final message. */
531
+ async reply(text, opts) {
338
532
  await this.publishTyping();
339
- await this.publishResponse(text);
340
- this.persistAsync(text, "response");
533
+ return this.persist(this.messageId, text, "response", this.parentFor(opts));
534
+ }
535
+ /** Replies thread under the answered message unless overridden. */
536
+ parentFor(opts) {
537
+ return opts?.parentMessageId ?? this.incomingMessageId;
341
538
  }
342
539
  /**
343
540
  * Streaming reply: consumes an async generator, batches chunks to Ably
344
- * every chunkBatchMs (default 200ms), then publishes the final response.
541
+ * every chunkBatchMs (default 200ms), then POSTs the final message.
542
+ * Resolves with the full response text.
345
543
  *
346
- * Mirrors useAbly.ts lines 86-102 chunk batching pattern.
544
+ * Mirrors useAbly.ts chunk batching pattern.
347
545
  */
348
- async stream(generator) {
546
+ async stream(generator, opts) {
349
547
  await this.publishTyping();
350
548
  let fullText = "";
351
549
  let chunkBuffer = "";
@@ -369,162 +567,141 @@ var MessageContext = class {
369
567
  }
370
568
  if (flushTimer) clearTimeout(flushTimer);
371
569
  await flushChunks();
372
- await this.publishResponse(fullText);
373
- this.persistAsync(fullText, "response");
374
570
  } catch (err) {
375
571
  if (flushTimer) clearTimeout(flushTimer);
376
572
  const errText = `Agent error: ${err instanceof Error ? err.message : String(err)}`;
377
- await this.publishError(errText);
378
- this.persistAsync(errText, "error");
573
+ await this.persist(this.messageId, errText, "error", this.parentFor(opts)).catch((e) => {
574
+ console.error("[sdk] Failed to persist error message:", e);
575
+ });
576
+ throw err;
379
577
  }
578
+ await this.persist(this.messageId, fullText, "response", this.parentFor(opts));
579
+ return fullText;
380
580
  }
381
581
  // ── Internal publish helpers ────────────────────────────────────────
382
582
  async publishTyping() {
383
583
  await this.ablyManager.publish(this.channelName, "message", {
384
- from: this.userId,
584
+ from: this.from,
385
585
  fromUsername: this.agentName,
386
586
  projectId: this.projectId,
387
587
  text: "",
388
588
  messageId: uuidv4(),
389
- responseId: this.responseId,
589
+ responseId: this.messageId,
390
590
  type: "typing",
391
- agentName: this.agentName
591
+ agentName: this.agentName,
592
+ agentId: this.agentId
392
593
  });
393
594
  }
394
595
  async publishChunk(text) {
395
596
  await this.ablyManager.publish(this.channelName, "message", {
396
- from: this.userId,
597
+ from: this.from,
397
598
  fromUsername: this.agentName,
398
599
  projectId: this.projectId,
399
600
  text,
400
- messageId: this.responseId,
601
+ messageId: this.messageId,
401
602
  type: "chunk",
402
- agentName: this.agentName
403
- });
404
- }
405
- async publishResponse(text) {
406
- await this.ablyManager.publish(this.channelName, "message", {
407
- from: this.userId,
408
- fromUsername: this.agentName,
409
- projectId: this.projectId,
410
- text,
411
- messageId: this.responseId,
412
- type: "response",
413
603
  agentName: this.agentName,
414
- isAgentMessage: true,
415
- responseDepth: this.responseDepth,
416
- respondingChain: this.respondingChain
604
+ agentId: this.agentId
417
605
  });
418
606
  }
419
- async publishError(text) {
420
- await this.ablyManager.publish(this.channelName, "message", {
421
- from: this.userId,
422
- fromUsername: this.agentName,
423
- projectId: this.projectId,
424
- text,
425
- messageId: this.responseId,
426
- type: "error",
427
- agentName: this.agentName
428
- });
429
- }
430
- /** Fire-and-forget persist to server. */
431
- persistAsync(text, type) {
432
- this.client.persistMessage(this.projectId, {
433
- id: this.responseId,
434
- senderType: "agent",
435
- senderName: this.agentName,
436
- type,
437
- text
438
- }).catch((err) => {
439
- console.error("[sdk] Failed to persist message:", err);
440
- });
607
+ /** POST the final message. Throws if the server rejects it. */
608
+ async persist(id, text, type, parentMessageId) {
609
+ this.tracker?.begin(id, this.projectId, text, type, parentMessageId);
610
+ try {
611
+ const saved = await this.client.persistMessage(this.projectId, {
612
+ id,
613
+ agentId: this.agentId,
614
+ type,
615
+ text,
616
+ parentMessageId
617
+ });
618
+ this.tracker?.posted(id);
619
+ return saved;
620
+ } catch (err) {
621
+ this.tracker?.failed(id);
622
+ throw err;
623
+ }
441
624
  }
442
625
  };
443
626
  var TaskContext = class {
444
627
  task;
445
628
  projectId;
446
629
  conversationHistory;
447
- ablyManager;
448
- channelName;
449
- userId;
630
+ agentId;
450
631
  agentName;
451
632
  client;
633
+ tracker;
452
634
  constructor(opts) {
453
635
  this.task = opts.task;
454
636
  this.projectId = opts.projectId;
455
- this.channelName = opts.channelName;
456
637
  this.conversationHistory = opts.conversationHistory;
457
- this.ablyManager = opts.ablyManager;
458
- this.userId = opts.userId;
638
+ this.agentId = opts.agentId;
459
639
  this.agentName = opts.agentName;
460
640
  this.client = opts.client;
641
+ this.tracker = opts.tracker;
461
642
  }
462
- /** Mark task as completed, optionally publishing a response message. */
643
+ /** Mark task as completed, optionally posting a response message. */
463
644
  async complete(resultText) {
464
645
  await this.client.updateTask(this.task.id, { status: "completed" });
465
646
  if (resultText) {
466
647
  await this.sendMessage(resultText);
467
648
  }
468
649
  }
469
- /** Mark task as failed, optionally publishing an error message. */
650
+ /** Mark task as failed, optionally posting an error message. */
470
651
  async fail(errorText) {
471
652
  await this.client.updateTask(this.task.id, { status: "failed" });
472
653
  if (errorText) {
473
- const msgId = uuidv4();
474
- await this.ablyManager.publish(this.channelName, "message", {
475
- from: this.userId,
476
- fromUsername: this.agentName,
477
- projectId: this.projectId,
478
- text: errorText,
479
- messageId: msgId,
480
- type: "error",
481
- agentName: this.agentName
482
- });
483
- this.client.persistMessage(this.projectId, {
484
- id: msgId,
485
- senderType: "agent",
486
- senderName: this.agentName,
487
- type: "error",
488
- text: errorText
489
- }).catch((err) => console.error("[sdk] Failed to persist:", err));
654
+ await this.sendMessage(errorText, { type: "error" });
490
655
  }
491
656
  }
492
657
  /**
493
658
  * Create a follow-up task assigned to another agent.
494
- * Automatically sets parentTaskId to the current task's ID.
659
+ * Automatically sets parentTaskId to the current task's ID and attributes
660
+ * creation to this agent.
495
661
  */
496
662
  async createFollowUpTask(data) {
497
663
  return this.client.createTask(this.projectId, {
498
664
  ...data,
499
665
  parentTaskId: this.task.id,
500
666
  createdByType: "agent",
501
- createdByName: this.agentName
667
+ createdByName: this.agentName,
668
+ createdByAgentId: this.agentId
502
669
  });
503
670
  }
504
- /** Send a chat message (for progress updates). */
505
- async sendMessage(text) {
671
+ /**
672
+ * Post a chat message (for progress updates). Returns the stored message.
673
+ * `type` defaults to "response"; use "message" for notices that must never
674
+ * trigger other agents (agent-to-agent chaining only flows through responses).
675
+ */
676
+ async sendMessage(text, opts) {
506
677
  const msgId = uuidv4();
507
- await this.ablyManager.publish(this.channelName, "message", {
508
- from: this.userId,
509
- fromUsername: this.agentName,
510
- projectId: this.projectId,
511
- text,
512
- messageId: msgId,
513
- type: "response",
514
- agentName: this.agentName,
515
- isAgentMessage: true
516
- });
517
- this.client.persistMessage(this.projectId, {
518
- id: msgId,
519
- senderType: "agent",
520
- senderName: this.agentName,
521
- type: "response",
522
- text
523
- }).catch((err) => console.error("[sdk] Failed to persist:", err));
678
+ const type = opts?.type ?? "response";
679
+ this.tracker?.begin(msgId, this.projectId, text, type, opts?.parentMessageId);
680
+ try {
681
+ const saved = await this.client.persistMessage(this.projectId, {
682
+ id: msgId,
683
+ agentId: this.agentId,
684
+ type,
685
+ text,
686
+ parentMessageId: opts?.parentMessageId
687
+ });
688
+ this.tracker?.posted(msgId);
689
+ return saved;
690
+ } catch (err) {
691
+ this.tracker?.failed(msgId);
692
+ throw err;
693
+ }
524
694
  }
525
695
  };
526
696
 
527
697
  // src/mentions.ts
698
+ function parseMentions(text) {
699
+ const mentions = [];
700
+ for (const match of text.matchAll(/@(\w+(?:\s+\w+)*)/g)) {
701
+ mentions.push(match[1].toLowerCase());
702
+ }
703
+ return mentions;
704
+ }
528
705
  function mentionsAgent(text, agentName) {
529
706
  const pattern = new RegExp(`@${escapeRegex(agentName)}(?!\\w)`, "i");
530
707
  return pattern.test(text);
@@ -925,6 +1102,11 @@ ${systemPrompt}
925
1102
  var DEFAULT_MAX_DEPTH = 3;
926
1103
  var DEFAULT_CHUNK_BATCH_MS = 200;
927
1104
  var DEFAULT_CONTEXT_WINDOW = 20;
1105
+ var DEFAULT_HEARTBEAT_MS = 12e4;
1106
+ var OWN_MESSAGE_MEMORY = 1e3;
1107
+ var MESSAGE_INDEX_SIZE = 500;
1108
+ var META_TTL_MS = 5 * 60 * 1e3;
1109
+ 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.";
928
1110
  var JaibberAgent = class extends EventEmitter {
929
1111
  config;
930
1112
  client;
@@ -932,75 +1114,189 @@ var JaibberAgent = class extends EventEmitter {
932
1114
  messageHandler = null;
933
1115
  taskHandler = null;
934
1116
  provider = null;
1117
+ providerKind = null;
935
1118
  connected = false;
936
1119
  projects = [];
937
1120
  unsubscribers = [];
1121
+ heartbeatTimer = null;
1122
+ agentId = null;
1123
+ agentRecord = null;
938
1124
  /** In-memory conversation history per project. */
939
1125
  history = /* @__PURE__ */ new Map();
1126
+ /** Recent messages per project (id → author/parent) for chain reconstruction. */
1127
+ messageIndex = /* @__PURE__ */ new Map();
940
1128
  /** Track in-flight responses to prevent double-handling. */
941
1129
  activeResponses = /* @__PURE__ */ new Set();
942
1130
  /** Session IDs per project for Claude --resume. */
943
1131
  sessionIds = /* @__PURE__ */ new Map();
1132
+ /** Messages we POSTed ourselves, keyed by id — for echo dedupe + own-reply history. */
1133
+ ownMessages = /* @__PURE__ */ new Map();
1134
+ /** `meta` hints waiting for their server echo. */
1135
+ pendingMeta = /* @__PURE__ */ new Map();
1136
+ /**
1137
+ * Safety valve: unthreaded agent responses (no `parentMessageId`) seen per
1138
+ * project since the last human message. Threaded chains are bounded by the
1139
+ * `parentMessageId` walk; this catches agents that post without threading,
1140
+ * which would otherwise look like a fresh depth-1 chain every time.
1141
+ */
1142
+ unthreadedHops = /* @__PURE__ */ new Map();
944
1143
  constructor(config) {
945
1144
  super();
946
1145
  this.config = config;
947
1146
  this.client = new JaibberClient(config.serverUrl);
948
1147
  }
1148
+ // ── Accessors ───────────────────────────────────────────────────────
1149
+ /** The agent's server-side id (available after `connect()`). */
1150
+ get id() {
1151
+ return this.agentId;
1152
+ }
1153
+ /** The agent record returned by the server (session mode only). */
1154
+ get record() {
1155
+ return this.agentRecord;
1156
+ }
1157
+ /** The underlying REST client (authenticated after `connect()`). */
1158
+ get api() {
1159
+ return this.client;
1160
+ }
1161
+ /** Projects this agent has joined. */
1162
+ get joinedProjects() {
1163
+ return [...this.projects];
1164
+ }
1165
+ /** Sender id used on client-published typing/chunk events. */
1166
+ get senderId() {
1167
+ return this.client.userId ?? `agent:${this.agentId ?? "unknown"}`;
1168
+ }
1169
+ get maxDepth() {
1170
+ return this.config.maxResponseDepth ?? DEFAULT_MAX_DEPTH;
1171
+ }
949
1172
  // ── Lifecycle ───────────────────────────────────────────────────────
950
- /** Authenticate, connect Ably, subscribe to project channels. */
1173
+ /** Authenticate, register/resolve the agent, connect Ably, subscribe to project channels. */
951
1174
  async connect() {
952
1175
  if (this.connected) throw new Error("Already connected");
953
- const { username, password } = this.config.credentials;
954
- console.log(`[sdk] Logging in as "${username}"...`);
955
- await this.client.login(username, password);
956
- const userId = this.client.userId;
957
- const displayName = this.client.username;
1176
+ const creds = this.config.credentials;
1177
+ const apiKeyMode = "apiKey" in creds;
1178
+ if (apiKeyMode) {
1179
+ this.client.setApiKey(creds.apiKey);
1180
+ this.agentId = this.config.agentId ?? null;
1181
+ console.log(`[sdk] Authenticating with agent API key ${creds.apiKey.slice(0, 11)}\u2026`);
1182
+ } else {
1183
+ console.log(`[sdk] Logging in as "${creds.username}"...`);
1184
+ await this.client.login(creds.username, creds.password);
1185
+ const record = await this.client.ensureAgent({
1186
+ name: this.config.agentName,
1187
+ instructions: this.config.agentInstructions,
1188
+ provider: this.resolveProviderKind(),
1189
+ kind: "sdk",
1190
+ machineName: this.config.machineName,
1191
+ orgId: this.config.orgId
1192
+ });
1193
+ this.agentId = record.id;
1194
+ this.agentRecord = record;
1195
+ this.config.agentId = record.id;
1196
+ console.log(`[sdk] Agent "${record.name}" registered (id ${record.id})`);
1197
+ }
958
1198
  const allProjects = await this.client.listProjects();
959
- this.projects = this.config.projectIds ? allProjects.filter((p) => this.config.projectIds.includes(p.id)) : allProjects;
1199
+ if (this.config.projectIds) {
1200
+ const wanted = new Set(this.config.projectIds);
1201
+ this.projects = allProjects.filter((p) => wanted.has(p.id));
1202
+ const missing = this.config.projectIds.filter(
1203
+ (id) => !this.projects.some((p) => p.id === id)
1204
+ );
1205
+ if (missing.length > 0) {
1206
+ console.warn(`[sdk] Project(s) not accessible, skipping: ${missing.join(", ")}`);
1207
+ }
1208
+ } else {
1209
+ this.projects = allProjects.filter((p) => p.role !== "org-admin");
1210
+ }
960
1211
  if (this.projects.length === 0) {
961
1212
  throw new Error(
962
- "No projects found. Ensure the agent account is a member of at least one project."
1213
+ 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."
963
1214
  );
964
1215
  }
965
1216
  console.log(
966
1217
  `[sdk] Found ${this.projects.length} project(s): ${this.projects.map((p) => p.name).join(", ")}`
967
1218
  );
968
- this.ablyManager = new AblyManager(this.client, userId, displayName);
1219
+ if (!apiKeyMode) {
1220
+ for (const project of this.projects) {
1221
+ try {
1222
+ await this.client.assignAgent(this.agentId, project.id);
1223
+ } catch (err) {
1224
+ console.warn(
1225
+ `[sdk] Could not assign agent to "${project.name}": ${err instanceof Error ? err.message : err}`
1226
+ );
1227
+ }
1228
+ }
1229
+ }
1230
+ this.ablyManager = new AblyManager(this.client, {
1231
+ clientId: apiKeyMode ? void 0 : this.client.userId,
1232
+ username: this.config.agentName
1233
+ });
969
1234
  await this.ablyManager.connect();
970
- await this.ablyManager.enterGlobalPresence(
971
- this.projects.map((p) => p.id)
972
- );
973
- for (const project of this.projects) {
1235
+ try {
1236
+ if (!this.agentId) {
1237
+ const cid = this.ablyManager.clientId;
1238
+ if (cid && cid.startsWith("agent:")) {
1239
+ this.agentId = cid.slice("agent:".length);
1240
+ this.config.agentId = this.agentId;
1241
+ } else {
1242
+ throw new Error(
1243
+ `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\`.`
1244
+ );
1245
+ }
1246
+ }
1247
+ this.startHeartbeat();
1248
+ await this.ablyManager.enterGlobalPresence({
1249
+ userId: this.client.userId ?? void 0,
1250
+ agentId: this.agentId,
1251
+ username: this.config.agentName,
1252
+ projectIds: this.projects.map((p) => p.id)
1253
+ });
974
1254
  const presenceData = {
975
- userId,
1255
+ userId: this.client.userId ?? void 0,
976
1256
  username: this.config.agentName,
977
1257
  isAgent: true,
978
1258
  agentName: this.config.agentName,
1259
+ agentId: this.agentId,
979
1260
  agentInstructions: this.config.agentInstructions,
980
1261
  agents: [
981
1262
  {
1263
+ agentId: this.agentId,
982
1264
  agentName: this.config.agentName,
983
1265
  agentInstructions: this.config.agentInstructions
984
1266
  }
985
1267
  ],
986
1268
  machineName: this.config.machineName
987
1269
  };
988
- await this.loadHistory(project.id);
989
- const unsub = await this.ablyManager.subscribeToProject(
990
- project,
991
- presenceData,
992
- (msg) => this.handleIncomingMessage(msg, project),
993
- (data) => this.handleTaskEvent(data, project)
994
- );
995
- this.unsubscribers.push(unsub);
1270
+ for (const project of this.projects) {
1271
+ await this.loadHistory(project.id);
1272
+ const unsub = await this.ablyManager.subscribeToProject(
1273
+ project,
1274
+ presenceData,
1275
+ (msg) => this.handleIncomingMessage(msg, project),
1276
+ (data) => this.handleTaskEvent(data, project),
1277
+ (data) => this.handleControlEvent(data, project)
1278
+ );
1279
+ this.unsubscribers.push(unsub);
1280
+ }
1281
+ } catch (err) {
1282
+ this.stopHeartbeat();
1283
+ for (const unsub of this.unsubscribers) unsub();
1284
+ this.unsubscribers = [];
1285
+ await this.ablyManager.disconnect().catch(() => {
1286
+ });
1287
+ this.ablyManager = null;
1288
+ throw err;
996
1289
  }
997
1290
  this.connected = true;
998
- console.log(`[sdk] Agent "${this.config.agentName}" connected and listening`);
1291
+ console.log(
1292
+ `[sdk] Agent "${this.config.agentName}" (${this.agentId}) connected and listening`
1293
+ );
999
1294
  this.emit("connected", this.projects);
1000
1295
  }
1001
- /** Leave presence, disconnect Ably. */
1296
+ /** Stop heartbeats, leave presence, disconnect Ably. */
1002
1297
  async disconnect() {
1003
1298
  if (!this.connected) return;
1299
+ this.stopHeartbeat();
1004
1300
  for (const unsub of this.unsubscribers) {
1005
1301
  unsub();
1006
1302
  }
@@ -1025,48 +1321,190 @@ var JaibberAgent = class extends EventEmitter {
1025
1321
  switch (name) {
1026
1322
  case "anthropic":
1027
1323
  this.provider = new AnthropicProvider(options);
1324
+ this.providerKind = "claude";
1028
1325
  break;
1029
1326
  case "openai":
1030
1327
  this.provider = new OpenAIProvider(options);
1328
+ this.providerKind = "openai";
1031
1329
  break;
1032
1330
  case "google":
1033
1331
  this.provider = new GoogleProvider(options);
1332
+ this.providerKind = "google";
1034
1333
  break;
1035
1334
  case "claude-cli":
1036
1335
  this.provider = new ClaudeCLIProvider(options);
1336
+ this.providerKind = "claude";
1037
1337
  break;
1038
1338
  }
1039
1339
  }
1340
+ /** Provider label stored on the agent record. */
1341
+ resolveProviderKind() {
1342
+ return this.config.provider ?? this.providerKind ?? "custom";
1343
+ }
1344
+ // ── Heartbeat ───────────────────────────────────────────────────────
1345
+ startHeartbeat() {
1346
+ this.stopHeartbeat();
1347
+ const beat = async () => {
1348
+ if (!this.agentId) return;
1349
+ try {
1350
+ await this.client.heartbeat(this.agentId);
1351
+ } catch (err) {
1352
+ console.warn(`[sdk] Heartbeat failed: ${err instanceof Error ? err.message : err}`);
1353
+ }
1354
+ };
1355
+ void beat();
1356
+ this.heartbeatTimer = setInterval(beat, this.config.heartbeatMs ?? DEFAULT_HEARTBEAT_MS);
1357
+ this.heartbeatTimer.unref?.();
1358
+ }
1359
+ stopHeartbeat() {
1360
+ if (this.heartbeatTimer) {
1361
+ clearInterval(this.heartbeatTimer);
1362
+ this.heartbeatTimer = null;
1363
+ }
1364
+ }
1365
+ // ── Message index / chain reconstruction ────────────────────────────
1366
+ indexMessage(projectId, id, entry) {
1367
+ const idx = this.messageIndex.get(projectId) ?? /* @__PURE__ */ new Map();
1368
+ idx.delete(id);
1369
+ idx.set(id, entry);
1370
+ while (idx.size > MESSAGE_INDEX_SIZE) {
1371
+ const oldest = idx.keys().next().value;
1372
+ if (oldest === void 0) break;
1373
+ idx.delete(oldest);
1374
+ }
1375
+ this.messageIndex.set(projectId, idx);
1376
+ }
1377
+ /**
1378
+ * Loop prevention for agent-to-agent chains. The server echo carries no
1379
+ * chain metadata, so the chain is reconstructed from `parentMessageId`
1380
+ * links: every agent response is posted as a reply to the message it
1381
+ * answered. Returns the number of consecutive agent hops ending at
1382
+ * `payload` (the depth) and the lowercased names of the agents in that run.
1383
+ * Mirrors useAbly.ts agentChainFor().
1384
+ */
1385
+ agentChainFor(projectId, payload) {
1386
+ const idx = this.messageIndex.get(projectId);
1387
+ const chain = [(payload.agentName ?? payload.fromUsername).toLowerCase()];
1388
+ let parentId = payload.parentMessageId;
1389
+ let guard = 0;
1390
+ while (parentId && guard++ < 50) {
1391
+ const parent = idx?.get(parentId);
1392
+ if (!parent?.agentId) break;
1393
+ chain.push(parent.senderName.toLowerCase());
1394
+ parentId = parent.parentMessageId;
1395
+ }
1396
+ return { depth: chain.length, chain };
1397
+ }
1398
+ // ── `meta` hints ────────────────────────────────────────────────────
1399
+ rememberMeta(messageId, meta) {
1400
+ const cutoff = Date.now() - META_TTL_MS;
1401
+ for (const [id, m] of this.pendingMeta) {
1402
+ if (m.receivedAt < cutoff) this.pendingMeta.delete(id);
1403
+ }
1404
+ this.pendingMeta.set(messageId, meta);
1405
+ }
1406
+ takeMeta(messageId, senderId) {
1407
+ const meta = this.pendingMeta.get(messageId);
1408
+ if (!meta) return void 0;
1409
+ this.pendingMeta.delete(messageId);
1410
+ return meta.clientId === senderId ? meta : void 0;
1411
+ }
1412
+ // ── Own-message tracking (echo dedupe + own replies in history) ─────
1413
+ tracker = {
1414
+ begin: (id, projectId, text, type, parentMessageId) => {
1415
+ this.ownMessages.set(id, { projectId, text, type, recorded: false });
1416
+ while (this.ownMessages.size > OWN_MESSAGE_MEMORY) {
1417
+ const oldest = this.ownMessages.keys().next().value;
1418
+ if (oldest === void 0) break;
1419
+ this.ownMessages.delete(oldest);
1420
+ }
1421
+ this.indexMessage(projectId, id, {
1422
+ agentId: this.agentId ?? void 0,
1423
+ senderName: this.config.agentName,
1424
+ parentMessageId
1425
+ });
1426
+ },
1427
+ posted: (id) => this.recordOwnMessage(id),
1428
+ failed: (id) => {
1429
+ this.ownMessages.delete(id);
1430
+ }
1431
+ };
1432
+ /**
1433
+ * Add one of our own messages to history exactly once — whichever arrives
1434
+ * first: the server's Ably echo or the POST response.
1435
+ */
1436
+ recordOwnMessage(id) {
1437
+ const own = this.ownMessages.get(id);
1438
+ if (!own || own.recorded) return;
1439
+ own.recorded = true;
1440
+ if (own.type === "error") return;
1441
+ this.addToHistory(own.projectId, {
1442
+ sender: "agent",
1443
+ senderName: this.config.agentName,
1444
+ text: own.text,
1445
+ agentId: this.agentId ?? void 0
1446
+ });
1447
+ }
1040
1448
  // ── Message handling ────────────────────────────────────────────────
1041
1449
  async handleIncomingMessage(payload, project) {
1042
1450
  if (payload._connectionId && payload._connectionId === this.ablyManager?.connectionId) return;
1043
- if (payload.type === "deregister") {
1044
- const targetName = payload.agentName?.toLowerCase();
1045
- if (!targetName || targetName === this.config.agentName.toLowerCase()) {
1046
- console.log(`[sdk] Received deregister command. Shutting down...`);
1047
- await this.disconnect();
1048
- process.exit(0);
1049
- }
1451
+ if (payload.type === "meta") {
1452
+ if (!payload._clientId) return;
1453
+ this.rememberMeta(payload.messageId, {
1454
+ clientId: payload._clientId,
1455
+ executionMode: payload.executionMode,
1456
+ attachments: payload.attachments,
1457
+ receivedAt: Date.now()
1458
+ });
1050
1459
  return;
1051
1460
  }
1052
- if (payload.isTaskNotification) return;
1053
1461
  if (payload.type !== "message" && payload.type !== "response") return;
1462
+ if (this.ownMessages.has(payload.messageId)) {
1463
+ this.recordOwnMessage(payload.messageId);
1464
+ return;
1465
+ }
1054
1466
  if (payload.text && payload.text.length > 1e5) {
1055
1467
  console.warn(`[sdk] Ignoring oversized message (${payload.text.length} chars)`);
1056
1468
  return;
1057
1469
  }
1470
+ const isAgent = payload.isAgentMessage === true || !!payload.agentId;
1471
+ const isSelf = !!this.agentId && payload.agentId === this.agentId;
1472
+ this.indexMessage(project.id, payload.messageId, {
1473
+ agentId: payload.agentId,
1474
+ senderName: payload.agentName ?? payload.fromUsername,
1475
+ parentMessageId: payload.parentMessageId
1476
+ });
1477
+ if (!isAgent) this.unthreadedHops.set(project.id, 0);
1058
1478
  this.addToHistory(project.id, {
1059
- sender: payload.isAgentMessage ? "agent" : "user",
1479
+ sender: isAgent ? "agent" : "user",
1060
1480
  senderName: payload.fromUsername,
1061
- text: payload.text
1481
+ text: payload.text,
1482
+ agentId: payload.agentId
1062
1483
  });
1063
- const depth = payload.responseDepth ?? 0;
1064
- const chain = payload.respondingChain ?? [];
1484
+ if (isSelf) return;
1485
+ if (payload.isTaskNotification) return;
1486
+ let depth = 0;
1487
+ let chain = [];
1488
+ let executionMode = payload.executionMode;
1489
+ let attachments = payload.attachments;
1490
+ if (isAgent) {
1491
+ if (payload.type !== "response") return;
1492
+ ({ depth, chain } = this.agentChainFor(project.id, payload));
1493
+ if (!payload.parentMessageId) {
1494
+ const n = (this.unthreadedHops.get(project.id) ?? 0) + 1;
1495
+ this.unthreadedHops.set(project.id, n);
1496
+ if (n > this.maxDepth) return;
1497
+ }
1498
+ } else {
1499
+ const meta = this.takeMeta(payload.messageId, payload.from);
1500
+ executionMode = executionMode ?? meta?.executionMode;
1501
+ attachments = attachments ?? meta?.attachments;
1502
+ }
1065
1503
  if (!this.shouldRespond(payload.text, depth, chain)) return;
1066
1504
  if (this.activeResponses.has(payload.messageId)) return;
1067
1505
  this.activeResponses.add(payload.messageId);
1068
1506
  try {
1069
- await this.respondToMessage(payload, project, depth, chain);
1507
+ await this.respondToMessage(payload, project, depth, chain, executionMode, attachments);
1070
1508
  } catch (err) {
1071
1509
  console.error("[sdk] Error responding to message:", err);
1072
1510
  this.emit("error", err);
@@ -1079,26 +1517,27 @@ var JaibberAgent = class extends EventEmitter {
1079
1517
  * Mirrors useAbly.ts shouldAgentRespond() logic.
1080
1518
  */
1081
1519
  shouldRespond(text, depth, chain) {
1082
- const maxDepth = this.config.maxResponseDepth ?? DEFAULT_MAX_DEPTH;
1083
- if (depth >= maxDepth) return false;
1520
+ if (depth >= this.maxDepth) return false;
1084
1521
  if (chain.includes(this.config.agentName.toLowerCase())) return false;
1085
1522
  if (!mentionsAgent(text, this.config.agentName)) return false;
1086
1523
  return true;
1087
1524
  }
1088
- async respondToMessage(payload, project, incomingDepth, incomingChain) {
1089
- const userId = this.client.userId;
1525
+ async respondToMessage(payload, project, incomingDepth, incomingChain, executionMode, attachments) {
1090
1526
  const conversationHistory = this.getFormattedHistory(project.id);
1091
1527
  const ctx = new MessageContext({
1092
1528
  projectId: project.id,
1093
1529
  channelName: project.ablyChannelName,
1094
1530
  conversationHistory,
1095
1531
  ablyManager: this.ablyManager,
1096
- userId,
1532
+ from: this.senderId,
1533
+ agentId: this.agentId,
1097
1534
  agentName: this.config.agentName,
1098
1535
  client: this.client,
1536
+ incomingMessageId: payload.messageId,
1099
1537
  incomingDepth,
1100
1538
  incomingChain,
1101
- chunkBatchMs: this.config.chunkBatchMs ?? DEFAULT_CHUNK_BATCH_MS
1539
+ chunkBatchMs: this.config.chunkBatchMs ?? DEFAULT_CHUNK_BATCH_MS,
1540
+ tracker: this.tracker
1102
1541
  });
1103
1542
  if (this.messageHandler) {
1104
1543
  await this.messageHandler(
@@ -1111,9 +1550,14 @@ var JaibberAgent = class extends EventEmitter {
1111
1550
  type: payload.type,
1112
1551
  responseDepth: incomingDepth,
1113
1552
  respondingChain: incomingChain,
1114
- executionMode: payload.executionMode,
1553
+ executionMode,
1115
1554
  isAgentMessage: payload.isAgentMessage,
1116
- attachments: payload.attachments
1555
+ agentId: payload.agentId,
1556
+ agentName: payload.agentName,
1557
+ mentions: payload.mentions,
1558
+ parentMessageId: payload.parentMessageId,
1559
+ attachments,
1560
+ createdAt: payload.createdAt
1117
1561
  },
1118
1562
  ctx
1119
1563
  );
@@ -1121,7 +1565,7 @@ var JaibberAgent = class extends EventEmitter {
1121
1565
  }
1122
1566
  if (this.provider) {
1123
1567
  this.updateProviderSession(project.id);
1124
- const systemPrompt = this.config.agentInstructions ?? "";
1568
+ const systemPrompt = this.systemPromptFor(executionMode);
1125
1569
  await ctx.stream(
1126
1570
  () => this.provider.generate(payload.text, systemPrompt, conversationHistory)
1127
1571
  );
@@ -1132,36 +1576,55 @@ var JaibberAgent = class extends EventEmitter {
1132
1576
  "[sdk] No message handler or provider configured. Ignoring message."
1133
1577
  );
1134
1578
  }
1579
+ /** Agent instructions, prefixed with the plan-mode directive when requested. */
1580
+ systemPromptFor(executionMode) {
1581
+ const instructions = this.config.agentInstructions ?? "";
1582
+ if (executionMode !== "plan") return instructions;
1583
+ return instructions ? `${PLAN_MODE_PREFIX}
1584
+
1585
+ ${instructions}` : PLAN_MODE_PREFIX;
1586
+ }
1587
+ // ── Agent control (server-published lifecycle commands) ─────────────
1588
+ /** Is a server control event addressed to this agent? */
1589
+ isControlForMe(data) {
1590
+ if (this.agentId) return data.agentId === this.agentId;
1591
+ return !!data.agentName && data.agentName.toLowerCase() === this.config.agentName.toLowerCase();
1592
+ }
1593
+ /**
1594
+ * `agent-control` events are published by the server on project channels,
1595
+ * e.g. `{action: "deregister", agentId, agentName}` when an agent is revoked
1596
+ * via the API. Events for other agents are ignored.
1597
+ */
1598
+ async handleControlEvent(data, project) {
1599
+ if (!data || data.action !== "deregister") return;
1600
+ if (!this.isControlForMe(data)) return;
1601
+ console.log(
1602
+ `[sdk] Agent "${this.config.agentName}" was deregistered by the server (via project "${project.name}"). Shutting down...`
1603
+ );
1604
+ try {
1605
+ await this.disconnect();
1606
+ } catch (err) {
1607
+ console.error("[sdk] Error during deregister shutdown:", err);
1608
+ }
1609
+ this.emit("deregistered", data);
1610
+ if (this.config.exitOnDeregister !== false) {
1611
+ process.exit(0);
1612
+ }
1613
+ }
1135
1614
  // ── Task handling ───────────────────────────────────────────────────
1136
1615
  async handleTaskEvent(data, project) {
1137
1616
  if (data.type !== "task-created" && data.type !== "task-updated")
1138
1617
  return;
1139
1618
  const task = data.task;
1140
1619
  if (task.status !== "submitted") return;
1141
- if (!task.assignedAgentName || task.assignedAgentName.toLowerCase() !== this.config.agentName.toLowerCase())
1142
- return;
1620
+ const assignedById = !!task.assignedAgentId && !!this.agentId && task.assignedAgentId === this.agentId;
1621
+ const assignedByName = !!task.assignedAgentName && task.assignedAgentName.toLowerCase() === this.config.agentName.toLowerCase();
1622
+ if (!assignedById && !assignedByName) return;
1143
1623
  console.log(
1144
1624
  `[sdk] Picking up task: "${task.title}" (${task.id})`
1145
1625
  );
1146
1626
  try {
1147
1627
  await this.client.updateTask(task.id, { status: "working" });
1148
- const userId = this.client.userId;
1149
- const announceMsgId = uuidv42();
1150
- await this.ablyManager.publish(
1151
- project.ablyChannelName,
1152
- "message",
1153
- {
1154
- from: userId,
1155
- fromUsername: this.config.agentName,
1156
- projectId: project.id,
1157
- text: `Picking up task: **${task.title}**`,
1158
- messageId: announceMsgId,
1159
- type: "message",
1160
- agentName: this.config.agentName,
1161
- isAgentMessage: true,
1162
- isTaskNotification: true
1163
- }
1164
- );
1165
1628
  const conversationHistory = this.getFormattedHistory(project.id);
1166
1629
  const ctx = new TaskContext({
1167
1630
  task,
@@ -1169,10 +1632,19 @@ var JaibberAgent = class extends EventEmitter {
1169
1632
  channelName: project.ablyChannelName,
1170
1633
  conversationHistory,
1171
1634
  ablyManager: this.ablyManager,
1172
- userId,
1635
+ from: this.senderId,
1636
+ agentId: this.agentId,
1173
1637
  agentName: this.config.agentName,
1174
- client: this.client
1638
+ client: this.client,
1639
+ tracker: this.tracker
1175
1640
  });
1641
+ try {
1642
+ await ctx.sendMessage(`Picking up task: **${task.title}**`, { type: "message" });
1643
+ } catch (err) {
1644
+ console.warn(
1645
+ `[sdk] Could not announce task pickup: ${err instanceof Error ? err.message : err}`
1646
+ );
1647
+ }
1176
1648
  if (this.taskHandler) {
1177
1649
  await this.taskHandler(task, ctx);
1178
1650
  return;
@@ -1188,12 +1660,14 @@ ${task.description}` : `Task: ${task.title}`;
1188
1660
  channelName: project.ablyChannelName,
1189
1661
  conversationHistory,
1190
1662
  ablyManager: this.ablyManager,
1191
- userId,
1663
+ from: this.senderId,
1664
+ agentId: this.agentId,
1192
1665
  agentName: this.config.agentName,
1193
1666
  client: this.client,
1194
1667
  incomingDepth: 0,
1195
1668
  incomingChain: [],
1196
- chunkBatchMs: this.config.chunkBatchMs ?? DEFAULT_CHUNK_BATCH_MS
1669
+ chunkBatchMs: this.config.chunkBatchMs ?? DEFAULT_CHUNK_BATCH_MS,
1670
+ tracker: this.tracker
1197
1671
  });
1198
1672
  try {
1199
1673
  await msgCtx.stream(
@@ -1243,6 +1717,11 @@ ${task.description}` : `Task: ${task.title}`;
1243
1717
  }
1244
1718
  }
1245
1719
  // ── Conversation history ────────────────────────────────────────────
1720
+ /** Is this stored message one of this agent's own prior replies? */
1721
+ isOwnServerMessage(m) {
1722
+ if (this.agentId && m.senderAgentId === this.agentId) return true;
1723
+ return m.senderType === "agent" && m.senderName.toLowerCase() === this.config.agentName.toLowerCase();
1724
+ }
1246
1725
  async loadHistory(projectId) {
1247
1726
  const contextSize = this.config.contextWindowSize ?? DEFAULT_CONTEXT_WINDOW;
1248
1727
  try {
@@ -1250,12 +1729,30 @@ ${task.description}` : `Task: ${task.title}`;
1250
1729
  projectId,
1251
1730
  contextSize
1252
1731
  );
1253
- const entries = messages.reverse().map((m) => ({
1254
- sender: m.senderType === "user" ? "user" : "agent",
1255
- senderName: m.senderName,
1256
- text: m.text
1257
- }));
1258
- this.history.set(projectId, entries);
1732
+ const first = messages[0];
1733
+ const last = messages[messages.length - 1];
1734
+ if (first && last && first !== last && first.createdAt > last.createdAt) {
1735
+ messages.reverse();
1736
+ }
1737
+ const entries = [];
1738
+ for (const m of messages) {
1739
+ const own = this.isOwnServerMessage(m);
1740
+ const agentId = m.senderAgentId ?? (own ? this.agentId ?? void 0 : void 0);
1741
+ this.indexMessage(projectId, m.id, {
1742
+ agentId,
1743
+ senderName: own ? this.config.agentName : m.senderName,
1744
+ parentMessageId: m.parentMessageId ?? void 0
1745
+ });
1746
+ if (m.type === "system" || !m.text) continue;
1747
+ const sender = own || m.senderType === "agent" ? "agent" : "user";
1748
+ entries.push({
1749
+ sender,
1750
+ senderName: own ? this.config.agentName : m.senderName,
1751
+ text: m.text,
1752
+ agentId
1753
+ });
1754
+ }
1755
+ this.history.set(projectId, entries.slice(-contextSize));
1259
1756
  } catch (err) {
1260
1757
  console.error(
1261
1758
  `[sdk] Failed to load history for project ${projectId}:`,
@@ -1275,7 +1772,7 @@ ${task.description}` : `Task: ${task.title}`;
1275
1772
  }
1276
1773
  /**
1277
1774
  * Format conversation history for LLM context.
1278
- * Matches useAbly.ts lines 77-84 format.
1775
+ * Matches useAbly.ts format: `User: text` / `Assistant (Name): text`.
1279
1776
  */
1280
1777
  getFormattedHistory(projectId) {
1281
1778
  const entries = this.history.get(projectId) ?? [];
@@ -1340,9 +1837,12 @@ export {
1340
1837
  ClaudeCLIProvider,
1341
1838
  GoogleProvider,
1342
1839
  JaibberAgent,
1840
+ JaibberClient,
1343
1841
  MessageContext,
1344
1842
  OpenAIProvider,
1345
1843
  TaskContext,
1346
- getTemplate
1844
+ getTemplate,
1845
+ mentionsAgent,
1846
+ parseMentions
1347
1847
  };
1348
1848
  //# sourceMappingURL=index.js.map