@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/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,284 @@ 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
+ }
65
127
  // ── Projects ────────────────────────────────────────────────────────
66
- /** GET /api/projects — list all projects user is member of. */
128
+ /**
129
+ * GET /api/projects — with a session: projects the user is a member of
130
+ * (plus org-admin-visible ones with role "org-admin"); with an agent key:
131
+ * the agent's assigned projects.
132
+ */
67
133
  async listProjects() {
68
- const res = await fetch(`${this.serverUrl}/api/projects`, {
69
- headers: this.authHeaders()
134
+ const res = await this.request("GET", "/api/projects", void 0, "Failed to list projects");
135
+ const json = await res.json();
136
+ const rows = json.projects ?? json.data ?? [];
137
+ return rows.map((p) => mapProject(p, this.apiKey ? "agent" : "member"));
138
+ }
139
+ /** POST /api/projects — create a new project (session only), returns it. */
140
+ async createProject(name, description, orgId2) {
141
+ const res = await this.request(
142
+ "POST",
143
+ "/api/projects",
144
+ { name, description, ...orgId2 ? { orgId: orgId2 } : {} },
145
+ "Failed to create project"
146
+ );
147
+ const json = await res.json();
148
+ const p = json.project ?? json.data;
149
+ if (!p) throw new Error("Failed to create project: malformed response");
150
+ return mapProject(p, "admin");
151
+ }
152
+ // ── Agents (/api/me/agents) ─────────────────────────────────────────
153
+ /**
154
+ * POST /api/me/agents — idempotent upsert of an agent hosted by the
155
+ * logged-in user, keyed by (org, lower(name)). Session only.
156
+ */
157
+ async ensureAgent(input) {
158
+ const body = { name: input.name, kind: input.kind };
159
+ if (input.instructions !== void 0) body.instructions = input.instructions;
160
+ if (input.provider) body.provider = input.provider;
161
+ if (input.machineName) body.machineName = input.machineName;
162
+ if (input.projectId) body.projectId = input.projectId;
163
+ if (input.orgId) body.orgId = input.orgId;
164
+ const res = await fetch(`${this.serverUrl}/api/me/agents`, {
165
+ method: "POST",
166
+ headers: this.authHeaders(),
167
+ body: JSON.stringify(body)
70
168
  });
71
169
  if (!res.ok) {
72
- const text = await res.text();
73
- throw new Error(`Failed to list projects (${res.status}): ${text}`);
170
+ const text = await readError(res);
171
+ if (res.status === 404) {
172
+ throw new Error(
173
+ "This Jaibber server does not support agent registration (POST /api/me/agents \u2192 404). Upgrade the server, or use @jaibber/sdk 0.3.x."
174
+ );
175
+ }
176
+ throw new Error(`Failed to register agent (${res.status}): ${text}`);
74
177
  }
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`, {
178
+ const json = await res.json();
179
+ return json.data;
180
+ }
181
+ /** GET /api/me/agents — agents hosted by the logged-in user (with assignments). */
182
+ async listMyAgents() {
183
+ const res = await this.request("GET", "/api/me/agents", void 0, "Failed to list agents");
184
+ const json = await res.json();
185
+ return json.data;
186
+ }
187
+ /** POST /api/me/agents/:id/assignments — assign an agent to a project (idempotent). */
188
+ async assignAgent(agentId, projectId) {
189
+ const res = await fetch(`${this.serverUrl}/api/me/agents/${agentId}/assignments`, {
87
190
  method: "POST",
88
191
  headers: this.authHeaders(),
89
- body: JSON.stringify({ name, description })
192
+ body: JSON.stringify({ projectId })
90
193
  });
91
- if (!res.ok) {
92
- const text = await res.text();
93
- throw new Error(`Failed to create project (${res.status}): ${text}`);
194
+ if (!res.ok && res.status !== 409) {
195
+ const text = await readError(res);
196
+ throw new Error(`Failed to assign agent to project ${projectId} (${res.status}): ${text}`);
94
197
  }
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
- };
198
+ }
199
+ /** DELETE /api/me/agents/:id/assignments?projectId= — remove an assignment. */
200
+ async unassignAgent(agentId, projectId) {
201
+ const res = await this.request(
202
+ "DELETE",
203
+ `/api/me/agents/${agentId}/assignments?projectId=${encodeURIComponent(projectId)}`,
204
+ void 0,
205
+ "Failed to unassign agent"
206
+ );
207
+ const json = await res.json().catch(() => ({}));
208
+ return json.data?.removed ?? true;
209
+ }
210
+ /** POST /api/me/agents/:id/keys — mint an agent-bound API key. The raw key is returned once. */
211
+ async createAgentKey(agentId, name) {
212
+ const res = await this.request(
213
+ "POST",
214
+ `/api/me/agents/${agentId}/keys`,
215
+ name ? { name } : {},
216
+ "Failed to create agent API key"
217
+ );
218
+ const json = await res.json();
219
+ return json.data;
220
+ }
221
+ /** POST /api/agents/:id/heartbeat — refresh lastSeenAt (host session or the agent's own key). */
222
+ async heartbeat(agentId) {
223
+ const res = await this.request(
224
+ "POST",
225
+ `/api/agents/${agentId}/heartbeat`,
226
+ void 0,
227
+ "Heartbeat"
228
+ );
229
+ const json = await res.json();
230
+ return json.data;
103
231
  }
104
232
  // ── Ably token ──────────────────────────────────────────────────────
105
233
  /** POST /api/ably/token — get scoped Ably TokenRequest. */
106
234
  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
- }
235
+ const res = await this.request("POST", "/api/ably/token", void 0, "Failed to get Ably token");
115
236
  return res.json();
116
237
  }
117
238
  // ── Messages ────────────────────────────────────────────────────────
118
239
  /**
119
- * POST /api/projects/{id}/messages — persist a message (idempotent).
120
- * Passing a client-generated `id` makes the server skip Ably re-publish.
240
+ * POST /api/projects/{id}/messages — persist a message. This is the only
241
+ * write path for final messages: the server publishes the echo to Ably
242
+ * itself. Idempotent on `id` (201 on create, 200 if it already existed).
243
+ *
244
+ * Identity is derived server-side: in session mode pass `agentId` to post
245
+ * as that hosted agent; with an agent key it is implied.
246
+ *
247
+ * Retries once on network errors / 5xx (safe: ids are idempotent).
121
248
  */
122
249
  async persistMessage(projectId, msg) {
123
- const res = await fetch(
124
- `${this.serverUrl}/api/projects/${projectId}/messages`,
125
- {
250
+ const body = { text: msg.text };
251
+ if (msg.id) body.id = msg.id;
252
+ if (msg.agentId) body.agentId = msg.agentId;
253
+ if (msg.type) body.type = msg.type;
254
+ if (msg.parentMessageId) body.parentMessageId = msg.parentMessageId;
255
+ if (msg.mentions?.length) body.mentions = msg.mentions;
256
+ const attempt = async () => {
257
+ const res = await fetch(`${this.serverUrl}/api/projects/${projectId}/messages`, {
126
258
  method: "POST",
127
259
  headers: this.authHeaders(),
128
- body: JSON.stringify(msg)
260
+ body: JSON.stringify(body)
261
+ });
262
+ if (!res.ok) {
263
+ const text = await readError(res);
264
+ const err = new Error(`Failed to persist message (${res.status}): ${text}`);
265
+ err.status = res.status;
266
+ throw err;
129
267
  }
130
- );
131
- if (!res.ok) {
132
- const text = await res.text();
133
- console.error(
134
- `[sdk] Failed to persist message (${res.status}): ${text}`
135
- );
268
+ const json = await res.json();
269
+ return json.data;
270
+ };
271
+ try {
272
+ return await attempt();
273
+ } catch (err) {
274
+ const status = err.status;
275
+ const retryable = status === void 0 || status >= 500 || status === 429;
276
+ if (!retryable) throw err;
277
+ await new Promise((r) => setTimeout(r, 1e3));
278
+ return attempt();
136
279
  }
137
280
  }
138
- /** GET /api/projects/{id}/messages — fetch recent messages. */
281
+ /** GET /api/projects/{id}/messages — fetch recent messages (oldest first). */
139
282
  async fetchMessages(projectId, limit = 20) {
140
- const res = await fetch(
141
- `${this.serverUrl}/api/projects/${projectId}/messages?limit=${limit}`,
142
- { headers: this.authHeaders() }
283
+ const res = await this.request(
284
+ "GET",
285
+ `/api/projects/${projectId}/messages?limit=${limit}`,
286
+ void 0,
287
+ "Failed to fetch messages"
143
288
  );
144
- if (!res.ok) {
145
- const text = await res.text();
146
- throw new Error(`Failed to fetch messages (${res.status}): ${text}`);
147
- }
148
289
  const data = await res.json();
149
290
  return data.data;
150
291
  }
151
292
  // ── Tasks ───────────────────────────────────────────────────────────
152
293
  /** POST /api/projects/{id}/tasks — create a task. */
153
294
  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
- }
295
+ const res = await this.request(
296
+ "POST",
297
+ `/api/projects/${projectId}/tasks`,
298
+ data,
299
+ "Failed to create task"
161
300
  );
162
- if (!res.ok) {
163
- const text = await res.text();
164
- throw new Error(`Failed to create task (${res.status}): ${text}`);
165
- }
166
301
  const result = await res.json();
167
302
  return result.data;
168
303
  }
169
- /** PATCH /api/tasks/{taskId} — update task fields. */
304
+ /** PATCH /api/tasks/{taskId} — update task fields. Returns the updated task. */
170
305
  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
- }
306
+ const res = await this.request(
307
+ "PATCH",
308
+ `/api/tasks/${taskId}`,
309
+ updates,
310
+ "Failed to update task"
311
+ );
312
+ const result = await res.json();
313
+ return result.data;
180
314
  }
181
315
  };
182
316
 
183
317
  // src/ably-manager.ts
184
318
  import Ably from "ably";
319
+ var CONNECT_TIMEOUT_MS = 3e4;
185
320
  var AblyManager = class {
186
- constructor(client, userId, username2) {
321
+ constructor(client, opts) {
187
322
  this.client = client;
188
- this.userId = userId;
189
- this.username = username2;
323
+ this.opts = opts;
190
324
  }
191
325
  ably = null;
192
326
  channels = /* @__PURE__ */ new Map();
193
327
  presenceChannel = null;
194
328
  /** Create Ably Realtime client with token auth callback. */
195
- async connect() {
329
+ async connect(timeoutMs = CONNECT_TIMEOUT_MS) {
196
330
  return new Promise((resolve, reject) => {
331
+ let lastAuthError = null;
332
+ let settled = false;
333
+ const finish = (fn) => {
334
+ if (settled) return;
335
+ settled = true;
336
+ clearTimeout(timer);
337
+ fn();
338
+ };
339
+ const timer = setTimeout(() => {
340
+ finish(() => {
341
+ this.ably?.close();
342
+ this.ably = null;
343
+ reject(
344
+ new Error(
345
+ `Ably connection timed out after ${Math.round(timeoutMs / 1e3)}s` + (lastAuthError ? ` (last auth error: ${lastAuthError.message})` : "")
346
+ )
347
+ );
348
+ });
349
+ }, timeoutMs);
197
350
  this.ably = new Ably.Realtime({
198
351
  authCallback: async (_tokenParams, callback) => {
199
352
  try {
200
353
  const tokenRequest = await this.client.getAblyToken();
201
354
  callback(null, tokenRequest);
202
355
  } catch (err) {
203
- callback(err, null);
356
+ lastAuthError = err instanceof Error ? err : new Error(String(err));
357
+ callback(lastAuthError.message, null);
204
358
  }
205
359
  },
206
- clientId: this.userId,
360
+ ...this.opts.clientId ? { clientId: this.opts.clientId } : {},
207
361
  disconnectedRetryTimeout: 5e3,
208
362
  // 5s initial retry on disconnect
209
363
  suspendedRetryTimeout: 3e4
210
364
  // 30s retry when suspended
211
365
  });
212
366
  this.ably.connection.once("connected", () => {
213
- resolve();
367
+ finish(resolve);
214
368
  });
215
369
  this.ably.connection.once("failed", (stateChange) => {
216
- reject(
217
- new Error(
218
- `Ably connection failed: ${stateChange?.reason?.message ?? "unknown"}`
370
+ finish(
371
+ () => reject(
372
+ new Error(
373
+ `Ably connection failed: ${stateChange?.reason?.message ?? lastAuthError?.message ?? "unknown"}`
374
+ )
219
375
  )
220
376
  );
221
377
  });
@@ -233,20 +389,22 @@ var AblyManager = class {
233
389
  });
234
390
  }
235
391
  /** Enter global presence channel (jaibber:presence). */
236
- async enterGlobalPresence(projectIds2) {
392
+ async enterGlobalPresence(data) {
237
393
  if (!this.ably) throw new Error("Ably not connected");
238
394
  this.presenceChannel = this.ably.channels.get("jaibber:presence");
239
395
  await this.presenceChannel.presence.enter({
240
- userId: this.userId,
241
- username: this.username,
242
- projectIds: projectIds2
396
+ ...data.userId ? { userId: data.userId } : {},
397
+ ...data.agentId ? { agentId: data.agentId } : {},
398
+ username: data.username,
399
+ projectIds: data.projectIds
243
400
  });
244
401
  }
245
402
  /**
246
- * Subscribe to a project channel and enter per-project presence.
403
+ * Subscribe to a project channel (`message`, `task` and server-published
404
+ * `agent-control` events) and enter per-project presence.
247
405
  * Returns an unsubscribe function.
248
406
  */
249
- async subscribeToProject(project, presenceData, onMessage, onTask) {
407
+ async subscribeToProject(project, presenceData, onMessage, onTask, onControl) {
250
408
  if (!this.ably) throw new Error("Ably not connected");
251
409
  const channel = this.ably.channels.get(project.ablyChannelName);
252
410
  this.channels.set(project.ablyChannelName, channel);
@@ -255,20 +413,31 @@ var AblyManager = class {
255
413
  if (!msg.data) return;
256
414
  const payload = msg.data;
257
415
  payload._connectionId = msg.connectionId ?? void 0;
416
+ payload._clientId = msg.clientId ?? void 0;
258
417
  onMessage(payload);
259
418
  };
260
419
  const taskHandler = (msg) => {
261
420
  if (!msg.data) return;
262
421
  onTask(msg.data);
263
422
  };
423
+ const controlHandler = (msg) => {
424
+ if (!msg.data || typeof msg.data !== "object") return;
425
+ onControl?.(msg.data);
426
+ };
264
427
  channel.subscribe("message", messageHandler);
265
428
  channel.subscribe("task", taskHandler);
429
+ channel.subscribe("agent-control", controlHandler);
266
430
  return () => {
267
431
  channel.unsubscribe("message", messageHandler);
268
432
  channel.unsubscribe("task", taskHandler);
433
+ channel.unsubscribe("agent-control", controlHandler);
269
434
  };
270
435
  }
271
- /** Publish a message on a project channel. */
436
+ /**
437
+ * Publish a client-side event on a project channel. Only `typing` and
438
+ * `chunk` are client-published; final messages go through the REST API
439
+ * and are echoed by the server.
440
+ */
272
441
  async publish(channelName, eventName, data) {
273
442
  const channel = this.channels.get(channelName);
274
443
  if (!channel) {
@@ -280,6 +449,10 @@ var AblyManager = class {
280
449
  get connectionId() {
281
450
  return this.ably?.connection.id;
282
451
  }
452
+ /** The clientId this connection authenticated as (from the token in API-key mode). */
453
+ get clientId() {
454
+ return this.ably?.auth.clientId ?? void 0;
455
+ }
283
456
  /** Leave presence on all channels and close the connection. */
284
457
  async disconnect() {
285
458
  for (const channel of this.channels.values()) {
@@ -310,44 +483,69 @@ var MessageContext = class {
310
483
  conversationHistory;
311
484
  /** The project ID this message was received on. */
312
485
  projectId;
313
- responseId;
486
+ /** The agent's server-side id (sent as `agentId` on every save). */
487
+ agentId;
488
+ /** The agent's display name. */
489
+ agentName;
490
+ /** Id of the message being responded to (if any). */
491
+ incomingMessageId;
492
+ /**
493
+ * The id the final reply will be stored under. Also the `responseId` sent
494
+ * with `typing` so clients can pre-create the bubble.
495
+ */
496
+ messageId;
314
497
  ablyManager;
315
498
  channelName;
316
- userId;
317
- agentName;
499
+ from;
318
500
  client;
319
501
  responseDepth;
320
502
  respondingChain;
321
503
  chunkBatchMs;
504
+ tracker;
322
505
  constructor(opts) {
323
506
  this.projectId = opts.projectId;
324
507
  this.channelName = opts.channelName;
325
508
  this.conversationHistory = opts.conversationHistory;
326
509
  this.ablyManager = opts.ablyManager;
327
- this.userId = opts.userId;
510
+ this.from = opts.from;
511
+ this.agentId = opts.agentId;
328
512
  this.agentName = opts.agentName;
329
513
  this.client = opts.client;
514
+ this.incomingMessageId = opts.incomingMessageId;
330
515
  this.responseDepth = opts.incomingDepth + 1;
331
516
  this.respondingChain = [
332
517
  ...opts.incomingChain,
333
518
  opts.agentName.toLowerCase()
334
519
  ];
335
520
  this.chunkBatchMs = opts.chunkBatchMs;
336
- this.responseId = uuidv4();
521
+ this.tracker = opts.tracker;
522
+ this.messageId = uuidv4();
523
+ }
524
+ /** Agent-to-agent hop count this reply will carry (informational). */
525
+ get depth() {
526
+ return this.responseDepth;
337
527
  }
338
- /** One-shot reply: publishes typing → response in sequence. */
339
- async reply(text) {
528
+ /** Agents that have already responded in this chain, including this one. */
529
+ get chain() {
530
+ return [...this.respondingChain];
531
+ }
532
+ /** One-shot reply: publishes `typing`, then POSTs the final message. */
533
+ async reply(text, opts) {
340
534
  await this.publishTyping();
341
- await this.publishResponse(text);
342
- this.persistAsync(text, "response");
535
+ return this.persist(this.messageId, text, "response", this.parentFor(opts));
536
+ }
537
+ /** Replies thread under the answered message unless overridden. */
538
+ parentFor(opts) {
539
+ return opts?.parentMessageId ?? this.incomingMessageId;
343
540
  }
344
541
  /**
345
542
  * Streaming reply: consumes an async generator, batches chunks to Ably
346
- * every chunkBatchMs (default 200ms), then publishes the final response.
543
+ * every chunkBatchMs (default 200ms), then POSTs the final message.
544
+ * Resolves with the full response text.
347
545
  *
348
- * Mirrors useAbly.ts lines 86-102 chunk batching pattern.
546
+ * Mirrors useAbly.ts chunk batching pattern.
349
547
  */
350
- async stream(generator) {
548
+ async stream(generator, opts) {
351
549
  await this.publishTyping();
352
550
  let fullText = "";
353
551
  let chunkBuffer = "";
@@ -371,158 +569,130 @@ var MessageContext = class {
371
569
  }
372
570
  if (flushTimer) clearTimeout(flushTimer);
373
571
  await flushChunks();
374
- await this.publishResponse(fullText);
375
- this.persistAsync(fullText, "response");
376
572
  } catch (err) {
377
573
  if (flushTimer) clearTimeout(flushTimer);
378
574
  const errText = `Agent error: ${err instanceof Error ? err.message : String(err)}`;
379
- await this.publishError(errText);
380
- this.persistAsync(errText, "error");
575
+ await this.persist(this.messageId, errText, "error", this.parentFor(opts)).catch((e) => {
576
+ console.error("[sdk] Failed to persist error message:", e);
577
+ });
578
+ throw err;
381
579
  }
580
+ await this.persist(this.messageId, fullText, "response", this.parentFor(opts));
581
+ return fullText;
382
582
  }
383
583
  // ── Internal publish helpers ────────────────────────────────────────
384
584
  async publishTyping() {
385
585
  await this.ablyManager.publish(this.channelName, "message", {
386
- from: this.userId,
586
+ from: this.from,
387
587
  fromUsername: this.agentName,
388
588
  projectId: this.projectId,
389
589
  text: "",
390
590
  messageId: uuidv4(),
391
- responseId: this.responseId,
591
+ responseId: this.messageId,
392
592
  type: "typing",
393
- agentName: this.agentName
593
+ agentName: this.agentName,
594
+ agentId: this.agentId
394
595
  });
395
596
  }
396
597
  async publishChunk(text) {
397
598
  await this.ablyManager.publish(this.channelName, "message", {
398
- from: this.userId,
599
+ from: this.from,
399
600
  fromUsername: this.agentName,
400
601
  projectId: this.projectId,
401
602
  text,
402
- messageId: this.responseId,
603
+ messageId: this.messageId,
403
604
  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
605
  agentName: this.agentName,
416
- isAgentMessage: true,
417
- responseDepth: this.responseDepth,
418
- respondingChain: this.respondingChain
606
+ agentId: this.agentId
419
607
  });
420
608
  }
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
- });
431
- }
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
- });
609
+ /** POST the final message. Throws if the server rejects it. */
610
+ async persist(id, text, type, parentMessageId) {
611
+ this.tracker?.begin(id, this.projectId, text, type, parentMessageId);
612
+ try {
613
+ const saved = await this.client.persistMessage(this.projectId, {
614
+ id,
615
+ agentId: this.agentId,
616
+ type,
617
+ text,
618
+ parentMessageId
619
+ });
620
+ this.tracker?.posted(id);
621
+ return saved;
622
+ } catch (err) {
623
+ this.tracker?.failed(id);
624
+ throw err;
625
+ }
443
626
  }
444
627
  };
445
628
  var TaskContext = class {
446
629
  task;
447
630
  projectId;
448
631
  conversationHistory;
449
- ablyManager;
450
- channelName;
451
- userId;
632
+ agentId;
452
633
  agentName;
453
634
  client;
635
+ tracker;
454
636
  constructor(opts) {
455
637
  this.task = opts.task;
456
638
  this.projectId = opts.projectId;
457
- this.channelName = opts.channelName;
458
639
  this.conversationHistory = opts.conversationHistory;
459
- this.ablyManager = opts.ablyManager;
460
- this.userId = opts.userId;
640
+ this.agentId = opts.agentId;
461
641
  this.agentName = opts.agentName;
462
642
  this.client = opts.client;
643
+ this.tracker = opts.tracker;
463
644
  }
464
- /** Mark task as completed, optionally publishing a response message. */
645
+ /** Mark task as completed, optionally posting a response message. */
465
646
  async complete(resultText) {
466
647
  await this.client.updateTask(this.task.id, { status: "completed" });
467
648
  if (resultText) {
468
649
  await this.sendMessage(resultText);
469
650
  }
470
651
  }
471
- /** Mark task as failed, optionally publishing an error message. */
652
+ /** Mark task as failed, optionally posting an error message. */
472
653
  async fail(errorText) {
473
654
  await this.client.updateTask(this.task.id, { status: "failed" });
474
655
  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));
656
+ await this.sendMessage(errorText, { type: "error" });
492
657
  }
493
658
  }
494
659
  /**
495
660
  * Create a follow-up task assigned to another agent.
496
- * Automatically sets parentTaskId to the current task's ID.
661
+ * Automatically sets parentTaskId to the current task's ID and attributes
662
+ * creation to this agent.
497
663
  */
498
664
  async createFollowUpTask(data) {
499
665
  return this.client.createTask(this.projectId, {
500
666
  ...data,
501
667
  parentTaskId: this.task.id,
502
668
  createdByType: "agent",
503
- createdByName: this.agentName
669
+ createdByName: this.agentName,
670
+ createdByAgentId: this.agentId
504
671
  });
505
672
  }
506
- /** Send a chat message (for progress updates). */
507
- async sendMessage(text) {
673
+ /**
674
+ * Post a chat message (for progress updates). Returns the stored message.
675
+ * `type` defaults to "response"; use "message" for notices that must never
676
+ * trigger other agents (agent-to-agent chaining only flows through responses).
677
+ */
678
+ async sendMessage(text, opts) {
508
679
  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));
680
+ const type = opts?.type ?? "response";
681
+ this.tracker?.begin(msgId, this.projectId, text, type, opts?.parentMessageId);
682
+ try {
683
+ const saved = await this.client.persistMessage(this.projectId, {
684
+ id: msgId,
685
+ agentId: this.agentId,
686
+ type,
687
+ text,
688
+ parentMessageId: opts?.parentMessageId
689
+ });
690
+ this.tracker?.posted(msgId);
691
+ return saved;
692
+ } catch (err) {
693
+ this.tracker?.failed(msgId);
694
+ throw err;
695
+ }
526
696
  }
527
697
  };
528
698
 
@@ -927,6 +1097,11 @@ ${systemPrompt}
927
1097
  var DEFAULT_MAX_DEPTH = 3;
928
1098
  var DEFAULT_CHUNK_BATCH_MS = 200;
929
1099
  var DEFAULT_CONTEXT_WINDOW = 20;
1100
+ var DEFAULT_HEARTBEAT_MS = 12e4;
1101
+ var OWN_MESSAGE_MEMORY = 1e3;
1102
+ var MESSAGE_INDEX_SIZE = 500;
1103
+ var META_TTL_MS = 5 * 60 * 1e3;
1104
+ 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.";
930
1105
  var JaibberAgent = class extends EventEmitter {
931
1106
  config;
932
1107
  client;
@@ -934,75 +1109,189 @@ var JaibberAgent = class extends EventEmitter {
934
1109
  messageHandler = null;
935
1110
  taskHandler = null;
936
1111
  provider = null;
1112
+ providerKind = null;
937
1113
  connected = false;
938
1114
  projects = [];
939
1115
  unsubscribers = [];
1116
+ heartbeatTimer = null;
1117
+ agentId = null;
1118
+ agentRecord = null;
940
1119
  /** In-memory conversation history per project. */
941
1120
  history = /* @__PURE__ */ new Map();
1121
+ /** Recent messages per project (id → author/parent) for chain reconstruction. */
1122
+ messageIndex = /* @__PURE__ */ new Map();
942
1123
  /** Track in-flight responses to prevent double-handling. */
943
1124
  activeResponses = /* @__PURE__ */ new Set();
944
1125
  /** Session IDs per project for Claude --resume. */
945
1126
  sessionIds = /* @__PURE__ */ new Map();
1127
+ /** Messages we POSTed ourselves, keyed by id — for echo dedupe + own-reply history. */
1128
+ ownMessages = /* @__PURE__ */ new Map();
1129
+ /** `meta` hints waiting for their server echo. */
1130
+ pendingMeta = /* @__PURE__ */ new Map();
1131
+ /**
1132
+ * Safety valve: unthreaded agent responses (no `parentMessageId`) seen per
1133
+ * project since the last human message. Threaded chains are bounded by the
1134
+ * `parentMessageId` walk; this catches agents that post without threading,
1135
+ * which would otherwise look like a fresh depth-1 chain every time.
1136
+ */
1137
+ unthreadedHops = /* @__PURE__ */ new Map();
946
1138
  constructor(config) {
947
1139
  super();
948
1140
  this.config = config;
949
1141
  this.client = new JaibberClient(config.serverUrl);
950
1142
  }
1143
+ // ── Accessors ───────────────────────────────────────────────────────
1144
+ /** The agent's server-side id (available after `connect()`). */
1145
+ get id() {
1146
+ return this.agentId;
1147
+ }
1148
+ /** The agent record returned by the server (session mode only). */
1149
+ get record() {
1150
+ return this.agentRecord;
1151
+ }
1152
+ /** The underlying REST client (authenticated after `connect()`). */
1153
+ get api() {
1154
+ return this.client;
1155
+ }
1156
+ /** Projects this agent has joined. */
1157
+ get joinedProjects() {
1158
+ return [...this.projects];
1159
+ }
1160
+ /** Sender id used on client-published typing/chunk events. */
1161
+ get senderId() {
1162
+ return this.client.userId ?? `agent:${this.agentId ?? "unknown"}`;
1163
+ }
1164
+ get maxDepth() {
1165
+ return this.config.maxResponseDepth ?? DEFAULT_MAX_DEPTH;
1166
+ }
951
1167
  // ── Lifecycle ───────────────────────────────────────────────────────
952
- /** Authenticate, connect Ably, subscribe to project channels. */
1168
+ /** Authenticate, register/resolve the agent, connect Ably, subscribe to project channels. */
953
1169
  async connect() {
954
1170
  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;
1171
+ const creds = this.config.credentials;
1172
+ const apiKeyMode = "apiKey" in creds;
1173
+ if (apiKeyMode) {
1174
+ this.client.setApiKey(creds.apiKey);
1175
+ this.agentId = this.config.agentId ?? null;
1176
+ console.log(`[sdk] Authenticating with agent API key ${creds.apiKey.slice(0, 11)}\u2026`);
1177
+ } else {
1178
+ console.log(`[sdk] Logging in as "${creds.username}"...`);
1179
+ await this.client.login(creds.username, creds.password);
1180
+ const record = await this.client.ensureAgent({
1181
+ name: this.config.agentName,
1182
+ instructions: this.config.agentInstructions,
1183
+ provider: this.resolveProviderKind(),
1184
+ kind: "sdk",
1185
+ machineName: this.config.machineName,
1186
+ orgId: this.config.orgId
1187
+ });
1188
+ this.agentId = record.id;
1189
+ this.agentRecord = record;
1190
+ this.config.agentId = record.id;
1191
+ console.log(`[sdk] Agent "${record.name}" registered (id ${record.id})`);
1192
+ }
960
1193
  const allProjects = await this.client.listProjects();
961
- this.projects = this.config.projectIds ? allProjects.filter((p) => this.config.projectIds.includes(p.id)) : allProjects;
1194
+ if (this.config.projectIds) {
1195
+ const wanted = new Set(this.config.projectIds);
1196
+ this.projects = allProjects.filter((p) => wanted.has(p.id));
1197
+ const missing = this.config.projectIds.filter(
1198
+ (id) => !this.projects.some((p) => p.id === id)
1199
+ );
1200
+ if (missing.length > 0) {
1201
+ console.warn(`[sdk] Project(s) not accessible, skipping: ${missing.join(", ")}`);
1202
+ }
1203
+ } else {
1204
+ this.projects = allProjects.filter((p) => p.role !== "org-admin");
1205
+ }
962
1206
  if (this.projects.length === 0) {
963
1207
  throw new Error(
964
- "No projects found. Ensure the agent account is a member of at least one project."
1208
+ 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
1209
  );
966
1210
  }
967
1211
  console.log(
968
1212
  `[sdk] Found ${this.projects.length} project(s): ${this.projects.map((p) => p.name).join(", ")}`
969
1213
  );
970
- this.ablyManager = new AblyManager(this.client, userId, displayName);
1214
+ if (!apiKeyMode) {
1215
+ for (const project of this.projects) {
1216
+ try {
1217
+ await this.client.assignAgent(this.agentId, project.id);
1218
+ } catch (err) {
1219
+ console.warn(
1220
+ `[sdk] Could not assign agent to "${project.name}": ${err instanceof Error ? err.message : err}`
1221
+ );
1222
+ }
1223
+ }
1224
+ }
1225
+ this.ablyManager = new AblyManager(this.client, {
1226
+ clientId: apiKeyMode ? void 0 : this.client.userId,
1227
+ username: this.config.agentName
1228
+ });
971
1229
  await this.ablyManager.connect();
972
- await this.ablyManager.enterGlobalPresence(
973
- this.projects.map((p) => p.id)
974
- );
975
- for (const project of this.projects) {
1230
+ try {
1231
+ if (!this.agentId) {
1232
+ const cid = this.ablyManager.clientId;
1233
+ if (cid && cid.startsWith("agent:")) {
1234
+ this.agentId = cid.slice("agent:".length);
1235
+ this.config.agentId = this.agentId;
1236
+ } else {
1237
+ throw new Error(
1238
+ `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\`.`
1239
+ );
1240
+ }
1241
+ }
1242
+ this.startHeartbeat();
1243
+ await this.ablyManager.enterGlobalPresence({
1244
+ userId: this.client.userId ?? void 0,
1245
+ agentId: this.agentId,
1246
+ username: this.config.agentName,
1247
+ projectIds: this.projects.map((p) => p.id)
1248
+ });
976
1249
  const presenceData = {
977
- userId,
1250
+ userId: this.client.userId ?? void 0,
978
1251
  username: this.config.agentName,
979
1252
  isAgent: true,
980
1253
  agentName: this.config.agentName,
1254
+ agentId: this.agentId,
981
1255
  agentInstructions: this.config.agentInstructions,
982
1256
  agents: [
983
1257
  {
1258
+ agentId: this.agentId,
984
1259
  agentName: this.config.agentName,
985
1260
  agentInstructions: this.config.agentInstructions
986
1261
  }
987
1262
  ],
988
1263
  machineName: this.config.machineName
989
1264
  };
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);
1265
+ for (const project of this.projects) {
1266
+ await this.loadHistory(project.id);
1267
+ const unsub = await this.ablyManager.subscribeToProject(
1268
+ project,
1269
+ presenceData,
1270
+ (msg) => this.handleIncomingMessage(msg, project),
1271
+ (data) => this.handleTaskEvent(data, project),
1272
+ (data) => this.handleControlEvent(data, project)
1273
+ );
1274
+ this.unsubscribers.push(unsub);
1275
+ }
1276
+ } catch (err) {
1277
+ this.stopHeartbeat();
1278
+ for (const unsub of this.unsubscribers) unsub();
1279
+ this.unsubscribers = [];
1280
+ await this.ablyManager.disconnect().catch(() => {
1281
+ });
1282
+ this.ablyManager = null;
1283
+ throw err;
998
1284
  }
