@jaibber/sdk 0.3.7 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,177 +1,161 @@
1
1
  import { EventEmitter } from 'events';
2
2
 
3
- /**
4
- * Provider interface for LLM backends.
5
- * Implementations return an async generator that yields text chunks.
6
- */
7
- interface Provider {
8
- generate(prompt: string, systemPrompt: string, conversationContext: string): AsyncGenerator<string, void, unknown>;
9
- }
10
- interface AnthropicProviderOptions {
11
- /** Anthropic API key (sk-ant-...) */
12
- apiKey: string;
13
- /** Model ID (default: "claude-sonnet-4-20250514") */
14
- model?: string;
15
- /** Max tokens (default: 8192) */
16
- maxTokens?: number;
17
- }
18
- interface OpenAIProviderOptions {
19
- /** OpenAI API key (sk-...) */
20
- apiKey: string;
21
- /** Model ID (default: "gpt-4o") */
22
- model?: string;
23
- /** Max tokens (default: 8192) */
24
- maxTokens?: number;
25
- }
26
- interface GoogleProviderOptions {
27
- /** Google AI API key (AIza...) */
28
- apiKey: string;
29
- /** Model ID (default: "gemini-flash-latest" — Google's auto-updating alias) */
30
- model?: string;
31
- /** Max tokens (default: 8192) */
32
- maxTokens?: number;
33
- }
34
- interface ClaudeCLIProviderOptions {
35
- /** Working directory for Claude CLI (default: cwd) */
36
- projectDir?: string;
37
- /** Session ID for --resume (resumes a specific prior session) */
38
- sessionId?: string;
39
- /** If true and no sessionId, use --continue to resume last session in project dir */
40
- continueSession?: boolean;
41
- }
42
-
43
- /**
44
- * REST API client wrapping the Jaibber server endpoints.
45
- * Handles JWT auth (login), project listing, message persistence,
46
- * task updates, and Ably token requests.
47
- */
48
- declare class JaibberClient {
49
- private serverUrl;
50
- private jwt;
51
- userId: string | null;
52
- username: string | null;
53
- constructor(serverUrl: string);
54
- /** POST /api/auth/register — create a new account, stores JWT. */
55
- register(username: string, password: string): Promise<void>;
56
- /** POST /api/auth/token — login with credentials, stores JWT. */
57
- login(username: string, password: string): Promise<void>;
58
- get isAuthenticated(): boolean;
59
- private authHeaders;
60
- /** GET /api/projects — list all projects user is member of. */
61
- listProjects(): Promise<Project[]>;
62
- /** POST /api/projects — create a new project, returns it. */
63
- createProject(name: string, description?: string): Promise<Project>;
64
- /** POST /api/ably/token — get scoped Ably TokenRequest. */
65
- getAblyToken(): Promise<object>;
66
- /**
67
- * POST /api/projects/{id}/messages — persist a message (idempotent).
68
- * Passing a client-generated `id` makes the server skip Ably re-publish.
69
- */
70
- persistMessage(projectId: string, msg: PersistMessagePayload): Promise<void>;
71
- /** GET /api/projects/{id}/messages — fetch recent messages. */
72
- fetchMessages(projectId: string, limit?: number): Promise<ServerMessage[]>;
73
- /** POST /api/projects/{id}/tasks — create a task. */
74
- createTask(projectId: string, data: {
75
- title: string;
76
- description?: string;
77
- priority?: string;
78
- assignedAgentName?: string;
79
- parentTaskId?: string;
80
- createdByType?: "user" | "agent";
81
- createdByName?: string;
82
- }): Promise<Task>;
83
- /** PATCH /api/tasks/{taskId} — update task fields. */
84
- updateTask(taskId: string, updates: Partial<Task>): Promise<void>;
85
- }
86
-
87
3
  /** Presence data entered on each project channel. */
88
4
  interface AgentPresenceData {
89
- userId: string;
5
+ /** Hosting user id (absent in API-key mode). */
6
+ userId?: string;
90
7
  username: string;
91
8
  isAgent: boolean;
92
9
  agentName: string;
10
+ /** The agent's server-side id. */
11
+ agentId?: string;
93
12
  agentInstructions?: string;
94
13
  agents?: Array<{
14
+ agentId?: string;
95
15
  agentName: string;
96
16
  agentInstructions?: string;
97
17
  }>;
98
18
  machineName?: string;
99
19
  }
20
+ /** Presence data entered on the global `jaibber:presence` channel. */
21
+ interface GlobalPresenceData {
22
+ userId?: string;
23
+ agentId?: string;
24
+ username: string;
25
+ projectIds: string[];
26
+ }
100
27
  /**
101
28
  * Manages the Ably Realtime connection, channel subscriptions, and presence.
102
29
  * Node.js equivalent of the frontend's src/lib/ably.ts + useAbly.ts subscription logic.
103
30
  */
