@jaibber/sdk 0.3.8 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -2,18 +2,59 @@
2
2
 
3
3
  // src/agent.ts
4
4
  import { EventEmitter } from "events";
5
- import { v4 as uuidv42 } from "uuid";
6
5
 
7
6
  // src/client.ts
7
+ var API_KEY_PREFIX = "jb_";
8
+ async function readError(res) {
9
+ const text = await res.text().catch(() => "");
10
+ try {
11
+ const json = JSON.parse(text);
12
+ const err = json?.error;
13
+ if (typeof err === "string") return err;
14
+ if (err && typeof err === "object") {
15
+ const e = err;
16
+ if (typeof e.message === "string") {
17
+ return e.code ? `${e.code}: ${e.message}` : e.message;
18
+ }
19
+ }
20
+ } catch {
21
+ }
22
+ return text || res.statusText || "Unknown error";
23
+ }
24
+ function mapProject(p, fallbackRole = "member") {
25
+ return {
26
+ id: p.id,
27
+ name: p.name,
28
+ description: p.description ?? null,
29
+ orgId: p.orgId ?? null,
30
+ ablyChannelName: p.ablyChannelName,
31
+ role: p.role ?? fallbackRole
32
+ };
33
+ }
8
34
  var JaibberClient = class {
9
35
  serverUrl;
10
36
  jwt = null;
37
+ apiKey = null;
11
38
  userId = null;
12
39
  username = null;
13
- constructor(serverUrl2) {
40
+ constructor(serverUrl2, opts) {
14
41
  this.serverUrl = serverUrl2.replace(/\/+$/, "");
42
+ if (opts?.apiKey) this.setApiKey(opts.apiKey);
43
+ if (opts?.token) this.jwt = opts.token;
15
44
  }
16
45
  // ── Auth ────────────────────────────────────────────────────────────
46
+ /** Use an API key (`jb_…`) for all requests. An agent-bound key authenticates AS that agent. */
47
+ setApiKey(apiKey2) {
48
+ const key = apiKey2.trim();
49
+ if (!key.startsWith(API_KEY_PREFIX)) {
50
+ throw new Error(`Invalid Jaibber API key: expected it to start with "${API_KEY_PREFIX}".`);
51
+ }
52
+ this.apiKey = key;
53
+ }
54
+ /** Use an existing session JWT for all requests. */
55
+ setToken(token) {
56
+ this.jwt = token;
57
+ }
17
58
  /** POST /api/auth/register — create a new account, stores JWT. */
18
59
  async register(username2, password2) {
19
60
  const res = await fetch(`${this.serverUrl}/api/auth/register`, {
@@ -22,7 +63,7 @@ var JaibberClient = class {
22
63
  body: JSON.stringify({ username: username2, password: password2 })
23
64
  });
24
65
  if (!res.ok) {
25
- const text = await res.text();
66
+ const text = await readError(res);
26
67
  if (res.status === 409) {
27
68
  throw new Error(`Username "${username2}" is already taken.`);
28
69
  }
@@ -41,7 +82,7 @@ var JaibberClient = class {
41
82
  body: JSON.stringify({ username: username2, password: password2 })
42
83
  });
43
84
  if (!res.ok) {
44
- const text = await res.text();
85
+ const text = await readError(res);
45
86
  if (res.status === 401) {
46
87
  throw new Error("Invalid credentials. Check username and password.");
47
88
  }
@@ -53,169 +94,300 @@ var JaibberClient = class {
53
94
  this.username = data.username;
54
95
  }
55
96
  get isAuthenticated() {
56
- return this.jwt !== null;
97
+ return this.jwt !== null || this.apiKey !== null;
98
+ }
99
+ /** Which credential requests will carry. */
100
+ get authMode() {
101
+ if (this.apiKey) return "apiKey";
102
+ if (this.jwt) return "session";
103
+ return "none";
57
104
  }
58
105
  authHeaders() {
59
106
  const h = { "Content-Type": "application/json" };
60
- if (this.jwt) {
107
+ if (this.apiKey) {
108
+ h["X-API-Key"] = this.apiKey;
109
+ } else if (this.jwt) {
61
110
  h["Authorization"] = `Bearer ${this.jwt}`;
62
111
  }
63
112
  return h;
64
113
  }
114
+ /** Authenticated fetch with uniform error reporting. */
115
+ async request(method, path, body, what) {
116
+ const res = await fetch(`${this.serverUrl}${path}`, {
117
+ method,
118
+ headers: this.authHeaders(),
119
+ ...body !== void 0 ? { body: JSON.stringify(body) } : {}
120
+ });
121
+ if (!res.ok) {
122
+ const text = await readError(res);
123
+ throw new Error(`${what ?? `${method} ${path}`} failed (${res.status}): ${text}`);
124
+ }
125
+ return res;
126
+ }
127
+ // ── Identity ────────────────────────────────────────────────────────
128
+ /**
129
+ * GET /api/me — who the current credential is: the user (session), the
130
+ * agent (agent-bound key) or the org (org key). Resolves `null` when the
131
+ * server predates the endpoint (404).
132
+ */
133
+ async whoAmI() {
134
+ const res = await fetch(`${this.serverUrl}/api/me`, { headers: this.authHeaders() });
135
+ if (res.status === 404) return null;
136
+ if (!res.ok) {
137
+ const text = await readError(res);
138
+ throw new Error(`GET /api/me failed (${res.status}): ${text}`);
139
+ }
140
+ const json = await res.json();
141
+ return json.data;
142
+ }
65
143
  // ── Projects ────────────────────────────────────────────────────────
66
- /** GET /api/projects — list all projects user is member of. */
144
+ /**
145
+ * GET /api/projects — with a session: projects the user is a member of
146
+ * (plus org-admin-visible ones with role "org-admin"); with an agent key:
147
+ * the agent's assigned projects.
148
+ */
67
149
  async listProjects() {
68
- const res = await fetch(`${this.serverUrl}/api/projects`, {
69
- headers: this.authHeaders()
150
+ const res = await this.request("GET", "/api/projects", void 0, "Failed to list projects");
151
+ const json = await res.json();
152
+ const rows = json.projects ?? json.data ?? [];
153
+ return rows.map((p) => mapProject(p, this.apiKey ? "agent" : "member"));
154
+ }
155
+ /** POST /api/projects — create a new project (session only), returns it. */
156
+ async createProject(name, description, orgId2) {
157
+ const res = await this.request(
158
+ "POST",
159
+ "/api/projects",
160
+ { name, description, ...orgId2 ? { orgId: orgId2 } : {} },
161
+ "Failed to create project"
162
+ );
163
+ const json = await res.json();
164
+ const p = json.project ?? json.data;
165
+ if (!p) throw new Error("Failed to create project: malformed response");
166
+ return mapProject(p, "admin");
167
+ }
168
+ // ── Agents (/api/me/agents) ─────────────────────────────────────────
169
+ /**
170
+ * POST /api/me/agents — idempotent upsert of an agent hosted by the
171
+ * logged-in user, keyed by (org, lower(name)). Session only.
172
+ */
173
+ async ensureAgent(input) {
174
+ const body = { name: input.name, kind: input.kind };
175
+ if (input.instructions !== void 0) body.instructions = input.instructions;
176
+ if (input.provider) body.provider = input.provider;
177
+ if (input.machineName) body.machineName = input.machineName;
178
+ if (input.projectId) body.projectId = input.projectId;
179
+ if (input.orgId) body.orgId = input.orgId;
180
+ const res = await fetch(`${this.serverUrl}/api/me/agents`, {
181
+ method: "POST",
182
+ headers: this.authHeaders(),
183
+ body: JSON.stringify(body)
70
184
  });
71
185
  if (!res.ok) {
72
- const text = await res.text();
73
- throw new Error(`Failed to list projects (${res.status}): ${text}`);
186
+ const text = await readError(res);
187
+ if (res.status === 404) {
188
+ throw new Error(
189
+ "This Jaibber server does not support agent registration (POST /api/me/agents \u2192 404). Upgrade the server, or use @jaibber/sdk 0.3.x."
190
+ );
191
+ }
192
+ throw new Error(`Failed to register agent (${res.status}): ${text}`);
74
193
  }
75
- const data = await res.json();
76
- return data.projects.map((p) => ({
77
- id: p.id,
78
- name: p.name,
79
- description: p.description,
80
- ablyChannelName: p.ablyChannelName,
81
- role: p.role
82
- }));
83
- }
84
- /** POST /api/projects — create a new project, returns it. */
85
- async createProject(name, description) {
86
- const res = await fetch(`${this.serverUrl}/api/projects`, {
194
+ const json = await res.json();
195
+ return json.data;
196
+ }
197
+ /** GET /api/me/agents — agents hosted by the logged-in user (with assignments). */
198
+ async listMyAgents() {
199
+ const res = await this.request("GET", "/api/me/agents", void 0, "Failed to list agents");
200
+ const json = await res.json();
201
+ return json.data;
202
+ }
203
+ /** POST /api/me/agents/:id/assignments — assign an agent to a project (idempotent). */
204
+ async assignAgent(agentId, projectId) {
205
+ const res = await fetch(`${this.serverUrl}/api/me/agents/${agentId}/assignments`, {
87
206
  method: "POST",
88
207
  headers: this.authHeaders(),
89
- body: JSON.stringify({ name, description })
208
+ body: JSON.stringify({ projectId })
90
209
  });
91
- if (!res.ok) {
92
- const text = await res.text();
93
- throw new Error(`Failed to create project (${res.status}): ${text}`);
210
+ if (!res.ok && res.status !== 409) {
211
+ const text = await readError(res);
212
+ throw new Error(`Failed to assign agent to project ${projectId} (${res.status}): ${text}`);
94
213
  }
95
- const data = await res.json();
96
- return {
97
- id: data.project.id,
98
- name: data.project.name,
99
- description: data.project.description,
100
- ablyChannelName: data.project.ablyChannelName,
101
- role: "admin"
102
- };
214
+ }
215
+ /** DELETE /api/me/agents/:id/assignments?projectId= — remove an assignment. */
216
+ async unassignAgent(agentId, projectId) {
217
+ const res = await this.request(
218
+ "DELETE",
219
+ `/api/me/agents/${agentId}/assignments?projectId=${encodeURIComponent(projectId)}`,
220
+ void 0,
221
+ "Failed to unassign agent"
222
+ );
223
+ const json = await res.json().catch(() => ({}));
224
+ return json.data?.removed ?? true;
225
+ }
226
+ /** POST /api/me/agents/:id/keys — mint an agent-bound API key. The raw key is returned once. */
227
+ async createAgentKey(agentId, name) {
228
+ const res = await this.request(
229
+ "POST",
230
+ `/api/me/agents/${agentId}/keys`,
231
+ name ? { name } : {},
232
+ "Failed to create agent API key"
233
+ );
234
+ const json = await res.json();
235
+ return json.data;
236
+ }
237
+ /** POST /api/agents/:id/heartbeat — refresh lastSeenAt (host session or the agent's own key). */
238
+ async heartbeat(agentId) {
239
+ const res = await this.request(
240
+ "POST",
241
+ `/api/agents/${agentId}/heartbeat`,
242
+ void 0,
243
+ "Heartbeat"
244
+ );
245
+ const json = await res.json();
246
+ return json.data;
103
247
  }
104
248
  // ── Ably token ──────────────────────────────────────────────────────
105
249
  /** POST /api/ably/token — get scoped Ably TokenRequest. */
106
250
  async getAblyToken() {
107
- const res = await fetch(`${this.serverUrl}/api/ably/token`, {
108
- method: "POST",
109
- headers: this.authHeaders()
110
- });
111
- if (!res.ok) {
112
- const text = await res.text();
113
- throw new Error(`Failed to get Ably token (${res.status}): ${text}`);
114
- }
251
+ const res = await this.request("POST", "/api/ably/token", void 0, "Failed to get Ably token");
115
252
  return res.json();
116
253
  }
117
254
  // ── Messages ────────────────────────────────────────────────────────
118
255
  /**
119
- * POST /api/projects/{id}/messages — persist a message (idempotent).
120
- * Passing a client-generated `id` makes the server skip Ably re-publish.
256
+ * POST /api/projects/{id}/messages — persist a message. This is the only
257
+ * write path for final messages: the server publishes the echo to Ably
258
+ * itself. Idempotent on `id` (201 on create, 200 if it already existed).
259
+ *
260
+ * Identity is derived server-side: in session mode pass `agentId` to post
261
+ * as that hosted agent; with an agent key it is implied.
262
+ *
263
+ * Retries once on network errors / 5xx (safe: ids are idempotent).
121
264
  */
122
265
  async persistMessage(projectId, msg) {
123
- const res = await fetch(
124
- `${this.serverUrl}/api/projects/${projectId}/messages`,
125
- {
266
+ const body = { text: msg.text };
267
+ if (msg.id) body.id = msg.id;
268
+ if (msg.agentId) body.agentId = msg.agentId;
269
+ if (msg.type) body.type = msg.type;
270
+ if (msg.parentMessageId) body.parentMessageId = msg.parentMessageId;
271
+ if (msg.mentions?.length) body.mentions = msg.mentions;
272
+ const attempt = async () => {
273
+ const res = await fetch(`${this.serverUrl}/api/projects/${projectId}/messages`, {
126
274
  method: "POST",
127
275
  headers: this.authHeaders(),
128
- body: JSON.stringify(msg)
276
+ body: JSON.stringify(body)
277
+ });
278
+ if (!res.ok) {
279
+ const text = await readError(res);
280
+ const err = new Error(`Failed to persist message (${res.status}): ${text}`);
281
+ err.status = res.status;
282
+ throw err;
129
283
  }
130
- );
131
- if (!res.ok) {
132
- const text = await res.text();
133
- console.error(
134
- `[sdk] Failed to persist message (${res.status}): ${text}`
135
- );
284
+ const json = await res.json();
285
+ return json.data;
286
+ };
287
+ try {
288
+ return await attempt();
289
+ } catch (err) {
290
+ const status = err.status;
291
+ const retryable = status === void 0 || status >= 500 || status === 429;
292
+ if (!retryable) throw err;
293
+ await new Promise((r) => setTimeout(r, 1e3));
294
+ return attempt();
136
295
  }
137
296
  }
138
- /** GET /api/projects/{id}/messages — fetch recent messages. */
297
+ /** GET /api/projects/{id}/messages — fetch recent messages (oldest first). */
139
298
  async fetchMessages(projectId, limit = 20) {
140
- const res = await fetch(
141
- `${this.serverUrl}/api/projects/${projectId}/messages?limit=${limit}`,
142
- { headers: this.authHeaders() }
299
+ const res = await this.request(
300
+ "GET",
301
+ `/api/projects/${projectId}/messages?limit=${limit}`,
302
+ void 0,
303
+ "Failed to fetch messages"
143
304
  );
144
- if (!res.ok) {
145
- const text = await res.text();
146
- throw new Error(`Failed to fetch messages (${res.status}): ${text}`);
147
- }
148
305
  const data = await res.json();
149
306
  return data.data;
150
307
  }
151
308
  // ── Tasks ───────────────────────────────────────────────────────────
152
309
  /** POST /api/projects/{id}/tasks — create a task. */
153
310
  async createTask(projectId, data) {
154
- const res = await fetch(
155
- `${this.serverUrl}/api/projects/${projectId}/tasks`,
156
- {
157
- method: "POST",
158
- headers: this.authHeaders(),
159
- body: JSON.stringify(data)
160
- }
311
+ const res = await this.request(
312
+ "POST",
313
+ `/api/projects/${projectId}/tasks`,
314
+ data,
315
+ "Failed to create task"
161
316
  );
162
- if (!res.ok) {
163
- const text = await res.text();
164
- throw new Error(`Failed to create task (${res.status}): ${text}`);
165
- }
166
317
  const result = await res.json();
167
318
  return result.data;
168
319
  }
169
- /** PATCH /api/tasks/{taskId} — update task fields. */
320
+ /** PATCH /api/tasks/{taskId} — update task fields. Returns the updated task. */
170
321
  async updateTask(taskId, updates) {
171
- const res = await fetch(`${this.serverUrl}/api/tasks/${taskId}`, {
172
- method: "PATCH",
173
- headers: this.authHeaders(),
174
- body: JSON.stringify(updates)
175
- });
176
- if (!res.ok) {
177
- const text = await res.text();
178
- console.error(`[sdk] Failed to update task (${res.status}): ${text}`);
179
- }
322
+ const res = await this.request(
323
+ "PATCH",
324
+ `/api/tasks/${taskId}`,
325
+ updates,
326
+ "Failed to update task"
327
+ );
328
+ const result = await res.json();
329
+ return result.data;
180
330
  }
181
331
  };
182
332
 
183
333
  // src/ably-manager.ts
184
334
  import Ably from "ably";
335
+ var CONNECT_TIMEOUT_MS = 3e4;
185
336
  var AblyManager = class {
186
- constructor(client, userId, username2) {
337
+ constructor(client, opts) {
187
338
  this.client = client;
188
- this.userId = userId;
189
- this.username = username2;
339
+ this.opts = opts;
190
340
  }
191
341
  ably = null;
192
342
  channels = /* @__PURE__ */ new Map();
193
343
  presenceChannel = null;
194
344
  /** Create Ably Realtime client with token auth callback. */
195
- async connect() {
345
+ async connect(timeoutMs = CONNECT_TIMEOUT_MS) {
196
346
  return new Promise((resolve, reject) => {
347
+ let lastAuthError = null;
348
+ let settled = false;
349
+ const finish = (fn) => {
350
+ if (settled) return;
351
+ settled = true;
352
+ clearTimeout(timer);
353
+ fn();
354
+ };
355
+ const timer = setTimeout(() => {
356
+ finish(() => {
357
+ this.ably?.close();
358
+ this.ably = null;
359
+ reject(
360
+ new Error(
361
+ `Ably connection timed out after ${Math.round(timeoutMs / 1e3)}s` + (lastAuthError ? ` (last auth error: ${lastAuthError.message})` : "")
362
+ )
363
+ );
364
+ });
365
+ }, timeoutMs);
197
366
  this.ably = new Ably.Realtime({
198
367
  authCallback: async (_tokenParams, callback) => {
199
368
  try {
200
369
  const tokenRequest = await this.client.getAblyToken();
201
370
  callback(null, tokenRequest);
202
371
  } catch (err) {
203
- callback(err, null);
372
+ lastAuthError = err instanceof Error ? err : new Error(String(err));
373
+ callback(lastAuthError.message, null);
204
374
  }
205
375
  },
206
- clientId: this.userId,
376
+ ...this.opts.clientId ? { clientId: this.opts.clientId } : {},
207
377
  disconnectedRetryTimeout: 5e3,
208
378
  // 5s initial retry on disconnect
209
379
  suspendedRetryTimeout: 3e4
210
380
  // 30s retry when suspended
211
381
  });
212
382
  this.ably.connection.once("connected", () => {
213
- resolve();
383
+ finish(resolve);
214
384
  });
215
385
  this.ably.connection.once("failed", (stateChange) => {
216
- reject(
217
- new Error(
218
- `Ably connection failed: ${stateChange?.reason?.message ?? "unknown"}`
386
+ finish(
387
+ () => reject(
388
+ new Error(
389
+ `Ably connection failed: ${stateChange?.reason?.message ?? lastAuthError?.message ?? "unknown"}`
390
+ )
219
391
  )
220
392
  );
221
393
  });
@@ -233,42 +405,62 @@ var AblyManager = class {
233
405
  });
234
406
  }
235
407
  /** Enter global presence channel (jaibber:presence). */
236
- async enterGlobalPresence(projectIds2) {
408
+ async enterGlobalPresence(data) {
237
409
  if (!this.ably) throw new Error("Ably not connected");
238
410
  this.presenceChannel = this.ably.channels.get("jaibber:presence");
239
411
  await this.presenceChannel.presence.enter({
240
- userId: this.userId,
241
- username: this.username,
242
- projectIds: projectIds2
412
+ ...data.userId ? { userId: data.userId } : {},
413
+ ...data.agentId ? { agentId: data.agentId } : {},
414
+ username: data.username,
415
+ projectIds: data.projectIds
243
416
  });
244
417
  }
245
418
  /**
246
- * Subscribe to a project channel and enter per-project presence.
419
+ * Subscribe to a project channel (`message`, `task` and server-published
420
+ * `agent-control` events) and enter per-project presence.
247
421
  * Returns an unsubscribe function.
248
422
  */
249
- async subscribeToProject(project, presenceData, onMessage, onTask) {
423
+ async subscribeToProject(project, presenceData, onMessage, onTask, onControl, onError = (err, event) => console.error(`[sdk] Unhandled error in ${event} handler:`, err)) {
250
424
  if (!this.ably) throw new Error("Ably not connected");
251
425
  const channel = this.ably.channels.get(project.ablyChannelName);
252
426
  this.channels.set(project.ablyChannelName, channel);
253
427
  await channel.presence.enter(presenceData);
254
- const messageHandler = (msg) => {
255
- if (!msg.data) return;
428
+ const safely = (event, body) => {
429
+ try {
430
+ Promise.resolve(body()).catch((err) => onError(err, event));
431
+ } catch (err) {
432
+ onError(err, event);
433
+ }
434
+ };
435
+ const messageHandler = (msg) => safely("message", () => {
436
+ if (!msg.data || typeof msg.data !== "object") return;
256
437
  const payload = msg.data;
257
438
  payload._connectionId = msg.connectionId ?? void 0;
258
- onMessage(payload);
259
- };
260
- const taskHandler = (msg) => {
261
- if (!msg.data) return;
262
- onTask(msg.data);
263
- };
439
+ payload._clientId = msg.clientId ?? void 0;
440
+ return onMessage(payload);
441
+ });
442
+ const taskHandler = (msg) => safely("task", () => {
443
+ if (!msg.data || typeof msg.data !== "object") return;
444
+ return onTask(msg.data);
445
+ });
446
+ const controlHandler = (msg) => safely("agent-control", () => {
447
+ if (!msg.data || typeof msg.data !== "object") return;
448
+ return onControl?.(msg.data);
449
+ });
264
450
  channel.subscribe("message", messageHandler);
265
451
  channel.subscribe("task", taskHandler);
452
+ channel.subscribe("agent-control", controlHandler);
266
453
  return () => {
267
454
  channel.unsubscribe("message", messageHandler);
268
455
  channel.unsubscribe("task", taskHandler);
456
+ channel.unsubscribe("agent-control", controlHandler);
269
457
  };
270
458
  }
271
- /** Publish a message on a project channel. */
459
+ /**
460
+ * Publish a client-side event on a project channel. Only `typing` and
461
+ * `chunk` are client-published; final messages go through the REST API
462
+ * and are echoed by the server.
463
+ */
272
464
  async publish(channelName, eventName, data) {
273
465
  const channel = this.channels.get(channelName);
274
466
  if (!channel) {
@@ -280,6 +472,10 @@ var AblyManager = class {
280
472
  get connectionId() {
281
473
  return this.ably?.connection.id;
282
474
  }
475
+ /** The clientId this connection authenticated as (from the token in API-key mode). */
476
+ get clientId() {
477
+ return this.ably?.auth.clientId ?? void 0;
478
+ }
283
479
  /** Leave presence on all channels and close the connection. */
284
480
  async disconnect() {
285
481
  for (const channel of this.channels.values()) {
@@ -310,44 +506,90 @@ var MessageContext = class {
310
506
  conversationHistory;
311
507
  /** The project ID this message was received on. */
312
508
  projectId;
313
- responseId;
509
+ /** The agent's server-side id (sent as `agentId` on every save). */
510
+ agentId;
511
+ /** The agent's display name. */
512
+ agentName;
513
+ /** Id of the message being responded to (if any). */
514
+ incomingMessageId;
515
+ /**
516
+ * The id the final reply will be stored under. Also the `responseId` sent
517
+ * with `typing` so clients can pre-create the bubble.
518
+ */
519
+ messageId;
314
520
  ablyManager;
315
521
  channelName;
316
- userId;
317
- agentName;
522
+ from;
318
523
  client;
319
524
  responseDepth;
320
525
  respondingChain;
321
526
  chunkBatchMs;
527
+ tracker;
528
+ /** Set by `stream()` when its generator threw. */
529
+ streamError = void 0;
322
530
  constructor(opts) {
323
531
  this.projectId = opts.projectId;
324
532
  this.channelName = opts.channelName;
325
533
  this.conversationHistory = opts.conversationHistory;
326
534
  this.ablyManager = opts.ablyManager;
327
- this.userId = opts.userId;
535
+ this.from = opts.from;
536
+ this.agentId = opts.agentId;
328
537
  this.agentName = opts.agentName;
329
538
  this.client = opts.client;
539
+ this.incomingMessageId = opts.incomingMessageId;
330
540
  this.responseDepth = opts.incomingDepth + 1;
331
541
  this.respondingChain = [
332
542
  ...opts.incomingChain,
333
543
  opts.agentName.toLowerCase()
334
544
  ];
335
545
  this.chunkBatchMs = opts.chunkBatchMs;
336
- this.responseId = uuidv4();
546
+ this.tracker = opts.tracker;
547
+ this.messageId = uuidv4();
548
+ }
549
+ /** Agent-to-agent hop count this reply will carry (informational). */
550
+ get depth() {
551
+ return this.responseDepth;
552
+ }
553
+ /** Agents that have already responded in this chain, including this one. */
554
+ get chain() {
555
+ return [...this.respondingChain];
556
+ }
557
+ /**
558
+ * Why `stream()` failed, if it did: the error its generator threw;
559
+ * `undefined` otherwise. The failure has already been stored under this
560
+ * reply's id as an `error` bubble, and `stream()` resolved with the
561
+ * partial text.
562
+ */
563
+ get error() {
564
+ return this.streamError;
337
565
  }
338
- /** One-shot reply: publishes typing → response in sequence. */
339
- async reply(text) {
566
+ /**
567
+ * One-shot reply: publishes `typing`, then POSTs the final message.
568
+ * Throws if the server rejects it (remote bubbles are closed first — see
569
+ * `deliver`).
570
+ */
571
+ async reply(text, opts) {
340
572
  await this.publishTyping();
341
- await this.publishResponse(text);
342
- this.persistAsync(text, "response");
573
+ return this.deliver(text, "response", this.parentFor(opts));
574
+ }
575
+ /** Replies thread under the answered message unless overridden. */
576
+ parentFor(opts) {
577
+ return opts?.parentMessageId ?? this.incomingMessageId;
343
578
  }
344
579
  /**
345
580
  * Streaming reply: consumes an async generator, batches chunks to Ably
346
- * every chunkBatchMs (default 200ms), then publishes the final response.
581
+ * every chunkBatchMs (default 200ms), then POSTs the final message.
582
+ * Resolves with the full response text.
583
+ *
584
+ * A provider error (the generator throwing) does not reject: the failure
585
+ * is stored under the same id as an `error` bubble, exposed as `error`,
586
+ * and the text streamed so far is returned. Only a delivery failure — the
587
+ * server rejecting the final POST after the retry — rejects, and remote
588
+ * bubbles are closed before it does.
347
589
  *
348
- * Mirrors useAbly.ts lines 86-102 chunk batching pattern.
590
+ * Mirrors useAbly.ts chunk batching pattern.
349
591
  */
350
- async stream(generator) {
592
+ async stream(generator, opts) {
351
593
  await this.publishTyping();
352
594
  let fullText = "";
353
595
  let chunkBuffer = "";
@@ -356,173 +598,190 @@ var MessageContext = class {
356
598
  if (!chunkBuffer) return;
357
599
  const text = chunkBuffer;
358
600
  chunkBuffer = "";
359
- await this.publishChunk(text);
601
+ try {
602
+ await this.publishChunk(text);
603
+ } catch (e) {
604
+ console.warn("[sdk] chunk publish failed:", e instanceof Error ? e.message : e);
605
+ }
360
606
  };
361
607
  try {
362
608
  for await (const chunk of generator()) {
363
609
  fullText += chunk;
364
610
  chunkBuffer += chunk;
365
611
  if (!flushTimer) {
366
- flushTimer = setTimeout(async () => {
612
+ flushTimer = setTimeout(() => {
367
613
  flushTimer = null;
368
- await flushChunks();
614
+ void flushChunks();
369
615
  }, this.chunkBatchMs);
370
616
  }
371
617
  }
372
618
  if (flushTimer) clearTimeout(flushTimer);
373
619
  await flushChunks();
374
- await this.publishResponse(fullText);
375
- this.persistAsync(fullText, "response");
376
620
  } catch (err) {
377
621
  if (flushTimer) clearTimeout(flushTimer);
622
+ this.streamError = err;
378
623
  const errText = `Agent error: ${err instanceof Error ? err.message : String(err)}`;
379
- await this.publishError(errText);
380
- this.persistAsync(errText, "error");
624
+ try {
625
+ await this.deliver(errText, "error", this.parentFor(opts));
626
+ } catch (e) {
627
+ console.error("[sdk] Failed to persist error message:", e);
628
+ }
629
+ return fullText;
381
630
  }
631
+ await this.deliver(fullText, "response", this.parentFor(opts));
632
+ return fullText;
382
633
  }
383
634
  // ── Internal publish helpers ────────────────────────────────────────
384
635
  async publishTyping() {
385
636
  await this.ablyManager.publish(this.channelName, "message", {
386
- from: this.userId,
637
+ from: this.from,
387
638
  fromUsername: this.agentName,
388
639
  projectId: this.projectId,
389
640
  text: "",
390
641
  messageId: uuidv4(),
391
- responseId: this.responseId,
642
+ responseId: this.messageId,
392
643
  type: "typing",
393
- agentName: this.agentName
644
+ agentName: this.agentName,
645
+ agentId: this.agentId
394
646
  });
395
647
  }
396
648
  async publishChunk(text) {
397
649
  await this.ablyManager.publish(this.channelName, "message", {
398
- from: this.userId,
650
+ from: this.from,
399
651
  fromUsername: this.agentName,
400
652
  projectId: this.projectId,
401
653
  text,
402
- messageId: this.responseId,
654
+ messageId: this.messageId,
403
655
  type: "chunk",
404
- agentName: this.agentName
405
- });
406
- }
407
- async publishResponse(text) {
408
- await this.ablyManager.publish(this.channelName, "message", {
409
- from: this.userId,
410
- fromUsername: this.agentName,
411
- projectId: this.projectId,
412
- text,
413
- messageId: this.responseId,
414
- type: "response",
415
656
  agentName: this.agentName,
416
- isAgentMessage: true,
417
- responseDepth: this.responseDepth,
418
- respondingChain: this.respondingChain
657
+ agentId: this.agentId
419
658
  });
420
659
  }
421
- async publishError(text) {
422
- await this.ablyManager.publish(this.channelName, "message", {
423
- from: this.userId,
424
- fromUsername: this.agentName,
425
- projectId: this.projectId,
426
- text,
427
- messageId: this.responseId,
428
- type: "error",
429
- agentName: this.agentName
430
- });
660
+ /**
661
+ * POST this reply's final message. If the server rejects it (after
662
+ * `persistMessage`'s single retry), every other client is stuck on the
663
+ * streaming bubble our `typing`/`chunk` events opened — the server echo
664
+ * that would close it is never coming. Close them with a client-published
665
+ * `error` event under the same id (ephemeral: the server does not persist
666
+ * it, acceptable for a last resort), then rethrow.
667
+ */
668
+ async deliver(text, type, parentMessageId) {
669
+ try {
670
+ return await this.persist(this.messageId, text, type, parentMessageId);
671
+ } catch (err) {
672
+ await this.publishDeliveryFailure(
673
+ err instanceof Error ? err.message : String(err),
674
+ parentMessageId
675
+ );
676
+ throw err;
677
+ }
431
678
  }
432
- /** Fire-and-forget persist to server. */
433
- persistAsync(text, type) {
434
- this.client.persistMessage(this.projectId, {
435
- id: this.responseId,
436
- senderType: "agent",
437
- senderName: this.agentName,
438
- type,
439
- text
440
- }).catch((err) => {
441
- console.error("[sdk] Failed to persist message:", err);
442
- });
679
+ /** Same wire shape as the desktop's delivery-failure fallback (useAbly.ts deliver()). */
680
+ async publishDeliveryFailure(reason, parentMessageId) {
681
+ try {
682
+ await this.ablyManager.publish(this.channelName, "message", {
683
+ from: this.from,
684
+ fromUsername: this.agentName,
685
+ projectId: this.projectId,
686
+ text: `Delivery failed: ${reason}`,
687
+ messageId: this.messageId,
688
+ type: "error",
689
+ agentName: this.agentName,
690
+ agentId: this.agentId,
691
+ isAgentMessage: true,
692
+ parentMessageId
693
+ });
694
+ } catch (e) {
695
+ console.warn("[sdk] delivery-failure publish failed:", e instanceof Error ? e.message : e);
696
+ }
697
+ }
698
+ /** POST the final message. Throws if the server rejects it. */
699
+ async persist(id, text, type, parentMessageId) {
700
+ this.tracker?.begin(id, this.projectId, text, type, parentMessageId);
701
+ try {
702
+ const saved = await this.client.persistMessage(this.projectId, {
703
+ id,
704
+ agentId: this.agentId,
705
+ type,
706
+ text,
707
+ parentMessageId
708
+ });
709
+ this.tracker?.posted(id);
710
+ return saved;
711
+ } catch (err) {
712
+ this.tracker?.failed(id);
713
+ throw err;
714
+ }
443
715
  }
444
716
  };
445
717
  var TaskContext = class {
446
718
  task;
447
719
  projectId;
448
720
  conversationHistory;
449
- ablyManager;
450
- channelName;
451
- userId;
721
+ agentId;
452
722
  agentName;
453
723
  client;
724
+ tracker;
454
725
  constructor(opts) {
455
726
  this.task = opts.task;
456
727
  this.projectId = opts.projectId;
457
- this.channelName = opts.channelName;
458
728
  this.conversationHistory = opts.conversationHistory;
459
- this.ablyManager = opts.ablyManager;
460
- this.userId = opts.userId;
729
+ this.agentId = opts.agentId;
461
730
  this.agentName = opts.agentName;
462
731
  this.client = opts.client;
732
+ this.tracker = opts.tracker;
463
733
  }
464
- /** Mark task as completed, optionally publishing a response message. */
734
+ /** Mark task as completed, optionally posting a response message. */
465
735
  async complete(resultText) {
466
736
  await this.client.updateTask(this.task.id, { status: "completed" });
467
737
  if (resultText) {
468
738
  await this.sendMessage(resultText);
469
739
  }
470
740
  }
471
- /** Mark task as failed, optionally publishing an error message. */
741
+ /** Mark task as failed, optionally posting an error message. */
472
742
  async fail(errorText) {
473
743
  await this.client.updateTask(this.task.id, { status: "failed" });
474
744
  if (errorText) {
475
- const msgId = uuidv4();
476
- await this.ablyManager.publish(this.channelName, "message", {
477
- from: this.userId,
478
- fromUsername: this.agentName,
479
- projectId: this.projectId,
480
- text: errorText,
481
- messageId: msgId,
482
- type: "error",
483
- agentName: this.agentName
484
- });
485
- this.client.persistMessage(this.projectId, {
486
- id: msgId,
487
- senderType: "agent",
488
- senderName: this.agentName,
489
- type: "error",
490
- text: errorText
491
- }).catch((err) => console.error("[sdk] Failed to persist:", err));
745
+ await this.sendMessage(errorText, { type: "error" });
492
746
  }
493
747
  }
494
748
  /**
495
749
  * Create a follow-up task assigned to another agent.
496
- * Automatically sets parentTaskId to the current task's ID.
750
+ * Automatically sets parentTaskId to the current task's ID and attributes
751
+ * creation to this agent.
497
752
  */
498
753
  async createFollowUpTask(data) {
499
754
  return this.client.createTask(this.projectId, {
500
755
  ...data,
501
756
  parentTaskId: this.task.id,
502
757
  createdByType: "agent",
503
- createdByName: this.agentName
758
+ createdByName: this.agentName,
759
+ createdByAgentId: this.agentId
504
760
  });
505
761
  }
506
- /** Send a chat message (for progress updates). */
507
- async sendMessage(text) {
762
+ /**
763
+ * Post a chat message (for progress updates). Returns the stored message.
764
+ * `type` defaults to "response"; use "message" for notices that must never
765
+ * trigger other agents (agent-to-agent chaining only flows through responses).
766
+ */
767
+ async sendMessage(text, opts) {
508
768
  const msgId = uuidv4();
509
- await this.ablyManager.publish(this.channelName, "message", {
510
- from: this.userId,
511
- fromUsername: this.agentName,
512
- projectId: this.projectId,
513
- text,
514
- messageId: msgId,
515
- type: "response",
516
- agentName: this.agentName,
517
- isAgentMessage: true
518
- });
519
- this.client.persistMessage(this.projectId, {
520
- id: msgId,
521
- senderType: "agent",
522
- senderName: this.agentName,
523
- type: "response",
524
- text
525
- }).catch((err) => console.error("[sdk] Failed to persist:", err));
769
+ const type = opts?.type ?? "response";
770
+ this.tracker?.begin(msgId, this.projectId, text, type, opts?.parentMessageId);
771
+ try {
772
+ const saved = await this.client.persistMessage(this.projectId, {
773
+ id: msgId,
774
+ agentId: this.agentId,
775
+ type,
776
+ text,
777
+ parentMessageId: opts?.parentMessageId
778
+ });
779
+ this.tracker?.posted(msgId);
780
+ return saved;
781
+ } catch (err) {
782
+ this.tracker?.failed(msgId);
783
+ throw err;
784
+ }
526
785
  }
527
786
  };
528
787
 
@@ -538,7 +797,7 @@ function escapeRegex(s) {
538
797
  // src/providers/anthropic.ts
539
798
  var ANTHROPIC_API_URL = "https://api.anthropic.com/v1/messages";
540
799
  var ANTHROPIC_VERSION = "2024-10-22";
541
- var DEFAULT_MODEL = "claude-sonnet-4-6";
800
+ var DEFAULT_MODEL = "claude-sonnet-5";
542
801
  var DEFAULT_MAX_TOKENS = 8192;
543
802
  var AnthropicProvider = class {
544
803
  apiKey;
@@ -927,82 +1186,262 @@ ${systemPrompt}
927
1186
  var DEFAULT_MAX_DEPTH = 3;
928
1187
  var DEFAULT_CHUNK_BATCH_MS = 200;
929
1188
  var DEFAULT_CONTEXT_WINDOW = 20;
930
- var JaibberAgent = class extends EventEmitter {
1189
+ var DEFAULT_HEARTBEAT_MS = 12e4;
1190
+ var OWN_MESSAGE_MEMORY = 1e3;
1191
+ var MESSAGE_INDEX_SIZE = 500;
1192
+ var META_TTL_MS = 5 * 60 * 1e3;
1193
+ 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.";
1194
+ var JaibberAgent = class _JaibberAgent extends EventEmitter {
931
1195
  config;
932
1196
  client;
933
1197
  ablyManager = null;
934
1198
  messageHandler = null;
935
1199
  taskHandler = null;
936
1200
  provider = null;
1201
+ providerKind = null;
937
1202
  connected = false;
938
1203
  projects = [];
939
1204
  unsubscribers = [];
1205
+ heartbeatTimer = null;
1206
+ agentId = null;
1207
+ agentRecord = null;
1208
+ keyIdentity = null;
940
1209
  /** In-memory conversation history per project. */
941
1210
  history = /* @__PURE__ */ new Map();
1211
+ /** Recent messages per project (id → author/parent) for chain reconstruction. */
1212
+ messageIndex = /* @__PURE__ */ new Map();
942
1213
  /** Track in-flight responses to prevent double-handling. */
943
1214
  activeResponses = /* @__PURE__ */ new Set();
944
1215
  /** Session IDs per project for Claude --resume. */
945
1216
  sessionIds = /* @__PURE__ */ new Map();
1217
+ /** Messages we POSTed ourselves, keyed by id — for echo dedupe + own-reply history. */
1218
+ ownMessages = /* @__PURE__ */ new Map();
1219
+ /** `meta` hints waiting for their server echo. */
1220
+ pendingMeta = /* @__PURE__ */ new Map();
1221
+ /**
1222
+ * Safety valve: unthreaded agent responses (no `parentMessageId`) seen per
1223
+ * project since the last human message. Threaded chains are bounded by the
1224
+ * `parentMessageId` walk; this catches agents that post without threading,
1225
+ * which would otherwise look like a fresh depth-1 chain every time.
1226
+ */
1227
+ unthreadedHops = /* @__PURE__ */ new Map();
946
1228
  constructor(config) {
947
1229
  super();
948
1230
  this.config = config;
949
1231
  this.client = new JaibberClient(config.serverUrl);
1232
+ this.on("error", _JaibberAgent.defaultErrorListener);
1233
+ }
1234
+ /**
1235
+ * Default `"error"` listener, registered by the constructor: logs the error
1236
+ * and keeps the process alive. To handle errors yourself without the log,
1237
+ * remove it: `agent.off("error", JaibberAgent.defaultErrorListener)`.
1238
+ */
1239
+ static defaultErrorListener = (err) => {
1240
+ console.error("[jaibber-agent] error:", err);
1241
+ };
1242
+ /** Emit `"error"` without ever throwing, even if every listener was removed. */
1243
+ emitError(err) {
1244
+ if (this.listenerCount("error") === 0) {
1245
+ _JaibberAgent.defaultErrorListener(err);
1246
+ return;
1247
+ }
1248
+ this.emit("error", err);
1249
+ }
1250
+ // ── Accessors ───────────────────────────────────────────────────────
1251
+ /** The agent's server-side id (available after `connect()`). */
1252
+ get id() {
1253
+ return this.agentId;
1254
+ }
1255
+ /** The agent record returned by the server (session mode only). */
1256
+ get record() {
1257
+ return this.agentRecord;
1258
+ }
1259
+ /** The key's agent identity from `GET /api/me` (API-key mode, on servers that have it). */
1260
+ get identity() {
1261
+ return this.keyIdentity;
1262
+ }
1263
+ /** The underlying REST client (authenticated after `connect()`). */
1264
+ get api() {
1265
+ return this.client;
1266
+ }
1267
+ /** Projects this agent has joined. */
1268
+ get joinedProjects() {
1269
+ return [...this.projects];
1270
+ }
1271
+ /** Sender id used on client-published typing/chunk events. */
1272
+ get senderId() {
1273
+ return this.client.userId ?? `agent:${this.agentId ?? "unknown"}`;
1274
+ }
1275
+ get maxDepth() {
1276
+ return this.config.maxResponseDepth ?? DEFAULT_MAX_DEPTH;
950
1277
  }
951
1278
  // ── Lifecycle ───────────────────────────────────────────────────────
952
- /** Authenticate, connect Ably, subscribe to project channels. */
1279
+ /** Authenticate, register/resolve the agent, connect Ably, subscribe to project channels. */
953
1280
  async connect() {
954
1281
  if (this.connected) throw new Error("Already connected");
955
- const { username: username2, password: password2 } = this.config.credentials;
956
- console.log(`[sdk] Logging in as "${username2}"...`);
957
- await this.client.login(username2, password2);
958
- const userId = this.client.userId;
959
- const displayName = this.client.username;
1282
+ const creds = this.config.credentials;
1283
+ const apiKeyMode = "apiKey" in creds;
1284
+ if (apiKeyMode) {
1285
+ this.client.setApiKey(creds.apiKey);
1286
+ this.agentId = this.config.agentId ?? null;
1287
+ console.log(`[sdk] Authenticating with agent API key ${creds.apiKey.slice(0, 11)}\u2026`);
1288
+ await this.resolveKeyIdentity();
1289
+ } else {
1290
+ console.log(`[sdk] Logging in as "${creds.username}"...`);
1291
+ await this.client.login(creds.username, creds.password);
1292
+ const record = await this.client.ensureAgent({
1293
+ name: this.config.agentName,
1294
+ instructions: this.config.agentInstructions,
1295
+ provider: this.resolveProviderKind(),
1296
+ kind: "sdk",
1297
+ machineName: this.config.machineName,
1298
+ orgId: this.config.orgId
1299
+ });
1300
+ this.agentId = record.id;
1301
+ this.agentRecord = record;
1302
+ this.config.agentId = record.id;
1303
+ console.log(`[sdk] Agent "${record.name}" registered (id ${record.id})`);
1304
+ }
960
1305
  const allProjects = await this.client.listProjects();
961
- this.projects = this.config.projectIds ? allProjects.filter((p) => this.config.projectIds.includes(p.id)) : allProjects;
1306
+ if (this.config.projectIds) {
1307
+ const wanted = new Set(this.config.projectIds);
1308
+ this.projects = allProjects.filter((p) => wanted.has(p.id));
1309
+ const missing = this.config.projectIds.filter(
1310
+ (id) => !this.projects.some((p) => p.id === id)
1311
+ );
1312
+ if (missing.length > 0) {
1313
+ console.warn(`[sdk] Project(s) not accessible, skipping: ${missing.join(", ")}`);
1314
+ }
1315
+ } else {
1316
+ this.projects = allProjects.filter((p) => p.role !== "org-admin");
1317
+ }
962
1318
  if (this.projects.length === 0) {
963
1319
  throw new Error(
964
- "No projects found. Ensure the agent account is a member of at least one project."
1320
+ 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."
965
1321
  );
966
1322
  }
967
1323
  console.log(
968
1324
  `[sdk] Found ${this.projects.length} project(s): ${this.projects.map((p) => p.name).join(", ")}`
969
1325
  );
970
- this.ablyManager = new AblyManager(this.client, userId, displayName);
1326
+ if (!apiKeyMode) {
1327
+ for (const project of this.projects) {
1328
+ try {
1329
+ await this.client.assignAgent(this.agentId, project.id);
1330
+ } catch (err) {
1331
+ console.warn(
1332
+ `[sdk] Could not assign agent to "${project.name}": ${err instanceof Error ? err.message : err}`
1333
+ );
1334
+ }
1335
+ }
1336
+ }
1337
+ this.ablyManager = new AblyManager(this.client, {
1338
+ clientId: apiKeyMode ? void 0 : this.client.userId,
1339
+ username: this.config.agentName
1340
+ });
971
1341
  await this.ablyManager.connect();
972
- await this.ablyManager.enterGlobalPresence(
973
- this.projects.map((p) => p.id)
974
- );
975
- for (const project of this.projects) {
1342
+ try {
1343
+ if (!this.agentId) {
1344
+ const cid = this.ablyManager.clientId;
1345
+ if (cid && cid.startsWith("agent:")) {
1346
+ this.agentId = cid.slice("agent:".length);
1347
+ this.config.agentId = this.agentId;
1348
+ } else {
1349
+ throw new Error(
1350
+ `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\`.`
1351
+ );
1352
+ }
1353
+ }
1354
+ this.startHeartbeat();
1355
+ await this.ablyManager.enterGlobalPresence({
1356
+ userId: this.client.userId ?? void 0,
1357
+ agentId: this.agentId,
1358
+ username: this.config.agentName,
1359
+ projectIds: this.projects.map((p) => p.id)
1360
+ });
976
1361
  const presenceData = {
977
- userId,
1362
+ userId: this.client.userId ?? void 0,
978
1363
  username: this.config.agentName,
979
1364
  isAgent: true,
980
1365
  agentName: this.config.agentName,
1366
+ agentId: this.agentId,
981
1367
  agentInstructions: this.config.agentInstructions,
982
1368
  agents: [
983
1369
  {
1370
+ agentId: this.agentId,
984
1371
  agentName: this.config.agentName,
985
1372
  agentInstructions: this.config.agentInstructions
986
1373
  }
987
1374
  ],
988
1375
  machineName: this.config.machineName
989
1376
  };
990
- await this.loadHistory(project.id);
991
- const unsub = await this.ablyManager.subscribeToProject(
992
- project,
993
- presenceData,
994
- (msg) => this.handleIncomingMessage(msg, project),
995
- (data) => this.handleTaskEvent(data, project)
996
- );
997
- this.unsubscribers.push(unsub);
1377
+ for (const project of this.projects) {
1378
+ await this.loadHistory(project.id);
1379
+ const unsub = await this.ablyManager.subscribeToProject(
1380
+ project,
1381
+ presenceData,
1382
+ (msg) => this.handleIncomingMessage(msg, project),
1383
+ (data) => this.handleTaskEvent(data, project),
1384
+ (data) => this.handleControlEvent(data, project),
1385
+ (err) => this.emitError(err)
1386
+ );
1387
+ this.unsubscribers.push(unsub);
1388
+ }
1389
+ } catch (err) {
1390
+ this.stopHeartbeat();
1391
+ for (const unsub of this.unsubscribers) unsub();
1392
+ this.unsubscribers = [];
1393
+ await this.ablyManager.disconnect().catch(() => {
1394
+ });
1395
+ this.ablyManager = null;
1396
+ throw err;
998
1397
  }
999
1398
  this.connected = true;
1000
- console.log(`[sdk] Agent "${this.config.agentName}" connected and listening`);
1399
+ console.log(
1400
+ `[sdk] Agent "${this.config.agentName}" (${this.agentId}) connected and listening`
1401
+ );
1001
1402
  this.emit("connected", this.projects);
1002
1403
  }
1003
- /** Leave presence, disconnect Ably. */
1404
+ /**
1405
+ * API-key mode: ask the server who the key is (`GET /api/me`) so the agent
1406
+ * id and name are known before Ably connects. Servers that predate the
1407
+ * endpoint answer 404; the id is then read from the Ably token's clientId
1408
+ * (`agent:{id}`) once connected, as in 0.4.0.
1409
+ */
1410
+ async resolveKeyIdentity() {
1411
+ const me = await this.client.whoAmI();
1412
+ if (me === null) {
1413
+ console.warn(
1414
+ "[sdk] GET /api/me is not available on this server; the agent id will be read from the Ably token."
1415
+ );
1416
+ return;
1417
+ }
1418
+ if (me.type !== "agent") {
1419
+ throw new Error(
1420
+ `The API key is not bound to an agent (GET /api/me reports type "${me.type}"). Mint an agent key with POST /api/me/agents/:id/keys or \`jaibber-agent --create-key\`.`
1421
+ );
1422
+ }
1423
+ if (this.agentId && this.agentId !== me.agentId) {
1424
+ console.warn(
1425
+ `[sdk] Configured agentId ${this.agentId} does not match the key's agent ${me.agentId}; using the key's.`
1426
+ );
1427
+ }
1428
+ this.agentId = me.agentId;
1429
+ this.config.agentId = me.agentId;
1430
+ this.keyIdentity = me;
1431
+ if (me.name && me.name.toLowerCase() !== this.config.agentName.toLowerCase()) {
1432
+ console.warn(
1433
+ `[sdk] agentName "${this.config.agentName}" differs from the key's agent "${me.name}"; using "${me.name}".`
1434
+ );
1435
+ this.config.agentName = me.name;
1436
+ }
1437
+ console.log(
1438
+ `[sdk] Authenticated as agent "${me.name}" (id ${me.agentId}${me.org ? `, org ${me.org.slug}` : ""})`
1439
+ );
1440
+ }
1441
+ /** Stop heartbeats, leave presence, disconnect Ably. */
1004
1442
  async disconnect() {
1005
1443
  if (!this.connected) return;
1444
+ this.stopHeartbeat();
1006
1445
  for (const unsub of this.unsubscribers) {
1007
1446
  unsub();
1008
1447
  }
@@ -1027,51 +1466,192 @@ var JaibberAgent = class extends EventEmitter {
1027
1466
  switch (name) {
1028
1467
  case "anthropic":
1029
1468
  this.provider = new AnthropicProvider(options);
1469
+ this.providerKind = "claude";
1030
1470
  break;
1031
1471
  case "openai":
1032
1472
  this.provider = new OpenAIProvider(options);
1473
+ this.providerKind = "openai";
1033
1474
  break;
1034
1475
  case "google":
1035
1476
  this.provider = new GoogleProvider(options);
1477
+ this.providerKind = "google";
1036
1478
  break;
1037
1479
  case "claude-cli":
1038
1480
  this.provider = new ClaudeCLIProvider(options);
1481
+ this.providerKind = "claude";
1039
1482
  break;
1040
1483
  }
1041
1484
  }
1485
+ /** Provider label stored on the agent record. */
1486
+ resolveProviderKind() {
1487
+ return this.config.provider ?? this.providerKind ?? "custom";
1488
+ }
1489
+ // ── Heartbeat ───────────────────────────────────────────────────────
1490
+ startHeartbeat() {
1491
+ this.stopHeartbeat();
1492
+ const beat = async () => {
1493
+ if (!this.agentId) return;
1494
+ try {
1495
+ await this.client.heartbeat(this.agentId);
1496
+ } catch (err) {
1497
+ console.warn(`[sdk] Heartbeat failed: ${err instanceof Error ? err.message : err}`);
1498
+ }
1499
+ };
1500
+ void beat();
1501
+ this.heartbeatTimer = setInterval(beat, this.config.heartbeatMs ?? DEFAULT_HEARTBEAT_MS);
1502
+ this.heartbeatTimer.unref?.();
1503
+ }
1504
+ stopHeartbeat() {
1505
+ if (this.heartbeatTimer) {
1506
+ clearInterval(this.heartbeatTimer);
1507
+ this.heartbeatTimer = null;
1508
+ }
1509
+ }
1510
+ // ── Message index / chain reconstruction ────────────────────────────
1511
+ indexMessage(projectId, id, entry) {
1512
+ const idx = this.messageIndex.get(projectId) ?? /* @__PURE__ */ new Map();
1513
+ idx.delete(id);
1514
+ idx.set(id, entry);
1515
+ while (idx.size > MESSAGE_INDEX_SIZE) {
1516
+ const oldest = idx.keys().next().value;
1517
+ if (oldest === void 0) break;
1518
+ idx.delete(oldest);
1519
+ }
1520
+ this.messageIndex.set(projectId, idx);
1521
+ }
1522
+ /**
1523
+ * Loop prevention for agent-to-agent chains. The server echo carries no
1524
+ * chain metadata, so the chain is reconstructed from `parentMessageId`
1525
+ * links: every agent response is posted as a reply to the message it
1526
+ * answered. Returns the number of consecutive agent hops ending at
1527
+ * `payload` (the depth) and the lowercased names of the agents in that run.
1528
+ * Mirrors useAbly.ts agentChainFor().
1529
+ */
1530
+ agentChainFor(projectId, payload) {
1531
+ const idx = this.messageIndex.get(projectId);
1532
+ const chain = [(payload.agentName ?? payload.fromUsername).toLowerCase()];
1533
+ let parentId = payload.parentMessageId;
1534
+ let guard = 0;
1535
+ while (parentId && guard++ < 50) {
1536
+ const parent = idx?.get(parentId);
1537
+ if (!parent?.agentId) break;
1538
+ chain.push(parent.senderName.toLowerCase());
1539
+ parentId = parent.parentMessageId;
1540
+ }
1541
+ return { depth: chain.length, chain };
1542
+ }
1543
+ // ── `meta` hints ────────────────────────────────────────────────────
1544
+ rememberMeta(messageId, meta) {
1545
+ const cutoff = Date.now() - META_TTL_MS;
1546
+ for (const [id, m] of this.pendingMeta) {
1547
+ if (m.receivedAt < cutoff) this.pendingMeta.delete(id);
1548
+ }
1549
+ this.pendingMeta.set(messageId, meta);
1550
+ }
1551
+ takeMeta(messageId, senderId) {
1552
+ const meta = this.pendingMeta.get(messageId);
1553
+ if (!meta) return void 0;
1554
+ this.pendingMeta.delete(messageId);
1555
+ return meta.clientId === senderId ? meta : void 0;
1556
+ }
1557
+ // ── Own-message tracking (echo dedupe + own replies in history) ─────
1558
+ tracker = {
1559
+ begin: (id, projectId, text, type, parentMessageId) => {
1560
+ this.ownMessages.set(id, { projectId, text, type, recorded: false });
1561
+ while (this.ownMessages.size > OWN_MESSAGE_MEMORY) {
1562
+ const oldest = this.ownMessages.keys().next().value;
1563
+ if (oldest === void 0) break;
1564
+ this.ownMessages.delete(oldest);
1565
+ }
1566
+ this.indexMessage(projectId, id, {
1567
+ agentId: this.agentId ?? void 0,
1568
+ senderName: this.config.agentName,
1569
+ parentMessageId
1570
+ });
1571
+ },
1572
+ posted: (id) => this.recordOwnMessage(id),
1573
+ failed: (id) => {
1574
+ this.ownMessages.delete(id);
1575
+ }
1576
+ };
1577
+ /**
1578
+ * Add one of our own messages to history exactly once — whichever arrives
1579
+ * first: the server's Ably echo or the POST response.
1580
+ */
1581
+ recordOwnMessage(id) {
1582
+ const own = this.ownMessages.get(id);
1583
+ if (!own || own.recorded) return;
1584
+ own.recorded = true;
1585
+ if (own.type === "error") return;
1586
+ this.addToHistory(own.projectId, {
1587
+ sender: "agent",
1588
+ senderName: this.config.agentName,
1589
+ text: own.text,
1590
+ agentId: this.agentId ?? void 0
1591
+ });
1592
+ }
1042
1593
  // ── Message handling ────────────────────────────────────────────────
1043
1594
  async handleIncomingMessage(payload, project) {
1044
1595
  if (payload._connectionId && payload._connectionId === this.ablyManager?.connectionId) return;
1045
- if (payload.type === "deregister") {
1046
- const targetName = payload.agentName?.toLowerCase();
1047
- if (!targetName || targetName === this.config.agentName.toLowerCase()) {
1048
- console.log(`[sdk] Received deregister command. Shutting down...`);
1049
- await this.disconnect();
1050
- process.exit(0);
1051
- }
1596
+ if (payload.type === "meta") {
1597
+ if (!payload._clientId) return;
1598
+ this.rememberMeta(payload.messageId, {
1599
+ clientId: payload._clientId,
1600
+ executionMode: payload.executionMode,
1601
+ attachments: payload.attachments,
1602
+ receivedAt: Date.now()
1603
+ });
1052
1604
  return;
1053
1605
  }
1054
- if (payload.isTaskNotification) return;
1055
1606
  if (payload.type !== "message" && payload.type !== "response") return;
1607
+ if (this.ownMessages.has(payload.messageId)) {
1608
+ this.recordOwnMessage(payload.messageId);
1609
+ return;
1610
+ }
1056
1611
  if (payload.text && payload.text.length > 1e5) {
1057
1612
  console.warn(`[sdk] Ignoring oversized message (${payload.text.length} chars)`);
1058
1613
  return;
1059
1614
  }
1615
+ const isAgent = payload.isAgentMessage === true || !!payload.agentId;
1616
+ const isSelf = !!this.agentId && payload.agentId === this.agentId;
1617
+ this.indexMessage(project.id, payload.messageId, {
1618
+ agentId: payload.agentId,
1619
+ senderName: payload.agentName ?? payload.fromUsername,
1620
+ parentMessageId: payload.parentMessageId
1621
+ });
1622
+ if (!isAgent) this.unthreadedHops.set(project.id, 0);
1060
1623
  this.addToHistory(project.id, {
1061
- sender: payload.isAgentMessage ? "agent" : "user",
1624
+ sender: isAgent ? "agent" : "user",
1062
1625
  senderName: payload.fromUsername,
1063
- text: payload.text
1626
+ text: payload.text,
1627
+ agentId: payload.agentId
1064
1628
  });
1065
- const depth = payload.responseDepth ?? 0;
1066
- const chain = payload.respondingChain ?? [];
1629
+ if (isSelf) return;
1630
+ if (payload.isTaskNotification) return;
1631
+ let depth = 0;
1632
+ let chain = [];
1633
+ let executionMode = payload.executionMode;
1634
+ let attachments = payload.attachments;
1635
+ if (isAgent) {
1636
+ if (payload.type !== "response") return;
1637
+ ({ depth, chain } = this.agentChainFor(project.id, payload));
1638
+ if (!payload.parentMessageId) {
1639
+ const n = (this.unthreadedHops.get(project.id) ?? 0) + 1;
1640
+ this.unthreadedHops.set(project.id, n);
1641
+ if (n > this.maxDepth) return;
1642
+ }
1643
+ } else {
1644
+ const meta = this.takeMeta(payload.messageId, payload.from);
1645
+ executionMode = executionMode ?? meta?.executionMode;
1646
+ attachments = attachments ?? meta?.attachments;
1647
+ }
1067
1648
  if (!this.shouldRespond(payload.text, depth, chain)) return;
1068
1649
  if (this.activeResponses.has(payload.messageId)) return;
1069
1650
  this.activeResponses.add(payload.messageId);
1070
1651
  try {
1071
- await this.respondToMessage(payload, project, depth, chain);
1652
+ await this.respondToMessage(payload, project, depth, chain, executionMode, attachments);
1072
1653
  } catch (err) {
1073
- console.error("[sdk] Error responding to message:", err);
1074
- this.emit("error", err);
1654
+ this.emitError(err);
1075
1655
  } finally {
1076
1656
  this.activeResponses.delete(payload.messageId);
1077
1657
  }
@@ -1081,26 +1661,27 @@ var JaibberAgent = class extends EventEmitter {
1081
1661
  * Mirrors useAbly.ts shouldAgentRespond() logic.
1082
1662
  */
1083
1663
  shouldRespond(text, depth, chain) {
1084
- const maxDepth = this.config.maxResponseDepth ?? DEFAULT_MAX_DEPTH;
1085
- if (depth >= maxDepth) return false;
1664
+ if (depth >= this.maxDepth) return false;
1086
1665
  if (chain.includes(this.config.agentName.toLowerCase())) return false;
1087
1666
  if (!mentionsAgent(text, this.config.agentName)) return false;
1088
1667
  return true;
1089
1668
  }
1090
- async respondToMessage(payload, project, incomingDepth, incomingChain) {
1091
- const userId = this.client.userId;
1669
+ async respondToMessage(payload, project, incomingDepth, incomingChain, executionMode, attachments) {
1092
1670
  const conversationHistory = this.getFormattedHistory(project.id);
1093
1671
  const ctx = new MessageContext({
1094
1672
  projectId: project.id,
1095
1673
  channelName: project.ablyChannelName,
1096
1674
  conversationHistory,
1097
1675
  ablyManager: this.ablyManager,
1098
- userId,
1676
+ from: this.senderId,
1677
+ agentId: this.agentId,
1099
1678
  agentName: this.config.agentName,
1100
1679
  client: this.client,
1680
+ incomingMessageId: payload.messageId,
1101
1681
  incomingDepth,
1102
1682
  incomingChain,
1103
- chunkBatchMs: this.config.chunkBatchMs ?? DEFAULT_CHUNK_BATCH_MS
1683
+ chunkBatchMs: this.config.chunkBatchMs ?? DEFAULT_CHUNK_BATCH_MS,
1684
+ tracker: this.tracker
1104
1685
  });
1105
1686
  if (this.messageHandler) {
1106
1687
  await this.messageHandler(
@@ -1113,20 +1694,30 @@ var JaibberAgent = class extends EventEmitter {
1113
1694
  type: payload.type,
1114
1695
  responseDepth: incomingDepth,
1115
1696
  respondingChain: incomingChain,
1116
- executionMode: payload.executionMode,
1697
+ executionMode,
1117
1698
  isAgentMessage: payload.isAgentMessage,
1118
- attachments: payload.attachments
1699
+ agentId: payload.agentId,
1700
+ agentName: payload.agentName,
1701
+ mentions: payload.mentions,
1702
+ parentMessageId: payload.parentMessageId,
1703
+ attachments,
1704
+ createdAt: payload.createdAt
1119
1705
  },
1120
1706
  ctx
1121
1707
  );
1708
+ if (ctx.error !== void 0) this.emitError(ctx.error);
1122
1709
  return;
1123
1710
  }
1124
1711
  if (this.provider) {
1125
1712
  this.updateProviderSession(project.id);
1126
- const systemPrompt = this.config.agentInstructions ?? "";
1713
+ const systemPrompt = this.systemPromptFor(executionMode);
1127
1714
  await ctx.stream(
1128
1715
  () => this.provider.generate(payload.text, systemPrompt, conversationHistory)
1129
1716
  );
1717
+ if (ctx.error !== void 0) {
1718
+ this.emitError(ctx.error);
1719
+ return;
1720
+ }
1130
1721
  this.captureProviderSession(project.id);
1131
1722
  return;
1132
1723
  }
@@ -1134,36 +1725,54 @@ var JaibberAgent = class extends EventEmitter {
1134
1725
  "[sdk] No message handler or provider configured. Ignoring message."
1135
1726
  );
1136
1727
  }
1728
+ /** Agent instructions, prefixed with the plan-mode directive when requested. */
1729
+ systemPromptFor(executionMode) {
1730
+ const instructions2 = this.config.agentInstructions ?? "";
1731
+ if (executionMode !== "plan") return instructions2;
1732
+ return instructions2 ? `${PLAN_MODE_PREFIX}
1733
+
1734
+ ${instructions2}` : PLAN_MODE_PREFIX;
1735
+ }
1736
+ // ── Agent control (server-published lifecycle commands) ─────────────
1737
+ /** Is a server control event addressed to this agent? */
1738
+ isControlForMe(data) {
1739
+ if (this.agentId) return data.agentId === this.agentId;
1740
+ return !!data.agentName && data.agentName.toLowerCase() === this.config.agentName.toLowerCase();
1741
+ }
1742
+ /**
1743
+ * `agent-control` events are published by the server on project channels,
1744
+ * e.g. `{action: "deregister", agentId, agentName}` when an agent is revoked
1745
+ * via the API. Events for other agents are ignored.
1746
+ */
1747
+ async handleControlEvent(data, project) {
1748
+ if (!data || data.action !== "deregister") return;
1749
+ if (!this.isControlForMe(data)) return;
1750
+ console.log(
1751
+ `[sdk] Agent "${this.config.agentName}" was deregistered by the server (via project "${project.name}"). Shutting down...`
1752
+ );
1753
+ try {
1754
+ await this.disconnect();
1755
+ } catch (err) {
1756
+ console.error("[sdk] Error during deregister shutdown:", err);
1757
+ }
1758
+ this.emit("deregistered", data);
1759
+ if (this.config.exitOnDeregister !== false) {
1760
+ process.exit(0);
1761
+ }
1762
+ }
1137
1763
  // ── Task handling ───────────────────────────────────────────────────
1138
1764
  async handleTaskEvent(data, project) {
1139
1765
  if (data.type !== "task-created" && data.type !== "task-updated")
1140
1766
  return;
1141
1767
  const task = data.task;
1142
1768
  if (task.status !== "submitted") return;
1143
- if (!task.assignedAgentName || task.assignedAgentName.toLowerCase() !== this.config.agentName.toLowerCase())
1144
- return;
1769
+ const mine = task.assignedAgentId ? !!this.agentId && task.assignedAgentId === this.agentId : !!task.assignedAgentName && task.assignedAgentName.toLowerCase() === this.config.agentName.toLowerCase();
1770
+ if (!mine) return;
1145
1771
  console.log(
1146
1772
  `[sdk] Picking up task: "${task.title}" (${task.id})`
1147
1773
  );
1148
1774
  try {
1149
1775
  await this.client.updateTask(task.id, { status: "working" });
1150
- const userId = this.client.userId;
1151
- const announceMsgId = uuidv42();
1152
- await this.ablyManager.publish(
1153
- project.ablyChannelName,
1154
- "message",
1155
- {
1156
- from: userId,
1157
- fromUsername: this.config.agentName,
1158
- projectId: project.id,
1159
- text: `Picking up task: **${task.title}**`,
1160
- messageId: announceMsgId,
1161
- type: "message",
1162
- agentName: this.config.agentName,
1163
- isAgentMessage: true,
1164
- isTaskNotification: true
1165
- }
1166
- );
1167
1776
  const conversationHistory = this.getFormattedHistory(project.id);
1168
1777
  const ctx = new TaskContext({
1169
1778
  task,
@@ -1171,10 +1780,19 @@ var JaibberAgent = class extends EventEmitter {
1171
1780
  channelName: project.ablyChannelName,
1172
1781
  conversationHistory,
1173
1782
  ablyManager: this.ablyManager,
1174
- userId,
1783
+ from: this.senderId,
1784
+ agentId: this.agentId,
1175
1785
  agentName: this.config.agentName,
1176
- client: this.client
1786
+ client: this.client,
1787
+ tracker: this.tracker
1177
1788
  });
1789
+ try {
1790
+ await ctx.sendMessage(`Picking up task: **${task.title}**`, { type: "message" });
1791
+ } catch (err) {
1792
+ console.warn(
1793
+ `[sdk] Could not announce task pickup: ${err instanceof Error ? err.message : err}`
1794
+ );
1795
+ }
1178
1796
  if (this.taskHandler) {
1179
1797
  await this.taskHandler(task, ctx);
1180
1798
  return;
@@ -1190,33 +1808,36 @@ ${task.description}` : `Task: ${task.title}`;
1190
1808
  channelName: project.ablyChannelName,
1191
1809
  conversationHistory,
1192
1810
  ablyManager: this.ablyManager,
1193
- userId,
1811
+ from: this.senderId,
1812
+ agentId: this.agentId,
1194
1813
  agentName: this.config.agentName,
1195
1814
  client: this.client,
1196
1815
  incomingDepth: 0,
1197
1816
  incomingChain: [],
1198
- chunkBatchMs: this.config.chunkBatchMs ?? DEFAULT_CHUNK_BATCH_MS
1817
+ chunkBatchMs: this.config.chunkBatchMs ?? DEFAULT_CHUNK_BATCH_MS,
1818
+ tracker: this.tracker
1199
1819
  });
1200
- try {
1201
- await msgCtx.stream(
1202
- () => this.provider.generate(
1203
- taskPrompt,
1204
- systemPrompt,
1205
- conversationHistory
1206
- )
1207
- );
1208
- this.captureProviderSession(project.id);
1209
- await this.client.updateTask(task.id, { status: "completed" });
1210
- } catch {
1820
+ await msgCtx.stream(
1821
+ () => this.provider.generate(
1822
+ taskPrompt,
1823
+ systemPrompt,
1824
+ conversationHistory
1825
+ )
1826
+ );
1827
+ if (msgCtx.error !== void 0) {
1828
+ this.emitError(msgCtx.error);
1211
1829
  await this.client.updateTask(task.id, { status: "failed" });
1830
+ return;
1212
1831
  }
1832
+ this.captureProviderSession(project.id);
1833
+ await this.client.updateTask(task.id, { status: "completed" });
1213
1834
  return;
1214
1835
  }
1215
1836
  console.warn(
1216
1837
  "[sdk] No task handler or provider configured. Task left as working."
1217
1838
  );
1218
1839
  } catch (err) {
1219
- console.error("[sdk] Error handling task:", err);
1840
+ this.emitError(err);
1220
1841
  try {
1221
1842
  await this.client.updateTask(task.id, { status: "failed" });
1222
1843
  } catch {
@@ -1245,6 +1866,11 @@ ${task.description}` : `Task: ${task.title}`;
1245
1866
  }
1246
1867
  }
1247
1868
  // ── Conversation history ────────────────────────────────────────────
1869
+ /** Is this stored message one of this agent's own prior replies? */
1870
+ isOwnServerMessage(m) {
1871
+ if (this.agentId && m.senderAgentId === this.agentId) return true;
1872
+ return m.senderType === "agent" && m.senderName.toLowerCase() === this.config.agentName.toLowerCase();
1873
+ }
1248
1874
  async loadHistory(projectId) {
1249
1875
  const contextSize = this.config.contextWindowSize ?? DEFAULT_CONTEXT_WINDOW;
1250
1876
  try {
@@ -1252,12 +1878,30 @@ ${task.description}` : `Task: ${task.title}`;
1252
1878
  projectId,
1253
1879
  contextSize
1254
1880
  );
1255
- const entries = messages.reverse().map((m) => ({
1256
- sender: m.senderType === "user" ? "user" : "agent",
1257
- senderName: m.senderName,
1258
- text: m.text
1259
- }));
1260
- this.history.set(projectId, entries);
1881
+ const first = messages[0];
1882
+ const last = messages[messages.length - 1];
1883
+ if (first && last && first !== last && first.createdAt > last.createdAt) {
1884
+ messages.reverse();
1885
+ }
1886
+ const entries = [];
1887
+ for (const m of messages) {
1888
+ const own = this.isOwnServerMessage(m);
1889
+ const agentId = m.senderAgentId ?? (own ? this.agentId ?? void 0 : void 0);
1890
+ this.indexMessage(projectId, m.id, {
1891
+ agentId,
1892
+ senderName: own ? this.config.agentName : m.senderName,
1893
+ parentMessageId: m.parentMessageId ?? void 0
1894
+ });
1895
+ if (m.type === "system" || !m.text) continue;
1896
+ const sender = own || m.senderType === "agent" ? "agent" : "user";
1897
+ entries.push({
1898
+ sender,
1899
+ senderName: own ? this.config.agentName : m.senderName,
1900
+ text: m.text,
1901
+ agentId
1902
+ });
1903
+ }
1904
+ this.history.set(projectId, entries.slice(-contextSize));
1261
1905
  } catch (err) {
1262
1906
  console.error(
1263
1907
  `[sdk] Failed to load history for project ${projectId}:`,
@@ -1277,7 +1921,7 @@ ${task.description}` : `Task: ${task.title}`;
1277
1921
  }
1278
1922
  /**
1279
1923
  * Format conversation history for LLM context.
1280
- * Matches useAbly.ts lines 77-84 format.
1924
+ * Matches useAbly.ts format: `User: text` / `Assistant (Name): text`.
1281
1925
  */
1282
1926
  getFormattedHistory(projectId) {
1283
1927
  const entries = this.history.get(projectId) ?? [];
@@ -1290,9 +1934,10 @@ ${task.description}` : `Task: ${task.title}`;
1290
1934
 
1291
1935
  // src/cli.ts
1292
1936
  import { writeFileSync, mkdirSync } from "fs";
1293
- import { execSync } from "child_process";
1294
- import { homedir } from "os";
1937
+ import { execSync, spawn as spawn2 } from "child_process";
1938
+ import { homedir, hostname } from "os";
1295
1939
  import { join } from "path";
1940
+ import { fileURLToPath } from "url";
1296
1941
 
1297
1942
  // src/templates.ts
1298
1943
  var AGENT_TEMPLATES = [
@@ -1362,6 +2007,12 @@ function parseArgs(argv) {
1362
2007
  return args2;
1363
2008
  }
1364
2009
  var args = parseArgs(process.argv.slice(2));
2010
+ var DEFAULT_SERVER = "https://api.jaibber.com";
2011
+ var DEFAULTS = {
2012
+ anthropic: "claude-sonnet-5",
2013
+ openai: "gpt-4o",
2014
+ google: "gemini-pro-latest"
2015
+ };
1365
2016
  if (args["help"] || args["h"] || process.argv.length <= 2) {
1366
2017
  console.log(`
1367
2018
  Jaibber Agent CLI \u2014 run a headless AI agent
@@ -1369,29 +2020,44 @@ Jaibber Agent CLI \u2014 run a headless AI agent
1369
2020
  USAGE:
1370
2021
  npx @jaibber/sdk [options]
1371
2022
 
2023
+ AUTH (one of):
2024
+ --api-key <jb_...> Agent API key \u2014 the key IS the agent's identity
2025
+ (mint one with --create-key; env JAIBBER_API_KEY)
2026
+ --username <name> Jaibber account username, with:
2027
+ --password <pass> Jaibber account password (env JAIBBER_PASSWORD)
2028
+ The agent is registered under your account
2029
+ (POST /api/me/agents) and posts as itself.
2030
+
1372
2031
  REQUIRED:
1373
- --username <name> Jaibber account username
1374
- --password <pass> Jaibber account password
1375
2032
  --agent-name <name> Agent display name (used for @mention routing)
1376
2033
 
1377
2034
  PROVIDER (at least one required \u2014 first match wins):
1378
2035
  --anthropic-key <key> Anthropic API key (Claude)
1379
- --openai-key <key> OpenAI API key (GPT-4o)
2036
+ --openai-key <key> OpenAI API key (GPT)
1380
2037
  --google-key <key> Google AI API key (Gemini)
1381
2038
  --claude-cli Use local Claude CLI (no API key needed)
1382
2039
 
1383
2040
  MODEL OVERRIDES (optional \u2014 defaults track each provider's recommended model):
1384
- --anthropic-model <id> Anthropic model (default: claude-sonnet-4-5)
1385
- --openai-model <id> OpenAI model (default: gpt-4o)
1386
- --google-model <id> Gemini model (default: gemini-flash-latest)
2041
+ --anthropic-model <id> Anthropic model (default: ${DEFAULTS.anthropic};
2042
+ claude-opus-5 for the most capable tier)
2043
+ --openai-model <id> OpenAI model (default: ${DEFAULTS.openai})
2044
+ --google-model <id> Gemini model (default: ${DEFAULTS.google})
2045
+
2046
+ ACCOUNT & SETUP (require --username/--password):
2047
+ --create-account Create a new Jaibber account, then continue
2048
+ --create-project <name> Create a new project and join it (prints project ID)
2049
+ --create-key Register the agent, assign it to --projects (or all
2050
+ your projects), mint an agent API key, print it, exit
2051
+ --org <id> Organization to register the agent / project under
2052
+ (default: your personal org)
1387
2053
 
1388
2054
  OPTIONAL:
1389
- --register Create a new account (instead of logging into an existing one)
1390
- --create-project <name> Create a new project and join it (prints project ID on start)
1391
- --install-service Install as a systemd user service and start it (Linux only)
2055
+ --install-service Install as a systemd user service and start it
2056
+ (Linux only; requires --api-key \u2014 passwords are never
2057
+ written to service files)
1392
2058
  --template <name> Use a preset agent template (sets agent-name + instructions)
1393
2059
  --list-templates Show available agent templates and exit
1394
- --server <url> Server URL (default: https://api.jaibber.com)
2060
+ --server <url> Server URL (default: ${DEFAULT_SERVER}; env JAIBBER_SERVER)
1395
2061
  --instructions <text> System prompt for the agent
1396
2062
  --machine-name <name> Machine identifier shown in presence
1397
2063
  --projects <id,id,...> Comma-separated project IDs to join (default: all)
@@ -1399,23 +2065,31 @@ OPTIONAL:
1399
2065
  --help Show this help message
1400
2066
 
1401
2067
  EXAMPLES:
1402
- # With Anthropic API key
2068
+ # First run: create an account, register the agent, chat via Anthropic
1403
2069
  npx @jaibber/sdk \\
1404
- --username coding-bot --password s3cret \\
2070
+ --create-account --username coding-bot --password s3cret \\
1405
2071
  --agent-name "CodingAgent" \\
1406
2072
  --anthropic-key sk-ant-api03-...
1407
2073
 
1408
- # With OpenAI
2074
+ # Existing account + local Claude CLI
1409
2075
  npx @jaibber/sdk \\
1410
2076
  --username coding-bot --password s3cret \\
1411
2077
  --agent-name "CodingAgent" \\
1412
- --openai-key sk-...
2078
+ --claude-cli --project-dir /path/to/project
1413
2079
 
1414
- # With local Claude CLI (no API key)
2080
+ # Mint an agent API key (shown once)
1415
2081
  npx @jaibber/sdk \\
1416
2082
  --username coding-bot --password s3cret \\
1417
- --agent-name "CodingAgent" \\
1418
- --claude-cli --project-dir /path/to/project
2083
+ --agent-name "CodingAgent" --projects abc-123 \\
2084
+ --create-key
2085
+
2086
+ # Run with the key (no password on the box)
2087
+ npx @jaibber/sdk --api-key jb_... --agent-name "CodingAgent" --claude-cli
2088
+
2089
+ # Install as a persistent background service (key goes into the unit)
2090
+ npx @jaibber/sdk \\
2091
+ --api-key jb_... --agent-name "CodingAgent" --claude-cli \\
2092
+ --install-service
1419
2093
 
1420
2094
  # Create a new project on first run
1421
2095
  npx @jaibber/sdk \\
@@ -1424,28 +2098,16 @@ EXAMPLES:
1424
2098
  --create-project "my-ubuntu-server" \\
1425
2099
  --claude-cli
1426
2100
 
1427
- # Install as a persistent background service
1428
- npx @jaibber/sdk \\
1429
- --username coding-bot --password s3cret \\
1430
- --agent-name "CodingAgent" \\
1431
- --projects abc-123 --claude-cli \\
1432
- --install-service
1433
-
1434
- # Register new account + Gemini
1435
- npx @jaibber/sdk \\
1436
- --register \\
1437
- --username tester --password p4ss \\
1438
- --agent-name "TestBot" \\
1439
- --google-key AIza...
1440
-
1441
2101
  ENVIRONMENT VARIABLES:
2102
+ JAIBBER_API_KEY Alternative to --api-key
2103
+ JAIBBER_PASSWORD Alternative to --password
2104
+ JAIBBER_SERVER Alternative to --server
1442
2105
  ANTHROPIC_API_KEY Alternative to --anthropic-key
1443
2106
  OPENAI_API_KEY Alternative to --openai-key
1444
2107
  GOOGLE_API_KEY Alternative to --google-key
1445
2108
  ANTHROPIC_MODEL Alternative to --anthropic-model
1446
2109
  OPENAI_MODEL Alternative to --openai-model
1447
2110
  GEMINI_MODEL Alternative to --google-model
1448
- JAIBBER_PASSWORD Alternative to --password
1449
2111
  `);
1450
2112
  process.exit(0);
1451
2113
  }
@@ -1466,8 +2128,10 @@ if (templateId && !template) {
1466
2128
  }
1467
2129
  var username = args["username"];
1468
2130
  var password = args["password"] || process.env.JAIBBER_PASSWORD;
2131
+ var apiKey = args["api-key"] || process.env.JAIBBER_API_KEY;
1469
2132
  var agentName = args["agent-name"] || template?.agentName;
1470
- var serverUrl = args["server"] || "https://api.jaibber.com";
2133
+ var serverUrl = args["server"] || process.env.JAIBBER_SERVER || DEFAULT_SERVER;
2134
+ var orgId = args["org"];
1471
2135
  var anthropicKey = args["anthropic-key"] || process.env.ANTHROPIC_API_KEY;
1472
2136
  var openaiKey = args["openai-key"] || process.env.OPENAI_API_KEY;
1473
2137
  var googleKey = args["google-key"] || process.env.GOOGLE_API_KEY;
@@ -1478,33 +2142,45 @@ var useClaudeCli = args["claude-cli"] === "true";
1478
2142
  var projectDir = args["project-dir"];
1479
2143
  var instructions = args["instructions"] || template?.instructions;
1480
2144
  var machineName = args["machine-name"];
1481
- var shouldRegister = args["register"] === "true";
2145
+ if (args["register"] === "true") {
2146
+ console.warn("[cli] --register is deprecated; use --create-account instead.");
2147
+ }
2148
+ var createAccount = args["create-account"] === "true" || args["register"] === "true";
1482
2149
  var createProjectName = args["create-project"];
2150
+ var createKey = args["create-key"] === "true";
1483
2151
  var installService = args["install-service"] === "true";
1484
- var projectIds = args["projects"] ? args["projects"].split(",").map((s) => s.trim()) : void 0;
1485
- if (!username) {
1486
- console.error("Error: --username is required");
1487
- process.exit(1);
1488
- }
1489
- if (!password) {
2152
+ var projectIds = args["projects"] ? args["projects"].split(",").map((s) => s.trim()).filter(Boolean) : void 0;
2153
+ var hasSession = !!username && !!password;
2154
+ if (!apiKey && !hasSession) {
1490
2155
  console.error(
1491
- "Error: --password is required (or set JAIBBER_PASSWORD env var)"
2156
+ "Error: provide an agent API key (--api-key or JAIBBER_API_KEY), or --username and --password (or JAIBBER_PASSWORD)."
1492
2157
  );
1493
2158
  process.exit(1);
1494
2159
  }
2160
+ if (apiKey && !apiKey.startsWith("jb_")) {
2161
+ console.error('Error: --api-key must be a Jaibber agent API key (starts with "jb_").');
2162
+ process.exit(1);
2163
+ }
1495
2164
  if (!agentName) {
1496
- console.error("Error: --agent-name is required");
2165
+ console.error("Error: --agent-name is required (or pick a --template)");
1497
2166
  process.exit(1);
1498
2167
  }
1499
- if (shouldRegister) {
1500
- console.log(`[cli] Registering new account "${username}"...`);
2168
+ if ((createAccount || createProjectName || createKey) && !hasSession) {
2169
+ console.error(
2170
+ "Error: --create-account, --create-project and --create-key act on your user account and require --username and --password."
2171
+ );
2172
+ process.exit(1);
2173
+ }
2174
+ var providerLabel = anthropicKey ? "claude" : openaiKey ? "openai" : googleKey ? "google" : useClaudeCli ? "claude" : "custom";
2175
+ if (createAccount) {
2176
+ console.log(`[cli] Creating account "${username}"...`);
1501
2177
  const client = new JaibberClient(serverUrl);
1502
2178
  try {
1503
2179
  await client.register(username, password);
1504
2180
  console.log(`[cli] Account created successfully.`);
1505
2181
  } catch (err) {
1506
2182
  console.error(
1507
- `[cli] Registration failed: ${err instanceof Error ? err.message : err}`
2183
+ `[cli] Account creation failed: ${err instanceof Error ? err.message : err}`
1508
2184
  );
1509
2185
  process.exit(1);
1510
2186
  }
@@ -1515,7 +2191,7 @@ if (createProjectName) {
1515
2191
  const client = new JaibberClient(serverUrl);
1516
2192
  try {
1517
2193
  await client.login(username, password);
1518
- const project = await client.createProject(createProjectName);
2194
+ const project = await client.createProject(createProjectName, void 0, orgId);
1519
2195
  console.log(`[cli] Project created: ${project.name}`);
1520
2196
  console.log(`[cli] Project ID: ${project.id}`);
1521
2197
  console.log(`[cli] Share this ID with teammates to join the project.`);
@@ -1527,26 +2203,75 @@ if (createProjectName) {
1527
2203
  process.exit(1);
1528
2204
  }
1529
2205
  }
2206
+ if (createKey) {
2207
+ const client = new JaibberClient(serverUrl);
2208
+ try {
2209
+ await client.login(username, password);
2210
+ const agent2 = await client.ensureAgent({
2211
+ name: agentName,
2212
+ instructions,
2213
+ provider: providerLabel,
2214
+ kind: "sdk",
2215
+ machineName,
2216
+ orgId
2217
+ });
2218
+ console.log(`[cli] Agent "${agent2.name}" registered (id ${agent2.id}).`);
2219
+ const targets = resolvedProjectIds ?? (await client.listProjects()).filter((p) => p.role !== "org-admin").map((p) => p.id);
2220
+ for (const pid of targets) {
2221
+ await client.assignAgent(agent2.id, pid);
2222
+ }
2223
+ console.log(`[cli] Assigned to ${targets.length} project(s).`);
2224
+ const key = await client.createAgentKey(agent2.id, machineName || hostname());
2225
+ console.log(`
2226
+ [cli] Agent API key (shown once \u2014 store it securely):
2227
+
2228
+ ${key.key}
2229
+ `);
2230
+ console.log(`[cli] Run the agent with:`);
2231
+ console.log(` jaibber-agent --api-key ${key.key} --agent-name "${agentName}" <provider flags>`);
2232
+ console.log(`[cli] Or install it as a service:`);
2233
+ console.log(` jaibber-agent --api-key ${key.key} --agent-name "${agentName}" <provider flags> --install-service`);
2234
+ } catch (err) {
2235
+ console.error(`[cli] Failed to create key: ${err instanceof Error ? err.message : err}`);
2236
+ process.exit(1);
2237
+ }
2238
+ process.exit(0);
2239
+ }
2240
+ function shellQuote(s) {
2241
+ if (/^[A-Za-z0-9_\/.:=@%+,-]+$/.test(s)) return s;
2242
+ return `'${s.replace(/'/g, `'\\''`)}'`;
2243
+ }
1530
2244
  if (installService) {
2245
+ if (!apiKey) {
2246
+ console.error(
2247
+ `Error: --install-service requires an agent API key (--api-key or JAIBBER_API_KEY).
2248
+ Passwords are never written to service files. Mint a key for this agent with:
2249
+
2250
+ jaibber-agent --username <user> --password <pass> --agent-name "${agentName}" --create-key
2251
+
2252
+ then re-run with --api-key jb_... --install-service`
2253
+ );
2254
+ process.exit(1);
2255
+ }
1531
2256
  const binaryPath = process.execPath;
1532
- const scriptPath = new URL(import.meta.url).pathname;
2257
+ const scriptPath = fileURLToPath(import.meta.url);
2258
+ const env = { JAIBBER_API_KEY: apiKey };
2259
+ if (anthropicKey) env.ANTHROPIC_API_KEY = anthropicKey;
2260
+ if (openaiKey) env.OPENAI_API_KEY = openaiKey;
2261
+ if (googleKey) env.GOOGLE_API_KEY = googleKey;
1533
2262
  const flags = [];
1534
- flags.push(`--username`, username);
1535
- flags.push(`--password`, password);
1536
2263
  flags.push(`--agent-name`, agentName);
1537
2264
  if (resolvedProjectIds?.length) flags.push(`--projects`, resolvedProjectIds.join(","));
1538
- if (serverUrl !== "https://api.jaibber.com") flags.push(`--server`, serverUrl);
2265
+ if (serverUrl !== DEFAULT_SERVER) flags.push(`--server`, serverUrl);
1539
2266
  if (instructions) flags.push(`--instructions`, instructions);
1540
2267
  if (machineName) flags.push(`--machine-name`, machineName);
1541
2268
  if (projectDir) flags.push(`--project-dir`, projectDir);
1542
2269
  if (useClaudeCli) flags.push(`--claude-cli`);
1543
- if (anthropicKey) flags.push(`--anthropic-key`, anthropicKey);
1544
- if (openaiKey) flags.push(`--openai-key`, openaiKey);
1545
- if (googleKey) flags.push(`--google-key`, googleKey);
1546
2270
  if (anthropicModel) flags.push(`--anthropic-model`, anthropicModel);
1547
2271
  if (openaiModel) flags.push(`--openai-model`, openaiModel);
1548
2272
  if (googleModel) flags.push(`--google-model`, googleModel);
1549
- const execStart = `${binaryPath} ${scriptPath} ${flags.map((f) => f.includes(" ") ? `"${f}"` : f).join(" ")}`;
2273
+ const execStart = [binaryPath, scriptPath, ...flags].map(shellQuote).join(" ");
2274
+ const envLines = Object.entries(env).map(([k, v]) => `Environment="${k}=${v.replace(/(["\\])/g, "\\$1")}"`).join("\n");
1550
2275
  const serviceContent = `[Unit]
1551
2276
  Description=Jaibber Agent (${agentName})
1552
2277
  After=network-online.target
@@ -1558,6 +2283,7 @@ ExecStart=${execStart}
1558
2283
  Restart=on-failure
1559
2284
  RestartSec=10
1560
2285
  Environment=HOME=${homedir()}
2286
+ ${envLines}
1561
2287
 
1562
2288
  [Install]
1563
2289
  WantedBy=default.target
@@ -1567,7 +2293,7 @@ WantedBy=default.target
1567
2293
  const serviceName = `${serviceSlug}.service`;
1568
2294
  const servicePath = join(serviceDir, serviceName);
1569
2295
  mkdirSync(serviceDir, { recursive: true });
1570
- writeFileSync(servicePath, serviceContent);
2296
+ writeFileSync(servicePath, serviceContent, { mode: 384 });
1571
2297
  try {
1572
2298
  execSync(`systemctl --user daemon-reload`, { stdio: "ignore" });
1573
2299
  execSync(`systemctl --user enable --now ${serviceName}`, { stdio: "ignore" });
@@ -1577,7 +2303,8 @@ WantedBy=default.target
1577
2303
  console.log(`[cli] journalctl --user -u ${serviceSlug} -f`);
1578
2304
  } catch {
1579
2305
  const logFile = `${homedir()}/${serviceSlug}.log`;
1580
- const cronLine = `@reboot ${execStart} >> ${logFile} 2>&1`;
2306
+ const envPrefix = Object.entries(env).map(([k, v]) => `${k}=${shellQuote(v)}`).join(" ");
2307
+ const cronLine = `@reboot ${envPrefix} ${execStart} >> ${shellQuote(logFile)} 2>&1`;
1581
2308
  const cronMarker = `jaibber:${serviceSlug}`;
1582
2309
  try {
1583
2310
  let existing = "";
@@ -1588,15 +2315,15 @@ WantedBy=default.target
1588
2315
  const filtered = existing.split("\n").filter((l) => !l.includes(cronMarker) && !l.includes(serviceSlug)).join("\n").trimEnd();
1589
2316
  const newCrontab = (filtered ? filtered + "\n" : "") + `# ${cronMarker}
1590
2317
  ` + cronLine + "\n";
1591
- execSync(`echo ${JSON.stringify(newCrontab)} | crontab -`);
2318
+ execSync("crontab -", { input: newCrontab });
1592
2319
  console.log(`[cli] Service installed via crontab (starts on reboot).`);
1593
2320
  console.log(`[cli] View log: tail -f ~/${serviceSlug}.log`);
1594
2321
  console.log(`[cli] Remove: crontab -e (delete the ${serviceSlug} lines)`);
1595
2322
  console.log(`[cli] Tip: run "sudo loginctl enable-linger ${process.env.USER || "ubuntu"}" to switch to systemd for better reliability.`);
1596
- const { spawn: spawnBg } = await import("child_process");
1597
- spawnBg(binaryPath, [scriptPath, ...flags], {
2323
+ spawn2(binaryPath, [scriptPath, ...flags], {
1598
2324
  detached: true,
1599
- stdio: ["ignore", "ignore", "ignore"]
2325
+ stdio: ["ignore", "ignore", "ignore"],
2326
+ env: { ...process.env, ...env }
1600
2327
  }).unref();
1601
2328
  console.log(`[cli] Agent started in background.`);
1602
2329
  } catch (cronErr) {
@@ -1608,19 +2335,23 @@ WantedBy=default.target
1608
2335
  }
1609
2336
  process.exit(0);
1610
2337
  }
2338
+ process.on("unhandledRejection", (reason) => {
2339
+ console.error("[cli] Unhandled promise rejection (continuing):", reason);
2340
+ });
2341
+ process.on("uncaughtException", (err) => {
2342
+ console.error("[cli] Uncaught exception (continuing):", err);
2343
+ });
2344
+ var credentials = apiKey ? { apiKey } : { username, password };
1611
2345
  var agent = new JaibberAgent({
1612
2346
  serverUrl,
1613
- credentials: { username, password },
2347
+ credentials,
1614
2348
  agentName,
1615
2349
  agentInstructions: instructions,
1616
2350
  machineName,
1617
- projectIds: resolvedProjectIds
2351
+ projectIds: resolvedProjectIds,
2352
+ provider: providerLabel,
2353
+ orgId
1618
2354
  });
1619
- var DEFAULTS = {
1620
- anthropic: "claude-sonnet-4-6",
1621
- openai: "gpt-4o",
1622
- google: "gemini-pro-latest"
1623
- };
1624
2355
  if (anthropicKey) {
1625
2356
  const model = anthropicModel || DEFAULTS.anthropic;
1626
2357
  agent.useProvider("anthropic", { apiKey: anthropicKey, model });
@@ -1649,14 +2380,18 @@ async function shutdown() {
1649
2380
  if (shuttingDown) return;
1650
2381
  shuttingDown = true;
1651
2382
  console.log("\n[cli] Shutting down...");
1652
- await agent.disconnect();
2383
+ try {
2384
+ await agent.disconnect();
2385
+ } catch (err) {
2386
+ console.error(`[cli] Error during shutdown: ${err instanceof Error ? err.message : err}`);
2387
+ }
1653
2388
  process.exit(0);
1654
2389
  }
1655
2390
  process.on("SIGINT", shutdown);
1656
2391
  process.on("SIGTERM", shutdown);
1657
2392
  try {
1658
2393
  await agent.connect();
1659
- console.log(`[cli] Agent "${agentName}" is running. Press Ctrl+C to stop.`);
2394
+ console.log(`[cli] Agent "${agentName}" (id ${agent.id}) is running. Press Ctrl+C to stop.`);
1660
2395
  } catch (err) {
1661
2396
  console.error(
1662
2397
  `[cli] Failed to start: ${err instanceof Error ? err.message : err}`