999
1285
  this.connected = true;
1000
- console.log(`[sdk] Agent "${this.config.agentName}" connected and listening`);
1286
+ console.log(
1287
+ `[sdk] Agent "${this.config.agentName}" (${this.agentId}) connected and listening`
1288
+ );
1001
1289
  this.emit("connected", this.projects);
1002
1290
  }
1003
- /** Leave presence, disconnect Ably. */
1291
+ /** Stop heartbeats, leave presence, disconnect Ably. */
1004
1292
  async disconnect() {
1005
1293
  if (!this.connected) return;
1294
+ this.stopHeartbeat();
1006
1295
  for (const unsub of this.unsubscribers) {
1007
1296
  unsub();
1008
1297
  }
@@ -1027,48 +1316,190 @@ var JaibberAgent = class extends EventEmitter {
1027
1316
  switch (name) {
1028
1317
  case "anthropic":
1029
1318
  this.provider = new AnthropicProvider(options);
1319
+ this.providerKind = "claude";
1030
1320
  break;
1031
1321
  case "openai":
1032
1322
  this.provider = new OpenAIProvider(options);
1323
+ this.providerKind = "openai";
1033
1324
  break;
1034
1325
  case "google":
1035
1326
  this.provider = new GoogleProvider(options);
1327
+ this.providerKind = "google";
1036
1328
  break;
1037
1329
  case "claude-cli":
1038
1330
  this.provider = new ClaudeCLIProvider(options);
1331
+ this.providerKind = "claude";
1039
1332
  break;
1040
1333
  }
1041
1334
  }
1335
+ /** Provider label stored on the agent record. */
1336
+ resolveProviderKind() {
1337
+ return this.config.provider ?? this.providerKind ?? "custom";
1338
+ }
1339
+ // ── Heartbeat ───────────────────────────────────────────────────────
1340
+ startHeartbeat() {
1341
+ this.stopHeartbeat();
1342
+ const beat = async () => {
1343
+ if (!this.agentId) return;
1344
+ try {
1345
+ await this.client.heartbeat(this.agentId);
1346
+ } catch (err) {
1347
+ console.warn(`[sdk] Heartbeat failed: ${err instanceof Error ? err.message : err}`);
1348
+ }
1349
+ };
1350
+ void beat();
1351
+ this.heartbeatTimer = setInterval(beat, this.config.heartbeatMs ?? DEFAULT_HEARTBEAT_MS);
1352
+ this.heartbeatTimer.unref?.();
1353
+ }
1354
+ stopHeartbeat() {
1355
+ if (this.heartbeatTimer) {
1356
+ clearInterval(this.heartbeatTimer);
1357
+ this.heartbeatTimer = null;
1358
+ }
1359
+ }
1360
+ // ── Message index / chain reconstruction ────────────────────────────
1361
+ indexMessage(projectId, id, entry) {
1362
+ const idx = this.messageIndex.get(projectId) ?? /* @__PURE__ */ new Map();
1363
+ idx.delete(id);
1364
+ idx.set(id, entry);
1365
+ while (idx.size > MESSAGE_INDEX_SIZE) {
1366
+ const oldest = idx.keys().next().value;
1367
+ if (oldest === void 0) break;
1368
+ idx.delete(oldest);
1369
+ }
1370
+ this.messageIndex.set(projectId, idx);
1371
+ }
1372
+ /**
1373
+ * Loop prevention for agent-to-agent chains. The server echo carries no
1374
+ * chain metadata, so the chain is reconstructed from `parentMessageId`
1375
+ * links: every agent response is posted as a reply to the message it
1376
+ * answered. Returns the number of consecutive agent hops ending at
1377
+ * `payload` (the depth) and the lowercased names of the agents in that run.
1378
+ * Mirrors useAbly.ts agentChainFor().
1379
+ */
1380
+ agentChainFor(projectId, payload) {
1381
+ const idx = this.messageIndex.get(projectId);
1382
+ const chain = [(payload.agentName ?? payload.fromUsername).toLowerCase()];
1383
+ let parentId = payload.parentMessageId;
1384
+ let guard = 0;
1385
+ while (parentId && guard++ < 50) {
1386
+ const parent = idx?.get(parentId);
1387
+ if (!parent?.agentId) break;
1388
+ chain.push(parent.senderName.toLowerCase());
1389
+ parentId = parent.parentMessageId;
1390
+ }
1391
+ return { depth: chain.length, chain };
1392
+ }
1393
+ // ── `meta` hints ────────────────────────────────────────────────────
1394
+ rememberMeta(messageId, meta) {
1395
+ const cutoff = Date.now() - META_TTL_MS;
1396
+ for (const [id, m] of this.pendingMeta) {
1397
+ if (m.receivedAt < cutoff) this.pendingMeta.delete(id);
1398
+ }
1399
+ this.pendingMeta.set(messageId, meta);
1400
+ }
1401
+ takeMeta(messageId, senderId) {
1402
+ const meta = this.pendingMeta.get(messageId);
1403
+ if (!meta) return void 0;
1404
+ this.pendingMeta.delete(messageId);
1405
+ return meta.clientId === senderId ? meta : void 0;
1406
+ }
1407
+ // ── Own-message tracking (echo dedupe + own replies in history) ─────
1408
+ tracker = {
1409
+ begin: (id, projectId, text, type, parentMessageId) => {
1410
+ this.ownMessages.set(id, { projectId, text, type, recorded: false });
1411
+ while (this.ownMessages.size > OWN_MESSAGE_MEMORY) {
1412
+ const oldest = this.ownMessages.keys().next().value;
1413
+ if (oldest === void 0) break;
1414
+ this.ownMessages.delete(oldest);
1415
+ }
1416
+ this.indexMessage(projectId, id, {
1417
+ agentId: this.agentId ?? void 0,
1418
+ senderName: this.config.agentName,
1419
+ parentMessageId
1420
+ });
1421
+ },
1422
+ posted: (id) => this.recordOwnMessage(id),
1423
+ failed: (id) => {
1424
+ this.ownMessages.delete(id);
1425
+ }
1426
+ };
1427
+ /**
1428
+ * Add one of our own messages to history exactly once — whichever arrives
1429
+ * first: the server's Ably echo or the POST response.
1430
+ */
1431
+ recordOwnMessage(id) {
1432
+ const own = this.ownMessages.get(id);
1433
+ if (!own || own.recorded) return;
1434
+ own.recorded = true;
1435
+ if (own.type === "error") return;
1436
+ this.addToHistory(own.projectId, {
1437
+ sender: "agent",
1438
+ senderName: this.config.agentName,
1439
+ text: own.text,
1440
+ agentId: this.agentId ?? void 0
1441
+ });
1442
+ }
1042
1443
  // ── Message handling ────────────────────────────────────────────────
1043
1444
  async handleIncomingMessage(payload, project) {
1044
1445
  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
- }
1446
+ if (payload.type === "meta") {
1447
+ if (!payload._clientId) return;
1448
+ this.rememberMeta(payload.messageId, {
1449
+ clientId: payload._clientId,
1450
+ executionMode: payload.executionMode,
1451
+ attachments: payload.attachments,
1452
+ receivedAt: Date.now()
1453
+ });
1052
1454
  return;
1053
1455
  }
1054
- if (payload.isTaskNotification) return;
1055
1456
  if (payload.type !== "message" && payload.type !== "response") return;
1457
+ if (this.ownMessages.has(payload.messageId)) {
1458
+ this.recordOwnMessage(payload.messageId);
1459
+ return;
1460
+ }
1056
1461
  if (payload.text && payload.text.length > 1e5) {
1057
1462
  console.warn(`[sdk] Ignoring oversized message (${payload.text.length} chars)`);
1058
1463
  return;
1059
1464
  }
1465
+ const isAgent = payload.isAgentMessage === true || !!payload.agentId;
1466
+ const isSelf = !!this.agentId && payload.agentId === this.agentId;
1467
+ this.indexMessage(project.id, payload.messageId, {
1468
+ agentId: payload.agentId,
1469
+ senderName: payload.agentName ?? payload.fromUsername,
1470
+ parentMessageId: payload.parentMessageId
1471
+ });
1472
+ if (!isAgent) this.unthreadedHops.set(project.id, 0);
1060
1473
  this.addToHistory(project.id, {
1061
- sender: payload.isAgentMessage ? "agent" : "user",
1474
+ sender: isAgent ? "agent" : "user",
1062
1475
  senderName: payload.fromUsername,
1063
- text: payload.text
1476
+ text: payload.text,
1477
+ agentId: payload.agentId
1064
1478
  });
1065
- const depth = payload.responseDepth ?? 0;
1066
- const chain = payload.respondingChain ?? [];
1479
+ if (isSelf) return;
1480
+ if (payload.isTaskNotification) return;
1481
+ let depth = 0;
1482
+ let chain = [];
1483
+ let executionMode = payload.executionMode;
1484
+ let attachments = payload.attachments;
1485
+ if (isAgent) {
1486
+ if (payload.type !== "response") return;
1487
+ ({ depth, chain } = this.agentChainFor(project.id, payload));
1488
+ if (!payload.parentMessageId) {
1489
+ const n = (this.unthreadedHops.get(project.id) ?? 0) + 1;
1490
+ this.unthreadedHops.set(project.id, n);
1491
+ if (n > this.maxDepth) return;
1492
+ }
1493
+ } else {
1494
+ const meta = this.takeMeta(payload.messageId, payload.from);
1495
+ executionMode = executionMode ?? meta?.executionMode;
1496
+ attachments = attachments ?? meta?.attachments;
1497
+ }
1067
1498
  if (!this.shouldRespond(payload.text, depth, chain)) return;
1068
1499
  if (this.activeResponses.has(payload.messageId)) return;
1069
1500
  this.activeResponses.add(payload.messageId);
1070
1501
  try {
1071
- await this.respondToMessage(payload, project, depth, chain);
1502
+ await this.respondToMessage(payload, project, depth, chain, executionMode, attachments);
1072
1503
  } catch (err) {
1073
1504
  console.error("[sdk] Error responding to message:", err);
1074
1505
  this.emit("error", err);
@@ -1081,26 +1512,27 @@ var JaibberAgent = class extends EventEmitter {
1081
1512
  * Mirrors useAbly.ts shouldAgentRespond() logic.
1082
1513
  */
1083
1514
  shouldRespond(text, depth, chain) {
1084
- const maxDepth = this.config.maxResponseDepth ?? DEFAULT_MAX_DEPTH;
1085
- if (depth >= maxDepth) return false;
1515
+ if (depth >= this.maxDepth) return false;
1086
1516
  if (chain.includes(this.config.agentName.toLowerCase())) return false;
1087
1517
  if (!mentionsAgent(text, this.config.agentName)) return false;
1088
1518
  return true;
1089
1519
  }
1090
- async respondToMessage(payload, project, incomingDepth, incomingChain) {
1091
- const userId = this.client.userId;
1520
+ async respondToMessage(payload, project, incomingDepth, incomingChain, executionMode, attachments) {
1092
1521
  const conversationHistory = this.getFormattedHistory(project.id);
1093
1522
  const ctx = new MessageContext({
1094
1523
  projectId: project.id,
1095
1524
  channelName: project.ablyChannelName,
1096
1525
  conversationHistory,
1097
1526
  ablyManager: this.ablyManager,
1098
- userId,
1527
+ from: this.senderId,
1528
+ agentId: this.agentId,
1099
1529
  agentName: this.config.agentName,
1100
1530
  client: this.client,
1531
+ incomingMessageId: payload.messageId,
1101
1532
  incomingDepth,
1102
1533
  incomingChain,
1103
- chunkBatchMs: this.config.chunkBatchMs ?? DEFAULT_CHUNK_BATCH_MS
1534
+ chunkBatchMs: this.config.chunkBatchMs ?? DEFAULT_CHUNK_BATCH_MS,
1535
+ tracker: this.tracker
1104
1536
  });
1105
1537
  if (this.messageHandler) {
1106
1538
  await this.messageHandler(
@@ -1113,9 +1545,14 @@ var JaibberAgent = class extends EventEmitter {
1113
1545
  type: payload.type,
1114
1546
  responseDepth: incomingDepth,
1115
1547
  respondingChain: incomingChain,
1116
- executionMode: payload.executionMode,
1548
+ executionMode,
1117
1549
  isAgentMessage: payload.isAgentMessage,
1118
- attachments: payload.attachments
1550
+ agentId: payload.agentId,
1551
+ agentName: payload.agentName,
1552
+ mentions: payload.mentions,
1553
+ parentMessageId: payload.parentMessageId,
1554
+ attachments,
1555
+ createdAt: payload.createdAt
1119
1556
  },
1120
1557
  ctx
1121
1558
  );
@@ -1123,7 +1560,7 @@ var JaibberAgent = class extends EventEmitter {
1123
1560
  }
1124
1561
  if (this.provider) {
1125
1562
  this.updateProviderSession(project.id);
1126
- const systemPrompt = this.config.agentInstructions ?? "";
1563
+ const systemPrompt = this.systemPromptFor(executionMode);
1127
1564
  await ctx.stream(
1128
1565
  () => this.provider.generate(payload.text, systemPrompt, conversationHistory)
1129
1566
  );
@@ -1134,36 +1571,55 @@ var JaibberAgent = class extends EventEmitter {
1134
1571
  "[sdk] No message handler or provider configured. Ignoring message."
1135
1572
  );
1136
1573
  }
1574
+ /** Agent instructions, prefixed with the plan-mode directive when requested. */
1575
+ systemPromptFor(executionMode) {
1576
+ const instructions2 = this.config.agentInstructions ?? "";
1577
+ if (executionMode !== "plan") return instructions2;
1578
+ return instructions2 ? `${PLAN_MODE_PREFIX}
1579
+
1580
+ ${instructions2}` : PLAN_MODE_PREFIX;
1581
+ }
1582
+ // ── Agent control (server-published lifecycle commands) ─────────────
1583
+ /** Is a server control event addressed to this agent? */
1584
+ isControlForMe(data) {
1585
+ if (this.agentId) return data.agentId === this.agentId;
1586
+ return !!data.agentName && data.agentName.toLowerCase() === this.config.agentName.toLowerCase();
1587
+ }
1588
+ /**
1589
+ * `agent-control` events are published by the server on project channels,
1590
+ * e.g. `{action: "deregister", agentId, agentName}` when an agent is revoked
1591
+ * via the API. Events for other agents are ignored.
1592
+ */
1593
+ async handleControlEvent(data, project) {
1594
+ if (!data || data.action !== "deregister") return;
1595
+ if (!this.isControlForMe(data)) return;
1596
+ console.log(
1597
+ `[sdk] Agent "${this.config.agentName}" was deregistered by the server (via project "${project.name}"). Shutting down...`
1598
+ );
1599
+ try {
1600
+ await this.disconnect();
1601
+ } catch (err) {
1602
+ console.error("[sdk] Error during deregister shutdown:", err);
1603
+ }
1604
+ this.emit("deregistered", data);
1605
+ if (this.config.exitOnDeregister !== false) {
1606
+ process.exit(0);
1607
+ }
1608
+ }
1137
1609
  // ── Task handling ───────────────────────────────────────────────────
1138
1610
  async handleTaskEvent(data, project) {
1139
1611
  if (data.type !== "task-created" && data.type !== "task-updated")
1140
1612
  return;
1141
1613
  const task = data.task;
1142
1614
  if (task.status !== "submitted") return;
1143
- if (!task.assignedAgentName || task.assignedAgentName.toLowerCase() !== this.config.agentName.toLowerCase())
1144
- return;
1615
+ const assignedById = !!task.assignedAgentId && !!this.agentId && task.assignedAgentId === this.agentId;
1616
+ const assignedByName = !!task.assignedAgentName && task.assignedAgentName.toLowerCase() === this.config.agentName.toLowerCase();
1617
+ if (!assignedById && !assignedByName) return;
1145
1618
  console.log(
1146
1619
  `[sdk] Picking up task: "${task.title}" (${task.id})`
1147
1620
  );
1148
1621
  try {
1149
1622
  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
1623
  const conversationHistory = this.getFormattedHistory(project.id);
1168
1624
  const ctx = new TaskContext({
1169
1625
  task,
@@ -1171,10 +1627,19 @@ var JaibberAgent = class extends EventEmitter {
1171
1627
  channelName: project.ablyChannelName,
1172
1628
  conversationHistory,
1173
1629
  ablyManager: this.ablyManager,
1174
- userId,
1630
+ from: this.senderId,
1631
+ agentId: this.agentId,
1175
1632
  agentName: this.config.agentName,
1176
- client: this.client
1633
+ client: this.client,
1634
+ tracker: this.tracker
1177
1635
  });
1636
+ try {
1637
+ await ctx.sendMessage(`Picking up task: **${task.title}**`, { type: "message" });
1638
+ } catch (err) {
1639
+ console.warn(
1640
+ `[sdk] Could not announce task pickup: ${err instanceof Error ? err.message : err}`
1641
+ );
1642
+ }
1178
1643
  if (this.taskHandler) {
1179
1644
  await this.taskHandler(task, ctx);
1180
1645
  return;
@@ -1190,12 +1655,14 @@ ${task.description}` : `Task: ${task.title}`;
1190
1655
  channelName: project.ablyChannelName,
1191
1656
  conversationHistory,
1192
1657
  ablyManager: this.ablyManager,
1193
- userId,
1658
+ from: this.senderId,
1659
+ agentId: this.agentId,
1194
1660
  agentName: this.config.agentName,
1195
1661
  client: this.client,
1196
1662
  incomingDepth: 0,
1197
1663
  incomingChain: [],
1198
- chunkBatchMs: this.config.chunkBatchMs ?? DEFAULT_CHUNK_BATCH_MS
1664
+ chunkBatchMs: this.config.chunkBatchMs ?? DEFAULT_CHUNK_BATCH_MS,
1665
+ tracker: this.tracker
1199
1666
  });
1200
1667
  try {
1201
1668
  await msgCtx.stream(
@@ -1245,6 +1712,11 @@ ${task.description}` : `Task: ${task.title}`;
1245
1712
  }
1246
1713
  }
1247
1714
  // ── Conversation history ────────────────────────────────────────────
1715
+ /** Is this stored message one of this agent's own prior replies? */
1716
+ isOwnServerMessage(m) {
1717
+ if (this.agentId && m.senderAgentId === this.agentId) return true;
1718
+ return m.senderType === "agent" && m.senderName.toLowerCase() === this.config.agentName.toLowerCase();
1719
+ }
1248
1720
  async loadHistory(projectId) {
1249
1721
  const contextSize = this.config.contextWindowSize ?? DEFAULT_CONTEXT_WINDOW;
1250
1722
  try {
@@ -1252,12 +1724,30 @@ ${task.description}` : `Task: ${task.title}`;
1252
1724
  projectId,
1253
1725
  contextSize
1254
1726
  );
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);
1727
+ const first = messages[0];
1728
+ const last = messages[messages.length - 1];
1729
+ if (first && last && first !== last && first.createdAt > last.createdAt) {
1730
+ messages.reverse();
1731
+ }
1732
+ const entries = [];
1733
+ for (const m of messages) {
1734
+ const own = this.isOwnServerMessage(m);
1735
+ const agentId = m.senderAgentId ?? (own ? this.agentId ?? void 0 : void 0);
1736
+ this.indexMessage(projectId, m.id, {
1737
+ agentId,
1738
+ senderName: own ? this.config.agentName : m.senderName,
1739
+ parentMessageId: m.parentMessageId ?? void 0
1740
+ });
1741
+ if (m.type === "system" || !m.text) continue;
1742
+ const sender = own || m.senderType === "agent" ? "agent" : "user";
1743
+ entries.push({
1744
+ sender,
1745
+ senderName: own ? this.config.agentName : m.senderName,
1746
+ text: m.text,
1747
+ agentId
1748
+ });
1749
+ }
1750
+ this.history.set(projectId, entries.slice(-contextSize));
1261
1751
  } catch (err) {
1262
1752
  console.error(
1263
1753
  `[sdk] Failed to load history for project ${projectId}:`,
@@ -1277,7 +1767,7 @@ ${task.description}` : `Task: ${task.title}`;
1277
1767
  }
1278
1768
  /**
1279
1769
  * Format conversation history for LLM context.
1280
- * Matches useAbly.ts lines 77-84 format.
1770
+ * Matches useAbly.ts format: `User: text` / `Assistant (Name): text`.
1281
1771
  */
1282
1772
  getFormattedHistory(projectId) {
1283
1773
  const entries = this.history.get(projectId) ?? [];
@@ -1290,9 +1780,10 @@ ${task.description}` : `Task: ${task.title}`;
1290
1780
 
1291
1781
  // src/cli.ts
1292
1782
  import { writeFileSync, mkdirSync } from "fs";
1293
- import { execSync } from "child_process";
1294
- import { homedir } from "os";
1783
+ import { execSync, spawn as spawn2 } from "child_process";
1784
+ import { homedir, hostname } from "os";
1295
1785
  import { join } from "path";
1786
+ import { fileURLToPath } from "url";
1296
1787
 
1297
1788
  // src/templates.ts
1298
1789
  var AGENT_TEMPLATES = [
@@ -1362,6 +1853,12 @@ function parseArgs(argv) {
1362
1853
  return args2;
1363
1854
  }
1364
1855
  var args = parseArgs(process.argv.slice(2));
1856
+ var DEFAULT_SERVER = "https://api.jaibber.com";
1857
+ var DEFAULTS = {
1858
+ anthropic: "claude-sonnet-4-6",
1859
+ openai: "gpt-4o",
1860
+ google: "gemini-pro-latest"
1861
+ };
1365
1862
  if (args["help"] || args["h"] || process.argv.length <= 2) {
1366
1863
  console.log(`
1367
1864
  Jaibber Agent CLI \u2014 run a headless AI agent
@@ -1369,29 +1866,43 @@ Jaibber Agent CLI \u2014 run a headless AI agent
1369
1866
  USAGE:
1370
1867
  npx @jaibber/sdk [options]
1371
1868
 
1869
+ AUTH (one of):
1870
+ --api-key <jb_...> Agent API key \u2014 the key IS the agent's identity
1871
+ (mint one with --create-key; env JAIBBER_API_KEY)
1872
+ --username <name> Jaibber account username, with:
1873
+ --password <pass> Jaibber account password (env JAIBBER_PASSWORD)
1874
+ The agent is registered under your account
1875
+ (POST /api/me/agents) and posts as itself.
1876
+
1372
1877
  REQUIRED:
1373
- --username <name> Jaibber account username
1374
- --password <pass> Jaibber account password
1375
1878
  --agent-name <name> Agent display name (used for @mention routing)
1376
1879
 
1377
1880
  PROVIDER (at least one required \u2014 first match wins):
1378
1881
  --anthropic-key <key> Anthropic API key (Claude)
1379
- --openai-key <key> OpenAI API key (GPT-4o)
1882
+ --openai-key <key> OpenAI API key (GPT)
1380
1883
  --google-key <key> Google AI API key (Gemini)
1381
1884
  --claude-cli Use local Claude CLI (no API key needed)
1382
1885
 
1383
1886
  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)
1887
+ --anthropic-model <id> Anthropic model (default: ${DEFAULTS.anthropic})
1888
+ --openai-model <id> OpenAI model (default: ${DEFAULTS.openai})
1889
+ --google-model <id> Gemini model (default: ${DEFAULTS.google})
1890
+
1891
+ ACCOUNT & SETUP (require --username/--password):
1892
+ --create-account Create a new Jaibber account, then continue
1893
+ --create-project <name> Create a new project and join it (prints project ID)
1894
+ --create-key Register the agent, assign it to --projects (or all
1895
+ your projects), mint an agent API key, print it, exit
1896
+ --org <id> Organization to register the agent / project under
1897
+ (default: your personal org)
1387
1898
 
1388
1899
  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)
1900
+ --install-service Install as a systemd user service and start it
1901
+ (Linux only; requires --api-key \u2014 passwords are never
1902
+ written to service files)
1392
1903
  --template <name> Use a preset agent template (sets agent-name + instructions)
1393
1904
  --list-templates Show available agent templates and exit
1394
- --server <url> Server URL (default: https://api.jaibber.com)
1905
+ --server <url> Server URL (default: ${DEFAULT_SERVER}; env JAIBBER_SERVER)
1395
1906
  --instructions <text> System prompt for the agent
1396
1907
  --machine-name <name> Machine identifier shown in presence
1397
1908
  --projects <id,id,...> Comma-separated project IDs to join (default: all)
@@ -1399,23 +1910,31 @@ OPTIONAL:
1399
1910
  --help Show this help message
1400
1911
 
1401
1912
  EXAMPLES:
1402
- # With Anthropic API key
1913
+ # First run: create an account, register the agent, chat via Anthropic
1403
1914
  npx @jaibber/sdk \\
1404
- --username coding-bot --password s3cret \\
1915
+ --create-account --username coding-bot --password s3cret \\
1405
1916
  --agent-name "CodingAgent" \\
1406
1917
  --anthropic-key sk-ant-api03-...
1407
1918
 
1408
- # With OpenAI
1919
+ # Existing account + local Claude CLI
1409
1920
  npx @jaibber/sdk \\
1410
1921
  --username coding-bot --password s3cret \\
1411
1922
  --agent-name "CodingAgent" \\
1412
- --openai-key sk-...
1923
+ --claude-cli --project-dir /path/to/project
1413
1924
 
1414
- # With local Claude CLI (no API key)
1925
+ # Mint an agent API key (shown once)
1415
1926
  npx @jaibber/sdk \\
1416
1927
  --username coding-bot --password s3cret \\
1417
- --agent-name "CodingAgent" \\
1418
- --claude-cli --project-dir /path/to/project
1928
+ --agent-name "CodingAgent" --projects abc-123 \\
1929
+ --create-key
1930
+
1931
+ # Run with the key (no password on the box)
1932
+ npx @jaibber/sdk --api-key jb_... --agent-name "CodingAgent" --claude-cli
1933
+
1934
+ # Install as a persistent background service (key goes into the unit)
1935
+ npx @jaibber/sdk \\
1936
+ --api-key jb_... --agent-name "CodingAgent" --claude-cli \\
1937
+ --install-service
1419
1938
 
1420
1939
  # Create a new project on first run
1421
1940
  npx @jaibber/sdk \\
@@ -1424,28 +1943,16 @@ EXAMPLES:
1424
1943
  --create-project "my-ubuntu-server" \\
1425
1944
  --claude-cli
1426
1945
 
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
1946
  ENVIRONMENT VARIABLES:
1947
+ JAIBBER_API_KEY Alternative to --api-key
1948
+ JAIBBER_PASSWORD Alternative to --password
1949
+ JAIBBER_SERVER Alternative to --server
1442
1950
  ANTHROPIC_API_KEY Alternative to --anthropic-key
1443
1951
  OPENAI_API_KEY Alternative to --openai-key
1444
1952
  GOOGLE_API_KEY Alternative to --google-key
1445
1953
  ANTHROPIC_MODEL Alternative to --anthropic-model
1446
1954
  OPENAI_MODEL Alternative to --openai-model
1447
1955
  GEMINI_MODEL Alternative to --google-model
1448
- JAIBBER_PASSWORD Alternative to --password
1449
1956
  `);
1450
1957
  process.exit(0);
1451
1958
  }
@@ -1466,8 +1973,10 @@ if (templateId && !template) {
1466
1973
  }
1467
1974
  var username = args["username"];
1468
1975
  var password = args["password"] || process.env.JAIBBER_PASSWORD;
1976
+ var apiKey = args["api-key"] || process.env.JAIBBER_API_KEY;
1469
1977
  var agentName = args["agent-name"] || template?.agentName;
1470
- var serverUrl = args["server"] || "https://api.jaibber.com";
1978
+ var serverUrl = args["server"] || process.env.JAIBBER_SERVER || DEFAULT_SERVER;
1979
+ var orgId = args["org"];
1471
1980
  var anthropicKey = args["anthropic-key"] || process.env.ANTHROPIC_API_KEY;
1472
1981
  var openaiKey = args["openai-key"] || process.env.OPENAI_API_KEY;
1473
1982
  var googleKey = args["google-key"] || process.env.GOOGLE_API_KEY;
@@ -1478,33 +1987,45 @@ var useClaudeCli = args["claude-cli"] === "true";
1478
1987
  var projectDir = args["project-dir"];
1479
1988
  var instructions = args["instructions"] || template?.instructions;
1480
1989
  var machineName = args["machine-name"];
1481
- var shouldRegister = args["register"] === "true";
1990
+ if (args["register"] === "true") {
1991
+ console.warn("[cli] --register is deprecated; use --create-account instead.");
1992
+ }
1993
+ var createAccount = args["create-account"] === "true" || args["register"] === "true";
1482
1994
  var createProjectName = args["create-project"];
1995
+ var createKey = args["create-key"] === "true";
1483
1996
  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) {
1997
+ var projectIds = args["projects"] ? args["projects"].split(",").map((s) => s.trim()).filter(Boolean) : void 0;
1998
+ var hasSession = !!username && !!password;
1999
+ if (!apiKey && !hasSession) {
1490
2000
  console.error(
1491
- "Error: --password is required (or set JAIBBER_PASSWORD env var)"
2001
+ "Error: provide an agent API key (--api-key or JAIBBER_API_KEY), or --username and --password (or JAIBBER_PASSWORD)."
1492
2002
  );
1493
2003
  process.exit(1);
1494
2004
  }
2005
+ if (apiKey && !apiKey.startsWith("jb_")) {
2006
+ console.error('Error: --api-key must be a Jaibber agent API key (starts with "jb_").');
2007
+ process.exit(1);
2008
+ }
1495
2009
  if (!agentName) {
1496
- console.error("Error: --agent-name is required");
2010
+ console.error("Error: --agent-name is required (or pick a --template)");
1497
2011
  process.exit(1);
1498
2012
  }
1499
- if (shouldRegister) {
1500
- console.log(`[cli] Registering new account "${username}"...`);
2013
+ if ((createAccount || createProjectName || createKey) && !hasSession) {
2014
+ console.error(
2015
+ "Error: --create-account, --create-project and --create-key act on your user account and require --username and --password."
2016
+ );
2017
+ process.exit(1);
2018
+ }
2019
+ var providerLabel = anthropicKey ? "claude" : openaiKey ? "openai" : googleKey ? "google" : useClaudeCli ? "claude" : "custom";
2020
+ if (createAccount) {
2021
+ console.log(`[cli] Creating account "${username}"...`);
1501
2022
  const client = new JaibberClient(serverUrl);
1502
2023
  try {
1503
2024
  await client.register(username, password);
1504
2025
  console.log(`[cli] Account created successfully.`);
1505
2026
  } catch (err) {
1506
2027
  console.error(
1507
- `[cli] Registration failed: ${err instanceof Error ? err.message : err}`
2028
+ `[cli] Account creation failed: ${err instanceof Error ? err.message : err}`
1508
2029
  );
1509
2030
  process.exit(1);
1510
2031
  }
@@ -1515,7 +2036,7 @@ if (createProjectName) {
1515
2036
  const client = new JaibberClient(serverUrl);
1516
2037
  try {
1517
2038
  await client.login(username, password);
1518
- const project = await client.createProject(createProjectName);
2039
+ const project = await client.createProject(createProjectName, void 0, orgId);
1519
2040
  console.log(`[cli] Project created: ${project.name}`);
1520
2041
  console.log(`[cli] Project ID: ${project.id}`);
1521
2042
  console.log(`[cli] Share this ID with teammates to join the project.`);
@@ -1527,26 +2048,75 @@ if (createProjectName) {
1527
2048
  process.exit(1);
1528
2049
  }
1529
2050
  }
2051
+ if (createKey) {
2052
+ const client = new JaibberClient(serverUrl);
2053
+ try {
2054
+ await client.login(username, password);
2055
+ const agent2 = await client.ensureAgent({
2056
+ name: agentName,
2057
+ instructions,
2058
+ provider: providerLabel,
2059
+ kind: "sdk",
2060
+ machineName,
2061
+ orgId
2062
+ });
2063
+ console.log(`[cli] Agent "${agent2.name}" registered (id ${agent2.id}).`);
2064
+ const targets = resolvedProjectIds ?? (await client.listProjects()).filter((p) => p.role !== "org-admin").map((p) => p.id);
2065
+ for (const pid of targets) {
2066
+ await client.assignAgent(agent2.id, pid);
2067
+ }
2068
+ console.log(`[cli] Assigned to ${targets.length} project(s).`);
2069
+ const key = await client.createAgentKey(agent2.id, machineName || hostname());
2070
+ console.log(`
2071
+ [cli] Agent API key (shown once \u2014 store it securely):
2072
+
2073
+ ${key.key}
2074
+ `);
2075
+ console.log(`[cli] Run the agent with:`);
2076
+ console.log(` jaibber-agent --api-key ${key.key} --agent-name "${agentName}" <provider flags>`);
2077
+ console.log(`[cli] Or install it as a service:`);
2078
+ console.log(` jaibber-agent --api-key ${key.key} --agent-name "${agentName}" <provider flags> --install-service`);
2079
+ } catch (err) {
2080
+ console.error(`[cli] Failed to create key: ${err instanceof Error ? err.message : err}`);
2081
+ process.exit(1);
2082
+ }
2083
+ process.exit(0);
2084
+ }
2085
+ function shellQuote(s) {
2086
+ if (/^[A-Za-z0-9_\/.:=@%+,-]+$/.test(s)) return s;
2087
+ return `'${s.replace(/'/g, `'\\''`)}'`;
2088
+ }
1530
2089
  if (installService) {
2090
+ if (!apiKey) {
2091
+ console.error(
2092
+ `Error: --install-service requires an agent API key (--api-key or JAIBBER_API_KEY).
2093
+ Passwords are never written to service files. Mint a key for this agent with:
2094
+
2095
+ jaibber-agent --username <user> --password <pass> --agent-name "${agentName}" --create-key
2096
+
2097
+ then re-run with --api-key jb_... --install-service`
2098
+ );
2099
+ process.exit(1);
2100
+ }
1531
2101
  const binaryPath = process.execPath;
1532
- const scriptPath = new URL(import.meta.url).pathname;
2102
+ const scriptPath = fileURLToPath(import.meta.url);
2103
+ const env = { JAIBBER_API_KEY: apiKey };
2104
+ if (anthropicKey) env.ANTHROPIC_API_KEY = anthropicKey;
2105
+ if (openaiKey) env.OPENAI_API_KEY = openaiKey;
2106
+ if (googleKey) env.GOOGLE_API_KEY = googleKey;
1533
2107
  const flags = [];
1534
- flags.push(`--username`, username);
1535
- flags.push(`--password`, password);
1536
2108
  flags.push(`--agent-name`, agentName);
1537
2109
  if (resolvedProjectIds?.length) flags.push(`--projects`, resolvedProjectIds.join(","));
1538
- if (serverUrl !== "https://api.jaibber.com") flags.push(`--server`, serverUrl);
2110
+ if (serverUrl !== DEFAULT_SERVER) flags.push(`--server`, serverUrl);
1539
2111
  if (instructions) flags.push(`--instructions`, instructions);
1540
2112
  if (machineName) flags.push(`--machine-name`, machineName);
1541
2113
  if (projectDir) flags.push(`--project-dir`, projectDir);
1542
2114
  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
2115
  if (anthropicModel) flags.push(`--anthropic-model`, anthropicModel);
1547
2116
  if (openaiModel) flags.push(`--openai-model`, openaiModel);
1548
2117
  if (googleModel) flags.push(`--google-model`, googleModel);
1549
- const execStart = `${binaryPath} ${scriptPath} ${flags.map((f) => f.includes(" ") ? `"${f}"` : f).join(" ")}`;
2118
+ const execStart = [binaryPath, scriptPath, ...flags].map(shellQuote).join(" ");
2119
+ const envLines = Object.entries(env).map(([k, v]) => `Environment="${k}=${v.replace(/(["\\])/g, "\\$1")}"`).join("\n");
1550
2120
  const serviceContent = `[Unit]
1551
2121
  Description=Jaibber Agent (${agentName})
1552
2122
  After=network-online.target
@@ -1558,6 +2128,7 @@ ExecStart=${execStart}
1558
2128
  Restart=on-failure
1559
2129
  RestartSec=10
1560
2130
  Environment=HOME=${homedir()}
2131
+ ${envLines}
1561
2132
 
1562
2133
  [Install]
1563
2134
  WantedBy=default.target
@@ -1567,7 +2138,7 @@ WantedBy=default.target
1567
2138
  const serviceName = `${serviceSlug}.service`;
1568
2139
  const servicePath = join(serviceDir, serviceName);
1569
2140
  mkdirSync(serviceDir, { recursive: true });
1570
- writeFileSync(servicePath, serviceContent);
2141
+ writeFileSync(servicePath, serviceContent, { mode: 384 });
1571
2142
  try {
1572
2143
  execSync(`systemctl --user daemon-reload`, { stdio: "ignore" });
1573
2144
  execSync(`systemctl --user enable --now ${serviceName}`, { stdio: "ignore" });
@@ -1577,7 +2148,8 @@ WantedBy=default.target
1577
2148
  console.log(`[cli] journalctl --user -u ${serviceSlug} -f`);
1578
2149
  } catch {
1579
2150
  const logFile = `${homedir()}/${serviceSlug}.log`;
1580
- const cronLine = `@reboot ${execStart} >> ${logFile} 2>&1`;
2151
+ const envPrefix = Object.entries(env).map(([k, v]) => `${k}=${shellQuote(v)}`).join(" ");
2152
+ const cronLine = `@reboot ${envPrefix} ${execStart} >> ${shellQuote(logFile)} 2>&1`;
1581
2153
  const cronMarker = `jaibber:${serviceSlug}`;
1582
2154
  try {
1583
2155
  let existing = "";
@@ -1588,15 +2160,15 @@ WantedBy=default.target
1588
2160
  const filtered = existing.split("\n").filter((l) => !l.includes(cronMarker) && !l.includes(serviceSlug)).join("\n").trimEnd();
1589
2161
  const newCrontab = (filtered ? filtered + "\n" : "") + `# ${cronMarker}
1590
2162
  ` + cronLine + "\n";
1591
- execSync(`echo ${JSON.stringify(newCrontab)} | crontab -`);
2163
+ execSync("crontab -", { input: newCrontab });
1592
2164
  console.log(`[cli] Service installed via crontab (starts on reboot).`);
1593
2165
  console.log(`[cli] View log: tail -f ~/${serviceSlug}.log`);
1594
2166
  console.log(`[cli] Remove: crontab -e (delete the ${serviceSlug} lines)`);
1595
2167
  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], {
2168
+ spawn2(binaryPath, [scriptPath, ...flags], {
1598
2169
  detached: true,
1599
- stdio: ["ignore", "ignore", "ignore"]
2170
+ stdio: ["ignore", "ignore", "ignore"],
2171
+ env: { ...process.env, ...env }
1600
2172
  }).unref();
1601
2173
  console.log(`[cli] Agent started in background.`);
1602
2174
  } catch (cronErr) {
@@ -1608,19 +2180,17 @@ WantedBy=default.target
1608
2180
  }
1609
2181
  process.exit(0);
1610
2182
  }
2183
+ var credentials = apiKey ? { apiKey } : { username, password };
1611
2184
  var agent = new JaibberAgent({
1612
2185
  serverUrl,
1613
- credentials: { username, password },
2186
+ credentials,
1614
2187
  agentName,
1615
2188
  agentInstructions: instructions,
1616
2189
  machineName,
1617
- projectIds: resolvedProjectIds
2190
+ projectIds: resolvedProjectIds,
2191
+ provider: providerLabel,
2192
+ orgId
1618
2193
  });
1619
- var DEFAULTS = {
1620
- anthropic: "claude-sonnet-4-6",
1621
- openai: "gpt-4o",
1622
- google: "gemini-pro-latest"
1623
- };
1624
2194
  if (anthropicKey) {
1625
2195
  const model = anthropicModel || DEFAULTS.anthropic;
1626
2196
  agent.useProvider("anthropic", { apiKey: anthropicKey, model });
@@ -1656,7 +2226,7 @@ process.on("SIGINT", shutdown);
1656
2226
  process.on("SIGTERM", shutdown);
1657
2227
  try {
1658
2228
  await agent.connect();
1659
- console.log(`[cli] Agent "${agentName}" is running. Press Ctrl+C to stop.`);
2229
+ console.log(`[cli] Agent "${agentName}" (id ${agent.id}) is running. Press Ctrl+C to stop.`);
1660
2230
  } catch (err) {
1661
2231
  console.error(
1662
2232
  `[cli] Failed to start: ${err instanceof Error ? err.message : err}`