104
31
  declare class AblyManager {
105
32
  private client;
106
- private userId;
107
- private username;
33
+ private opts;
108
34
  private ably;
109
35
  private channels;
110
36
  private presenceChannel;
111
- constructor(client: JaibberClient, userId: string, username: string);
37
+ constructor(client: JaibberClient, opts: {
38
+ /**
39
+ * Explicit Ably clientId. Session mode passes the userId (the token's
40
+ * clientId). API-key mode leaves it unset so the connection adopts the
41
+ * token's clientId (`agent:{agentId}`).
42
+ */
43
+ clientId?: string;
44
+ username: string;
45
+ });
112
46
  /** Create Ably Realtime client with token auth callback. */
113
- connect(): Promise<void>;
47
+ connect(timeoutMs?: number): Promise<void>;
114
48
  /** Enter global presence channel (jaibber:presence). */
115
- enterGlobalPresence(projectIds: string[]): Promise<void>;
49
+ enterGlobalPresence(data: GlobalPresenceData): Promise<void>;
116
50
  /**
117
- * Subscribe to a project channel and enter per-project presence.
51
+ * Subscribe to a project channel (`message`, `task` and server-published
52
+ * `agent-control` events) and enter per-project presence.
118
53
  * Returns an unsubscribe function.
119
54
  */
120
- subscribeToProject(project: Project, presenceData: AgentPresenceData, onMessage: (msg: AblyMessage) => void, onTask: (data: TaskEvent) => void): Promise<() => void>;
121
- /** Publish a message on a project channel. */
55
+ subscribeToProject(project: Project, presenceData: AgentPresenceData, onMessage: (msg: AblyMessage) => void, onTask: (data: TaskEvent) => void, onControl?: (data: AgentControlEvent) => void): Promise<() => void>;
56
+ /**
57
+ * Publish a client-side event on a project channel. Only `typing` and
58
+ * `chunk` are client-published; final messages go through the REST API
59
+ * and are echoed by the server.
60
+ */
122
61
  publish(channelName: string, eventName: string, data: AblyMessage): Promise<void>;
123
62
  /** Get the Ably connection ID (used for skip logic). */
124
63
  get connectionId(): string | undefined;
64
+ /** The clientId this connection authenticated as (from the token in API-key mode). */
65
+ get clientId(): string | undefined;
125
66
  /** Leave presence on all channels and close the connection. */
126
67
  disconnect(): Promise<void>;
127
68
  }
128
69
 
70
+ type PostedType = "message" | "response" | "error";
71
+ /**
72
+ * Lets the owning agent learn about messages this context POSTs, so it can
73
+ * (a) dedupe the server's Ably echo by message id and (b) feed the agent's own
74
+ * replies back into conversation history.
75
+ */
76
+ interface OwnMessageTracker {
77
+ /** Called with the client-generated id right before the POST. */
78
+ begin(id: string, projectId: string, text: string, type: PostedType, parentMessageId?: string): void;
79
+ /** Called after the server accepted the message. */
80
+ posted(id: string): void;
81
+ /** Called when the POST failed (the message never existed server-side). */
82
+ failed(id: string): void;
83
+ }
84
+ interface ReplyOptions {
85
+ /**
86
+ * Thread the reply under this message id. Replies default to the message
87
+ * being answered — that link is how agent-to-agent chains are tracked.
88
+ */
89
+ parentMessageId?: string;
90
+ }
129
91
  /**
130
92
  * Context passed to message handlers.
131
93
  * Provides `reply()` for one-shot responses and `stream()` for streaming.
132
- * Handles the full Ably publish protocol: typing → chunks → response.
94
+ *
95
+ * Protocol: `typing` and `chunk` events are published to Ably by the client;
96
+ * the final message is POSTed to the server, which persists it, attributes it
97
+ * to the agent, and publishes the echo to Ably itself.
133
98
  */
134
99
  declare class MessageContext {
135
100
  /** Formatted conversation history for LLM prompts. */
136
101
  readonly conversationHistory: string;
137
102
  /** The project ID this message was received on. */
138
103
  readonly projectId: string;
139
- private responseId;
104
+ /** The agent's server-side id (sent as `agentId` on every save). */
105
+ readonly agentId: string;
106
+ /** The agent's display name. */
107
+ readonly agentName: string;
108
+ /** Id of the message being responded to (if any). */
109
+ readonly incomingMessageId?: string;
110
+ /**
111
+ * The id the final reply will be stored under. Also the `responseId` sent
112
+ * with `typing` so clients can pre-create the bubble.
113
+ */
114
+ readonly messageId: string;
140
115
  private ablyManager;
141
116
  private channelName;
142
- private userId;
143
- private agentName;
117
+ private from;
144
118
  private client;
145
119
  private responseDepth;
146
120
  private respondingChain;
147
121
  private chunkBatchMs;
122
+ private tracker?;
148
123
  constructor(opts: {
149
124
  projectId: string;
150
125
  channelName: string;
151
126
  conversationHistory: string;
152
127
  ablyManager: AblyManager;
153
- userId: string;
128
+ /** Sender id for client-published events (userId, or `agent:{id}` in API-key mode). */
129
+ from: string;
130
+ agentId: string;
154
131
  agentName: string;
155
132
  client: JaibberClient;
133
+ incomingMessageId?: string;
156
134
  incomingDepth: number;
157
135
  incomingChain: string[];
158
136
  chunkBatchMs: number;
137
+ tracker?: OwnMessageTracker;
159
138
  });
160
- /** One-shot reply: publishes typing → response in sequence. */
161
- reply(text: string): Promise<void>;
139
+ /** Agent-to-agent hop count this reply will carry (informational). */
140
+ get depth(): number;
141
+ /** Agents that have already responded in this chain, including this one. */
142
+ get chain(): string[];
143
+ /** One-shot reply: publishes `typing`, then POSTs the final message. */
144
+ reply(text: string, opts?: ReplyOptions): Promise<ServerMessage>;
145
+ /** Replies thread under the answered message unless overridden. */
146
+ private parentFor;
162
147
  /**
163
148
  * Streaming reply: consumes an async generator, batches chunks to Ably
164
- * every chunkBatchMs (default 200ms), then publishes the final response.
149
+ * every chunkBatchMs (default 200ms), then POSTs the final message.
150
+ * Resolves with the full response text.
165
151
  *
166
- * Mirrors useAbly.ts lines 86-102 chunk batching pattern.
152
+ * Mirrors useAbly.ts chunk batching pattern.
167
153
  */
168
- stream(generator: () => AsyncGenerator<string, void, unknown>): Promise<void>;
154
+ stream(generator: () => AsyncGenerator<string, void, unknown>, opts?: ReplyOptions): Promise<string>;
169
155
  private publishTyping;
170
156
  private publishChunk;
171
- private publishResponse;
172
- private publishError;
173
- /** Fire-and-forget persist to server. */
174
- private persistAsync;
157
+ /** POST the final message. Throws if the server rejects it. */
158
+ private persist;
175
159
  }
176
160
  /**
177
161
  * Context passed to task handlers.
@@ -182,59 +166,123 @@ declare class TaskContext {
182
166
  readonly task: Task;
183
167
  readonly projectId: string;
184
168
  readonly conversationHistory: string;
185
- private ablyManager;
186
- private channelName;
187
- private userId;
188
- private agentName;
169
+ readonly agentId: string;
170
+ readonly agentName: string;
189
171
  private client;
172
+ private tracker?;
190
173
  constructor(opts: {
191
174
  task: Task;
192
175
  projectId: string;
193
176
  channelName: string;
194
177
  conversationHistory: string;
195
178
  ablyManager: AblyManager;
196
- userId: string;
179
+ from: string;
180
+ agentId: string;
197
181
  agentName: string;
198
182
  client: JaibberClient;
183
+ tracker?: OwnMessageTracker;
199
184
  });
200
- /** Mark task as completed, optionally publishing a response message. */
185
+ /** Mark task as completed, optionally posting a response message. */
201
186
  complete(resultText?: string): Promise<void>;
202
- /** Mark task as failed, optionally publishing an error message. */
187
+ /** Mark task as failed, optionally posting an error message. */
203
188
  fail(errorText?: string): Promise<void>;
204
189
  /**
205
190
  * Create a follow-up task assigned to another agent.
206
- * Automatically sets parentTaskId to the current task's ID.
191
+ * Automatically sets parentTaskId to the current task's ID and attributes
192
+ * creation to this agent.
207
193
  */
208
194
  createFollowUpTask(data: {
209
195
  title: string;
210
196
  description?: string;
211
197
  priority?: "low" | "medium" | "high" | "urgent";
212
198
  assignedAgentName?: string;
199
+ assignedAgentId?: string;
213
200
  }): Promise<Task>;
214
- /** Send a chat message (for progress updates). */
215
- sendMessage(text: string): Promise<void>;
201
+ /**
202
+ * Post a chat message (for progress updates). Returns the stored message.
203
+ * `type` defaults to "response"; use "message" for notices that must never
204
+ * trigger other agents (agent-to-agent chaining only flows through responses).
205
+ */
206
+ sendMessage(text: string, opts?: ReplyOptions & {
207
+ type?: PostedType;
208
+ }): Promise<ServerMessage>;
216
209
  }
217
210
 
218
211
  type ExecutionMode = "auto" | "plan";
212
+ /** Server-side provider label stored on the agent record. */
213
+ type AgentProvider = "claude" | "codex" | "gemini" | "openai" | "google" | "openclaw" | "custom";
214
+ /** Hosted agent kinds the SDK can register as. */
215
+ type AgentKind = "desktop" | "sdk";
216
+ /** An `agents` row as returned by `/api/me/agents`. */
217
+ interface AgentRecord {
218
+ id: string;
219
+ orgId: string | null;
220
+ name: string;
221
+ handle: string | null;
222
+ kind: string;
223
+ provider: AgentProvider | string;
224
+ instructions: string | null;
225
+ machineName: string | null;
226
+ status: "active" | "paused" | "revoked" | string;
227
+ trustTier: string;
228
+ /** Present on `GET /api/me/agents`. */
229
+ assignments?: Array<{
230
+ projectId: string;
231
+ }>;
232
+ }
233
+ /** Input for `JaibberClient.ensureAgent()` (`POST /api/me/agents`). */
234
+ interface EnsureAgentInput {
235
+ name: string;
236
+ instructions?: string;
237
+ provider?: AgentProvider;
238
+ kind: AgentKind;
239
+ machineName?: string;
240
+ /** Also assign the agent to this project in the same call. */
241
+ projectId?: string;
242
+ /**
243
+ * Organization to register the agent under. Optional — the server
244
+ * defaults to the caller's personal org. Only sent when set.
245
+ */
246
+ orgId?: string;
247
+ }
248
+ /** A freshly minted agent-bound API key. The raw `key` is returned once. */
249
+ interface AgentApiKey {
250
+ id: string;
251
+ key: string;
252
+ prefix: string;
253
+ }
219
254
  interface AblyMessage {
255
+ /** Sender userId (server-derived on final events; `api:{keyId}` for key senders). */
220
256
  from: string;
221
257
  fromUsername: string;
222
258
  projectId: string;
223
259
  text: string;
224
260
  messageId: string;
225
- type: "message" | "response" | "typing" | "done" | "error" | "chunk" | "task-created" | "task-updated" | "task-deleted" | "deregister";
261
+ type: "message" | "response" | "typing" | "error" | "chunk" | "meta" | "task-created" | "task-updated" | "task-deleted";
226
262
  responseId?: string;
227
263
  agentName?: string;
264
+ /** Server agent id on agent-attributed final events. */
265
+ agentId?: string;
228
266
  mentions?: string[];
267
+ /** `meta` hint (and legacy `message`) so agents know which mode to use. */
229
268
  executionMode?: ExecutionMode;
269
+ /**
270
+ * True if this message is attributed to an agent (not a human). Chains are
271
+ * reconstructed from `parentMessageId` links — there is no depth on the wire.
272
+ */
230
273
  isAgentMessage?: boolean;
231
- responseDepth?: number;
232
- respondingChain?: string[];
274
+ /** Legacy client-published task notifications — never trigger agent responses. */
233
275
  isTaskNotification?: boolean;
276
+ /** File attachments (`meta` hint and legacy `message`). */
234
277
  attachments?: MessageAttachment[];
278
+ /** Reply threading; agent responses reply to the message they answered. */
235
279
  parentMessageId?: string;
280
+ /** Server timestamp on server-published final events. */
281
+ createdAt?: string;
236
282
  /** Injected by AblyManager — not on the wire. Used for connection-level self-skip. */
237
283
  _connectionId?: string;
284
+ /** Injected by AblyManager — not on the wire. Authenticated Ably clientId of a client publisher. */
285
+ _clientId?: string;
238
286
  }
239
287
  type TaskStatus = "submitted" | "working" | "input-required" | "completed" | "failed" | "cancelled";
240
288
  type TaskPriority = "low" | "medium" | "high" | "urgent";
@@ -246,9 +294,12 @@ interface Task {
246
294
  status: TaskStatus;
247
295
  priority: TaskPriority;
248
296
  assignedAgentName: string | null;
297
+ /** Id of the assigned agent (name column kept for display/compat). */
298
+ assignedAgentId: string | null;
249
299
  createdBy: string;
250
300
  createdByType: "user" | "agent";
251
301
  createdByName: string;
302
+ createdByAgentId: string | null;
252
303
  sourceMessageId: string | null;
253
304
  parentTaskId: string | null;
254
305
  createdAt: string;
@@ -265,7 +316,9 @@ interface Project {
265
316
  id: string;
266
317
  name: string;
267
318
  description: string | null;
319
+ orgId: string | null;
268
320
  ablyChannelName: string;
321
+ /** "admin" | "member" | "org-admin" for sessions; assignment role for agent keys. */
269
322
  role: string;
270
323
  }
271
324
  interface IncomingMessage {
@@ -275,74 +328,268 @@ interface IncomingMessage {
275
328
  fromUsername: string;
276
329
  text: string;
277
330
  type: string;
331
+ /**
332
+ * Agent-to-agent hop count ending at this message (0 for human messages),
333
+ * reconstructed from `parentMessageId` links.
334
+ */
278
335
  responseDepth: number;
336
+ /** Lowercased names of the agents in that run (empty for human messages). */
279
337
  respondingChain: string[];
280
338
  executionMode?: ExecutionMode;
281
339
  isAgentMessage?: boolean;
340
+ /** Set when the sender is a registered agent. */
341
+ agentId?: string;
342
+ agentName?: string;
343
+ mentions?: string[];
344
+ parentMessageId?: string;
282
345
  attachments?: MessageAttachment[];
346
+ createdAt?: string;
283
347
  }
284
348
  interface TaskEvent {
285
349
  type: "task-created" | "task-updated" | "task-deleted";
286
350
  task: Task;
287
351
  projectId: string;
288
352
  }
353
+ interface AgentControlEvent {
354
+ /** "deregister" when the agent was revoked via the API. */
355
+ action: "deregister" | string;
356
+ agentId?: string;
357
+ agentName?: string;
358
+ }
359
+ /**
360
+ * How the agent authenticates.
361
+ * - `{ username, password }`: log in as the hosting user, then register/upsert
362
+ * the agent record (`POST /api/me/agents`) and post as that agent.
363
+ * - `{ apiKey }`: an agent-bound key (`jb_…`). The key IS the identity — no
364
+ * login, no registration; projects are the agent's assignments.
365
+ */
366
+ type AgentCredentials = {
367
+ username: string;
368
+ password: string;
369
+ } | {
370
+ apiKey: string;
371
+ };
289
372
  interface AgentConfig {
290
373
  /** Jaibber server URL (e.g. "https://api.jaibber.com") */
291
374
  serverUrl: string;
292
- /** Login credentials for the agent's Jaibber account */
293
- credentials: {
294
- username: string;
295
- password: string;
296
- };
375
+ /** Session credentials or an agent-bound API key. */
376
+ credentials: AgentCredentials;
297
377
  /** Agent display name (used for @mention routing and presence) */
298
378
  agentName: string;
299
- /** System prompt prepended to every LLM call */
379
+ /** System prompt prepended to every LLM call (also stored on the agent record) */
300
380
  agentInstructions?: string;
301
381
  /** Machine identifier shown in presence */
302
382
  machineName?: string;
303
- /** Specific project IDs to join. Omit to join all user's projects. */
383
+ /** Specific project IDs to join. Omit to join all member/assigned projects. */
304
384
  projectIds?: string[];
385
+ /**
386
+ * Provider label stored on the agent record. Defaults to the backend chosen
387
+ * with `useProvider()` ("claude" | "openai" | "google"), else "custom".
388
+ */
389
+ provider?: AgentProvider;
390
+ /** Organization to register the agent under (session mode). Default: personal org. */
391
+ orgId?: string;
392
+ /**
393
+ * The agent's id. Resolved during `connect()`: from `POST /api/me/agents`
394
+ * (session mode) or from the key's Ably clientId (API-key mode). May be
395
+ * pre-supplied in API-key mode to skip resolution.
396
+ */
397
+ agentId?: string;
305
398
  /** Max depth for agent-to-agent chains (default: 3) */
306
399
  maxResponseDepth?: number;
307
400
  /** Chunk batching interval in ms (default: 200) */
308
401
  chunkBatchMs?: number;
309
402
  /** Number of recent messages for conversation context (default: 20) */
310
403
  contextWindowSize?: number;
404
+ /** Heartbeat interval in ms (default: 120_000) */
405
+ heartbeatMs?: number;
406
+ /**
407
+ * When the server revokes this agent (`agent-control` event with
408
+ * `action: "deregister"`), the agent disconnects and, by default, exits the
409
+ * process. Set false to only disconnect and emit "deregistered".
410
+ */
411
+ exitOnDeregister?: boolean;
311
412
  }
312
413
  type MessageHandler = (message: IncomingMessage, context: MessageContext) => Promise<void>;
313
414
  type TaskHandler = (task: Task, context: TaskContext) => Promise<void>;
314
415
  interface ServerMessage {
315
416
  id: string;
316
417
  projectId: string;
317
- senderId: string;
418
+ senderId?: string;
318
419
  senderType: "user" | "agent" | "api";
319
420
  senderName: string;
320
- type: "message" | "response" | "error";
421
+ /** Set exactly when senderType === "agent". */
422
+ senderAgentId: string | null;
423
+ type: "message" | "response" | "error" | "system";
321
424
  text: string;
322
- parentMessageId?: string;
425
+ parentMessageId: string | null;
426
+ metadata?: Record<string, unknown> | null;
323
427
  createdAt: string;
324
428
  }
325
429
  interface PersistMessagePayload {
326
- id: string;
327
- senderType: "agent";
328
- senderName: string;
329
- type: "message" | "response" | "error";
430
+ /** Client-generated id (8–64 chars of [A-Za-z0-9_-]) used to dedupe the Ably echo. */
431
+ id?: string;
432
+ /** Post as this hosted agent. Required in session mode, ignored for agent keys. */
433
+ agentId?: string;
434
+ type?: "message" | "response" | "error";
330
435
  text: string;
331
436
  parentMessageId?: string;
437
+ mentions?: string[];
438
+ }
439
+
440
+ /**
441
+ * REST API client wrapping the Jaibber server endpoints.
442
+ *
443
+ * Authenticates either with a session JWT (`login()` / `register()` /
444
+ * `setToken()`) or with an agent-bound API key (`jb_…`). `authHeaders()` is
445
+ * the single choke point: an API key is sent as `X-API-Key`, a session as
446
+ * `Authorization: Bearer`. When both are configured the API key wins.
447
+ */
448
+ declare class JaibberClient {
449
+ private serverUrl;
450
+ private jwt;
451
+ private apiKey;
452
+ userId: string | null;
453
+ username: string | null;
454
+ constructor(serverUrl: string, opts?: {
455
+ apiKey?: string;
456
+ token?: string;
457
+ });
458
+ /** Use an API key (`jb_…`) for all requests. An agent-bound key authenticates AS that agent. */
459
+ setApiKey(apiKey: string): void;
460
+ /** Use an existing session JWT for all requests. */
461
+ setToken(token: string): void;
462
+ /** POST /api/auth/register — create a new account, stores JWT. */
463
+ register(username: string, password: string): Promise<void>;
464
+ /** POST /api/auth/token — login with credentials, stores JWT. */
465
+ login(username: string, password: string): Promise<void>;
466
+ get isAuthenticated(): boolean;
467
+ /** Which credential requests will carry. */
468
+ get authMode(): "apiKey" | "session" | "none";
469
+ private authHeaders;
470
+ /** Authenticated fetch with uniform error reporting. */
471
+ private request;
472
+ /**
473
+ * GET /api/projects — with a session: projects the user is a member of
474
+ * (plus org-admin-visible ones with role "org-admin"); with an agent key:
475
+ * the agent's assigned projects.
476
+ */
477
+ listProjects(): Promise<Project[]>;
478
+ /** POST /api/projects — create a new project (session only), returns it. */
479
+ createProject(name: string, description?: string, orgId?: string): Promise<Project>;
480
+ /**
481
+ * POST /api/me/agents — idempotent upsert of an agent hosted by the
482
+ * logged-in user, keyed by (org, lower(name)). Session only.
483
+ */
484
+ ensureAgent(input: EnsureAgentInput): Promise<AgentRecord>;
485
+ /** GET /api/me/agents — agents hosted by the logged-in user (with assignments). */
486
+ listMyAgents(): Promise<AgentRecord[]>;
487
+ /** POST /api/me/agents/:id/assignments — assign an agent to a project (idempotent). */
488
+ assignAgent(agentId: string, projectId: string): Promise<void>;
489
+ /** DELETE /api/me/agents/:id/assignments?projectId= — remove an assignment. */
490
+ unassignAgent(agentId: string, projectId: string): Promise<boolean>;
491
+ /** POST /api/me/agents/:id/keys — mint an agent-bound API key. The raw key is returned once. */
492
+ createAgentKey(agentId: string, name?: string): Promise<AgentApiKey>;
493
+ /** POST /api/agents/:id/heartbeat — refresh lastSeenAt (host session or the agent's own key). */
494
+ heartbeat(agentId: string): Promise<{
495
+ lastSeenAt: string;
496
+ }>;
497
+ /** POST /api/ably/token — get scoped Ably TokenRequest. */
498
+ getAblyToken(): Promise<object>;
499
+ /**
500
+ * POST /api/projects/{id}/messages — persist a message. This is the only
501
+ * write path for final messages: the server publishes the echo to Ably
502
+ * itself. Idempotent on `id` (201 on create, 200 if it already existed).
503
+ *
504
+ * Identity is derived server-side: in session mode pass `agentId` to post
505
+ * as that hosted agent; with an agent key it is implied.
506
+ *
507
+ * Retries once on network errors / 5xx (safe: ids are idempotent).
508
+ */
509
+ persistMessage(projectId: string, msg: PersistMessagePayload): Promise<ServerMessage>;
510
+ /** GET /api/projects/{id}/messages — fetch recent messages (oldest first). */
511
+ fetchMessages(projectId: string, limit?: number): Promise<ServerMessage[]>;
512
+ /** POST /api/projects/{id}/tasks — create a task. */
513
+ createTask(projectId: string, data: {
514
+ title: string;
515
+ description?: string;
516
+ priority?: string;
517
+ assignedAgentName?: string;
518
+ assignedAgentId?: string;
519
+ parentTaskId?: string;
520
+ sourceMessageId?: string;
521
+ createdByType?: "user" | "agent";
522
+ createdByName?: string;
523
+ createdByAgentId?: string;
524
+ }): Promise<Task>;
525
+ /** PATCH /api/tasks/{taskId} — update task fields. Returns the updated task. */
526
+ updateTask(taskId: string, updates: Partial<Pick<Task, "title" | "description" | "status" | "priority" | "assignedAgentName" | "assignedAgentId">>): Promise<Task>;
527
+ }
528
+
529
+ /**
530
+ * Provider interface for LLM backends.
531
+ * Implementations return an async generator that yields text chunks.
532
+ */
533
+ interface Provider {
534
+ generate(prompt: string, systemPrompt: string, conversationContext: string): AsyncGenerator<string, void, unknown>;
535
+ }
536
+ interface AnthropicProviderOptions {
537
+ /** Anthropic API key (sk-ant-...) */
538
+ apiKey: string;
539
+ /** Model ID (default: "claude-sonnet-4-6") */
540
+ model?: string;
541
+ /** Max tokens (default: 8192) */
542
+ maxTokens?: number;
543
+ }
544
+ interface OpenAIProviderOptions {
545
+ /** OpenAI API key (sk-...) */
546
+ apiKey: string;
547
+ /** Model ID (default: "gpt-4o") */
548
+ model?: string;
549
+ /** Max tokens (default: 8192) */
550
+ maxTokens?: number;
551
+ }
552
+ interface GoogleProviderOptions {
553
+ /** Google AI API key (AIza...) */
554
+ apiKey: string;
555
+ /** Model ID (default: "gemini-pro-latest" — Google's auto-updating alias) */
556
+ model?: string;
557
+ /** Max tokens (default: 8192) */
558
+ maxTokens?: number;
559
+ }
560
+ interface ClaudeCLIProviderOptions {
561
+ /** Working directory for Claude CLI (default: cwd) */
562
+ projectDir?: string;
563
+ /** Session ID for --resume (resumes a specific prior session) */
564
+ sessionId?: string;
565
+ /** If true and no sessionId, use --continue to resume last session in project dir */
566
+ continueSession?: boolean;
332
567
  }
333
568
 
334
569
  /**
335
570
  * Headless Jaibber agent.
336
571
  *
337
572
  * Connects to the Jaibber server via REST + Ably, subscribes to project
338
- * channels, handles @mention routing, streams responses, and dual-writes
339
- * to the server for persistence.
573
+ * channels, handles @mention routing and streams responses.
574
+ *
575
+ * Identity (0.4.0+): every agent is an `agents` row on the server.
576
+ * - Session credentials: logs in as the hosting user, upserts the agent record
577
+ * (`POST /api/me/agents`), assigns it to the joined projects, and posts
578
+ * replies with `agentId` so the server attributes them to the agent.
579
+ * - API key credentials: the agent-bound key IS the identity; the agent id is
580
+ * taken from the key's Ably clientId (`agent:{id}`) and projects are the
581
+ * agent's assignments.
582
+ *
583
+ * Final messages are POSTed to the server (which publishes the Ably echo);
584
+ * only `typing` and `chunk` events are published by the client. Replies are
585
+ * threaded under the message they answer (`parentMessageId`), which is how
586
+ * agent-to-agent chains are reconstructed for loop prevention.
340
587
  *
341
588
  * Usage:
342
589
  * ```ts
343
590
  * const agent = new JaibberAgent({ serverUrl, credentials, agentName });
591
+ * agent.useProvider("anthropic", { apiKey });
344
592
  * await agent.connect();
345
- * agent.onMessage(async (msg, ctx) => ctx.reply('Hello!'));
346
593
  * ```
347
594
  */
348
595
  declare class JaibberAgent extends EventEmitter {
@@ -352,19 +599,47 @@ declare class JaibberAgent extends EventEmitter {
352
599
  private messageHandler;
353
600
  private taskHandler;
354
601
  private provider;
602
+ private providerKind;
355
603
  private connected;
356
604
  private projects;
357
605
  private unsubscribers;
606
+ private heartbeatTimer;
607
+ private agentId;
608
+ private agentRecord;
358
609
  /** In-memory conversation history per project. */
359
610
  private history;
611
+ /** Recent messages per project (id → author/parent) for chain reconstruction. */
612
+ private messageIndex;
360
613
  /** Track in-flight responses to prevent double-handling. */
361
614
  private activeResponses;
362
615
  /** Session IDs per project for Claude --resume. */
363
616
  private sessionIds;
617
+ /** Messages we POSTed ourselves, keyed by id — for echo dedupe + own-reply history. */
618
+ private ownMessages;
619
+ /** `meta` hints waiting for their server echo. */
620
+ private pendingMeta;
621
+ /**
622
+ * Safety valve: unthreaded agent responses (no `parentMessageId`) seen per
623
+ * project since the last human message. Threaded chains are bounded by the
624
+ * `parentMessageId` walk; this catches agents that post without threading,
625
+ * which would otherwise look like a fresh depth-1 chain every time.
626
+ */
627
+ private unthreadedHops;
364
628
  constructor(config: AgentConfig);
365
- /** Authenticate, connect Ably, subscribe to project channels. */
629
+ /** The agent's server-side id (available after `connect()`). */
630
+ get id(): string | null;
631
+ /** The agent record returned by the server (session mode only). */
632
+ get record(): AgentRecord | null;
633
+ /** The underlying REST client (authenticated after `connect()`). */
634
+ get api(): JaibberClient;
635
+ /** Projects this agent has joined. */
636
+ get joinedProjects(): Project[];
637
+ /** Sender id used on client-published typing/chunk events. */
638
+ private get senderId();
639
+ private get maxDepth();
640
+ /** Authenticate, register/resolve the agent, connect Ably, subscribe to project channels. */
366
641
  connect(): Promise<void>;
367
- /** Leave presence, disconnect Ably. */
642
+ /** Stop heartbeats, leave presence, disconnect Ably. */
368
643
  disconnect(): Promise<void>;
369
644
  /** Register a handler for incoming messages. */
370
645
  onMessage(handler: MessageHandler): void;
@@ -375,6 +650,28 @@ declare class JaibberAgent extends EventEmitter {
375
650
  useProvider(name: "openai", options: OpenAIProviderOptions): void;
376
651
  useProvider(name: "google", options: GoogleProviderOptions): void;
377
652
  useProvider(name: "claude-cli", options?: ClaudeCLIProviderOptions): void;
653
+ /** Provider label stored on the agent record. */
654
+ private resolveProviderKind;
655
+ private startHeartbeat;
656
+ private stopHeartbeat;
657
+ private indexMessage;
658
+ /**
659
+ * Loop prevention for agent-to-agent chains. The server echo carries no
660
+ * chain metadata, so the chain is reconstructed from `parentMessageId`
661
+ * links: every agent response is posted as a reply to the message it
662
+ * answered. Returns the number of consecutive agent hops ending at
663
+ * `payload` (the depth) and the lowercased names of the agents in that run.
664
+ * Mirrors useAbly.ts agentChainFor().
665
+ */
666
+ private agentChainFor;
667
+ private rememberMeta;
668
+ private takeMeta;
669
+ private readonly tracker;
670
+ /**
671
+ * Add one of our own messages to history exactly once — whichever arrives
672
+ * first: the server's Ably echo or the POST response.
673
+ */
674
+ private recordOwnMessage;
378
675
  private handleIncomingMessage;
379
676
  /**
380
677
  * Should this agent respond to the message?
@@ -382,16 +679,28 @@ declare class JaibberAgent extends EventEmitter {
382
679
  */
383
680
  private shouldRespond;
384
681
  private respondToMessage;
682
+ /** Agent instructions, prefixed with the plan-mode directive when requested. */
683
+ private systemPromptFor;
684
+ /** Is a server control event addressed to this agent? */
685
+ private isControlForMe;
686
+ /**
687
+ * `agent-control` events are published by the server on project channels,
688
+ * e.g. `{action: "deregister", agentId, agentName}` when an agent is revoked
689
+ * via the API. Events for other agents are ignored.
690
+ */
691
+ private handleControlEvent;
385
692
  private handleTaskEvent;
386
693
  /** Pass stored session ID to ClaudeCLIProvider before each invocation. */
387
694
  private updateProviderSession;
388
695
  /** After response, capture the session ID from ClaudeCLIProvider if available. */
389
696
  private captureProviderSession;
697
+ /** Is this stored message one of this agent's own prior replies? */
698
+ private isOwnServerMessage;
390
699
  private loadHistory;
391
700
  private addToHistory;
392
701
  /**
393
702
  * Format conversation history for LLM context.
394
- * Matches useAbly.ts lines 77-84 format.
703
+ * Matches useAbly.ts format: `User: text` / `Assistant (Name): text`.
395
704
  */
396
705
  private getFormattedHistory;
397
706
  }
@@ -461,4 +770,18 @@ interface AgentTemplate {
461
770
  declare const AGENT_TEMPLATES: AgentTemplate[];
462
771
  declare function getTemplate(id: string): AgentTemplate | undefined;
463
772
 
464
- export { AGENT_TEMPLATES, type AblyMessage, type AgentConfig, type AgentTemplate, AnthropicProvider, type AnthropicProviderOptions, ClaudeCLIProvider, type ClaudeCLIProviderOptions, type ExecutionMode, GoogleProvider, type GoogleProviderOptions, type IncomingMessage, JaibberAgent, type MessageAttachment, MessageContext, type MessageHandler, OpenAIProvider, type OpenAIProviderOptions, type Project, type Provider, type Task, TaskContext, type TaskHandler, type TaskPriority, type TaskStatus, getTemplate };
773
+ /**
774
+ * Parse @mentions from message text.
775
+ * Returns lowercase agent names found after @ symbols.
776
+ * Supports multi-word names like "@Testing Agent".
777
+ *
778
+ * Port of src/lib/mentions.ts from the Jaibber frontend.
779
+ */
780
+ declare function parseMentions(text: string): string[];
781
+ /**
782
+ * Check whether a message @mentions a specific agent by name.
783
+ * Case-insensitive, handles multi-word agent names.
784
+ */
785
+ declare function mentionsAgent(text: string, agentName: string): boolean;
786
+
787
+ export { AGENT_TEMPLATES, type AblyMessage, type AgentApiKey, type AgentConfig, type AgentControlEvent, type AgentCredentials, type AgentKind, type AgentPresenceData, type AgentProvider, type AgentRecord, type AgentTemplate, AnthropicProvider, type AnthropicProviderOptions, ClaudeCLIProvider, type ClaudeCLIProviderOptions, type EnsureAgentInput, type ExecutionMode, type GlobalPresenceData, GoogleProvider, type GoogleProviderOptions, type IncomingMessage, JaibberAgent, JaibberClient, type MessageAttachment, MessageContext, type MessageHandler, OpenAIProvider, type OpenAIProviderOptions, type OwnMessageTracker, type PersistMessagePayload, type Project, type Provider, type ReplyOptions, type ServerMessage, type Task, TaskContext, type TaskEvent, type TaskHandler, type TaskPriority, type TaskStatus, getTemplate, mentionsAgent, parseMentions };