@jaibber/sdk 0.3.8 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -1,177 +1,191 @@
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 | Promise<void>, onTask: (data: TaskEvent) => void | Promise<void>, onControl?: (data: AgentControlEvent) => void | Promise<void>, onError?: (err: unknown, event: string) => 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?;
123
+ /** Set by `stream()` when its generator threw. */
124
+ private streamError;
148
125
  constructor(opts: {
149
126
  projectId: string;
150
127
  channelName: string;
151
128
  conversationHistory: string;
152
129
  ablyManager: AblyManager;
153
- userId: string;
130
+ /** Sender id for client-published events (userId, or `agent:{id}` in API-key mode). */
131
+ from: string;
132
+ agentId: string;
154
133
  agentName: string;
155
134
  client: JaibberClient;
135
+ incomingMessageId?: string;
156
136
  incomingDepth: number;
157
137
  incomingChain: string[];
158
138
  chunkBatchMs: number;
139
+ tracker?: OwnMessageTracker;
159
140
  });
160
- /** One-shot reply: publishes typing → response in sequence. */
161
- reply(text: string): Promise<void>;
141
+ /** Agent-to-agent hop count this reply will carry (informational). */
142
+ get depth(): number;
143
+ /** Agents that have already responded in this chain, including this one. */
144
+ get chain(): string[];
145
+ /**
146
+ * Why `stream()` failed, if it did: the error its generator threw;
147
+ * `undefined` otherwise. The failure has already been stored under this
148
+ * reply's id as an `error` bubble, and `stream()` resolved with the
149
+ * partial text.
150
+ */
151
+ get error(): unknown;
152
+ /**
153
+ * One-shot reply: publishes `typing`, then POSTs the final message.
154
+ * Throws if the server rejects it (remote bubbles are closed first — see
155
+ * `deliver`).
156
+ */
157
+ reply(text: string, opts?: ReplyOptions): Promise<ServerMessage>;
158
+ /** Replies thread under the answered message unless overridden. */
159
+ private parentFor;
162
160
  /**
163
161
  * Streaming reply: consumes an async generator, batches chunks to Ably
164
- * every chunkBatchMs (default 200ms), then publishes the final response.
162
+ * every chunkBatchMs (default 200ms), then POSTs the final message.
163
+ * Resolves with the full response text.
165
164
  *
166
- * Mirrors useAbly.ts lines 86-102 chunk batching pattern.
165
+ * A provider error (the generator throwing) does not reject: the failure
166
+ * is stored under the same id as an `error` bubble, exposed as `error`,
167
+ * and the text streamed so far is returned. Only a delivery failure — the
168
+ * server rejecting the final POST after the retry — rejects, and remote
169
+ * bubbles are closed before it does.
170
+ *
171
+ * Mirrors useAbly.ts chunk batching pattern.
167
172
  */
168
- stream(generator: () => AsyncGenerator<string, void, unknown>): Promise<void>;
173
+ stream(generator: () => AsyncGenerator<string, void, unknown>, opts?: ReplyOptions): Promise<string>;
169
174
  private publishTyping;
170
175
  private publishChunk;
171
- private publishResponse;
172
- private publishError;
173
- /** Fire-and-forget persist to server. */
174
- private persistAsync;
176
+ /**
177
+ * POST this reply's final message. If the server rejects it (after
178
+ * `persistMessage`'s single retry), every other client is stuck on the
179
+ * streaming bubble our `typing`/`chunk` events opened — the server echo
180
+ * that would close it is never coming. Close them with a client-published
181
+ * `error` event under the same id (ephemeral: the server does not persist
182
+ * it, acceptable for a last resort), then rethrow.
183
+ */
184
+ private deliver;
185
+ /** Same wire shape as the desktop's delivery-failure fallback (useAbly.ts deliver()). */
186
+ private publishDeliveryFailure;
187
+ /** POST the final message. Throws if the server rejects it. */
188
+ private persist;
175
189
  }
176
190
  /**
177
191
  * Context passed to task handlers.
@@ -182,59 +196,156 @@ declare class TaskContext {
182
196
  readonly task: Task;
183
197
  readonly projectId: string;
184
198
  readonly conversationHistory: string;
185
- private ablyManager;
186
- private channelName;
187
- private userId;
188
- private agentName;
199
+ readonly agentId: string;
200
+ readonly agentName: string;
189
201
  private client;
202
+ private tracker?;
190
203
  constructor(opts: {
191
204
  task: Task;
192
205
  projectId: string;
193
206
  channelName: string;
194
207
  conversationHistory: string;
195
208
  ablyManager: AblyManager;
196
- userId: string;
209
+ from: string;
210
+ agentId: string;
197
211
  agentName: string;
198
212
  client: JaibberClient;
213
+ tracker?: OwnMessageTracker;
199
214
  });
200
- /** Mark task as completed, optionally publishing a response message. */
215
+ /** Mark task as completed, optionally posting a response message. */
201
216
  complete(resultText?: string): Promise<void>;
202
- /** Mark task as failed, optionally publishing an error message. */
217
+ /** Mark task as failed, optionally posting an error message. */
203
218
  fail(errorText?: string): Promise<void>;
204
219
  /**
205
220
  * Create a follow-up task assigned to another agent.
206
- * Automatically sets parentTaskId to the current task's ID.
221
+ * Automatically sets parentTaskId to the current task's ID and attributes
222
+ * creation to this agent.
207
223
  */
208
224
  createFollowUpTask(data: {
209
225
  title: string;
210
226
  description?: string;
211
227
  priority?: "low" | "medium" | "high" | "urgent";
212
228
  assignedAgentName?: string;
229
+ assignedAgentId?: string;
213
230
  }): Promise<Task>;
214
- /** Send a chat message (for progress updates). */
215
- sendMessage(text: string): Promise<void>;
231
+ /**
232
+ * Post a chat message (for progress updates). Returns the stored message.
233
+ * `type` defaults to "response"; use "message" for notices that must never
234
+ * trigger other agents (agent-to-agent chaining only flows through responses).
235
+ */
236
+ sendMessage(text: string, opts?: ReplyOptions & {
237
+ type?: PostedType;
238
+ }): Promise<ServerMessage>;
216
239
  }
217
240
 
218
241
  type ExecutionMode = "auto" | "plan";
242
+ /** Server-side provider label stored on the agent record. */
243
+ type AgentProvider = "claude" | "codex" | "gemini" | "openai" | "google" | "openclaw" | "custom";
244
+ /** Hosted agent kinds the SDK can register as. */
245
+ type AgentKind = "desktop" | "sdk";
246
+ /** An `agents` row as returned by `/api/me/agents`. */
247
+ interface AgentRecord {
248
+ id: string;
249
+ orgId: string | null;
250
+ name: string;
251
+ handle: string | null;
252
+ kind: string;
253
+ provider: AgentProvider | string;
254
+ instructions: string | null;
255
+ machineName: string | null;
256
+ status: "active" | "paused" | "revoked" | string;
257
+ trustTier: string;
258
+ /** Present on `GET /api/me/agents`. */
259
+ assignments?: Array<{
260
+ projectId: string;
261
+ }>;
262
+ }
263
+ /** Input for `JaibberClient.ensureAgent()` (`POST /api/me/agents`). */
264
+ interface EnsureAgentInput {
265
+ name: string;
266
+ instructions?: string;
267
+ provider?: AgentProvider;
268
+ kind: AgentKind;
269
+ machineName?: string;
270
+ /** Also assign the agent to this project in the same call. */
271
+ projectId?: string;
272
+ /**
273
+ * Organization to register the agent under. Optional — the server
274
+ * defaults to the caller's personal org. Only sent when set.
275
+ */
276
+ orgId?: string;
277
+ }
278
+ /** A freshly minted agent-bound API key. The raw `key` is returned once. */
279
+ interface AgentApiKey {
280
+ id: string;
281
+ key: string;
282
+ prefix: string;
283
+ }
284
+ /** What `GET /api/me` reports for an agent-bound API key. */
285
+ interface AgentIdentity {
286
+ type: "agent";
287
+ agentId: string;
288
+ name: string;
289
+ handle: string | null;
290
+ kind?: string | null;
291
+ trustTier?: string | null;
292
+ hostUserId?: string | null;
293
+ org: {
294
+ id: string;
295
+ slug: string;
296
+ name: string;
297
+ } | null;
298
+ keyId?: string;
299
+ scopes?: string[];
300
+ }
301
+ /** `GET /api/me` — who the current credential is. */
302
+ type WhoAmI = {
303
+ type: "user";
304
+ userId: string;
305
+ username: string;
306
+ email?: string | null;
307
+ } | AgentIdentity | {
308
+ type: "apiKey";
309
+ keyId: string;
310
+ scopes?: string[];
311
+ org: {
312
+ id: string;
313
+ slug: string;
314
+ name: string;
315
+ } | null;
316
+ };
219
317
  interface AblyMessage {
318
+ /** Sender userId (server-derived on final events; `api:{keyId}` for key senders). */
220
319
  from: string;
221
320
  fromUsername: string;
222
321
  projectId: string;
223
322
  text: string;
224
323
  messageId: string;
225
- type: "message" | "response" | "typing" | "done" | "error" | "chunk" | "task-created" | "task-updated" | "task-deleted" | "deregister";
324
+ type: "message" | "response" | "typing" | "error" | "chunk" | "meta" | "task-created" | "task-updated" | "task-deleted";
226
325
  responseId?: string;
227
326
  agentName?: string;
327
+ /** Server agent id on agent-attributed final events. */
328
+ agentId?: string;
228
329
  mentions?: string[];
330
+ /** `meta` hint (and legacy `message`) so agents know which mode to use. */
229
331
  executionMode?: ExecutionMode;
332
+ /**
333
+ * True if this message is attributed to an agent (not a human). Chains are
334
+ * reconstructed from `parentMessageId` links — there is no depth on the wire.
335
+ */
230
336
  isAgentMessage?: boolean;
231
- responseDepth?: number;
232
- respondingChain?: string[];
337
+ /** Legacy client-published task notifications — never trigger agent responses. */
233
338
  isTaskNotification?: boolean;
339
+ /** File attachments (`meta` hint and legacy `message`). */
234
340
  attachments?: MessageAttachment[];
341
+ /** Reply threading; agent responses reply to the message they answered. */
235
342
  parentMessageId?: string;
343
+ /** Server timestamp on server-published final events. */
344
+ createdAt?: string;
236
345
  /** Injected by AblyManager — not on the wire. Used for connection-level self-skip. */
237
346
  _connectionId?: string;
347
+ /** Injected by AblyManager — not on the wire. Authenticated Ably clientId of a client publisher. */
348
+ _clientId?: string;
238
349
  }
239
350
  type TaskStatus = "submitted" | "working" | "input-required" | "completed" | "failed" | "cancelled";
240
351
  type TaskPriority = "low" | "medium" | "high" | "urgent";
@@ -246,9 +357,12 @@ interface Task {
246
357
  status: TaskStatus;
247
358
  priority: TaskPriority;
248
359
  assignedAgentName: string | null;
360
+ /** Id of the assigned agent (name column kept for display/compat). */
361
+ assignedAgentId: string | null;
249
362
  createdBy: string;
250
363
  createdByType: "user" | "agent";
251
364
  createdByName: string;
365
+ createdByAgentId: string | null;
252
366
  sourceMessageId: string | null;
253
367
  parentTaskId: string | null;
254
368
  createdAt: string;
@@ -265,7 +379,9 @@ interface Project {
265
379
  id: string;
266
380
  name: string;
267
381
  description: string | null;
382
+ orgId: string | null;
268
383
  ablyChannelName: string;
384
+ /** "admin" | "member" | "org-admin" for sessions; assignment role for agent keys. */
269
385
  role: string;
270
386
  }
271
387
  interface IncomingMessage {
@@ -275,74 +391,278 @@ interface IncomingMessage {
275
391
  fromUsername: string;
276
392
  text: string;
277
393
  type: string;
394
+ /**
395
+ * Agent-to-agent hop count ending at this message (0 for human messages),
396
+ * reconstructed from `parentMessageId` links.
397
+ */
278
398
  responseDepth: number;
399
+ /** Lowercased names of the agents in that run (empty for human messages). */
279
400
  respondingChain: string[];
280
401
  executionMode?: ExecutionMode;
281
402
  isAgentMessage?: boolean;
403
+ /** Set when the sender is a registered agent. */
404
+ agentId?: string;
405
+ agentName?: string;
406
+ mentions?: string[];
407
+ parentMessageId?: string;
282
408
  attachments?: MessageAttachment[];
409
+ createdAt?: string;
283
410
  }
284
411
  interface TaskEvent {
285
412
  type: "task-created" | "task-updated" | "task-deleted";
286
413
  task: Task;
287
414
  projectId: string;
288
415
  }
416
+ interface AgentControlEvent {
417
+ /** "deregister" when the agent was revoked via the API. */
418
+ action: "deregister" | string;
419
+ agentId?: string;
420
+ agentName?: string;
421
+ }
422
+ /**
423
+ * How the agent authenticates.
424
+ * - `{ username, password }`: log in as the hosting user, then register/upsert
425
+ * the agent record (`POST /api/me/agents`) and post as that agent.
426
+ * - `{ apiKey }`: an agent-bound key (`jb_…`). The key IS the identity — no
427
+ * login, no registration; projects are the agent's assignments.
428
+ */
429
+ type AgentCredentials = {
430
+ username: string;
431
+ password: string;
432
+ } | {
433
+ apiKey: string;
434
+ };
289
435
  interface AgentConfig {
290
436
  /** Jaibber server URL (e.g. "https://api.jaibber.com") */
291
437
  serverUrl: string;
292
- /** Login credentials for the agent's Jaibber account */
293
- credentials: {
294
- username: string;
295
- password: string;
296
- };
297
- /** Agent display name (used for @mention routing and presence) */
438
+ /** Session credentials or an agent-bound API key. */
439
+ credentials: AgentCredentials;
440
+ /**
441
+ * Agent display name (used for @mention routing and presence). In API-key
442
+ * mode the key's agent name takes precedence if it differs (`GET /api/me`).
443
+ */
298
444
  agentName: string;
299
- /** System prompt prepended to every LLM call */
445
+ /** System prompt prepended to every LLM call (also stored on the agent record) */
300
446
  agentInstructions?: string;
301
447
  /** Machine identifier shown in presence */
302
448
  machineName?: string;
303
- /** Specific project IDs to join. Omit to join all user's projects. */
449
+ /** Specific project IDs to join. Omit to join all member/assigned projects. */
304
450
  projectIds?: string[];
451
+ /**
452
+ * Provider label stored on the agent record. Defaults to the backend chosen
453
+ * with `useProvider()` ("claude" | "openai" | "google"), else "custom".
454
+ */
455
+ provider?: AgentProvider;
456
+ /** Organization to register the agent under (session mode). Default: personal org. */
457
+ orgId?: string;
458
+ /**
459
+ * The agent's id. Resolved during `connect()`: from `POST /api/me/agents`
460
+ * (session mode) or from `GET /api/me` (API-key mode; servers without that
461
+ * endpoint fall back to the key's Ably clientId). May be pre-supplied in
462
+ * API-key mode, but the key's own identity wins if they differ.
463
+ */
464
+ agentId?: string;
305
465
  /** Max depth for agent-to-agent chains (default: 3) */
306
466
  maxResponseDepth?: number;
307
467
  /** Chunk batching interval in ms (default: 200) */
308
468
  chunkBatchMs?: number;
309
469
  /** Number of recent messages for conversation context (default: 20) */
310
470
  contextWindowSize?: number;
471
+ /** Heartbeat interval in ms (default: 120_000) */
472
+ heartbeatMs?: number;
473
+ /**
474
+ * When the server revokes this agent (`agent-control` event with
475
+ * `action: "deregister"`), the agent disconnects and, by default, exits the
476
+ * process. Set false to only disconnect and emit "deregistered".
477
+ */
478
+ exitOnDeregister?: boolean;
311
479
  }
312
480
  type MessageHandler = (message: IncomingMessage, context: MessageContext) => Promise<void>;
313
481
  type TaskHandler = (task: Task, context: TaskContext) => Promise<void>;
314
482
  interface ServerMessage {
315
483
  id: string;
316
484
  projectId: string;
317
- senderId: string;
485
+ senderId?: string;
318
486
  senderType: "user" | "agent" | "api";
319
487
  senderName: string;
320
- type: "message" | "response" | "error";
488
+ /** Set exactly when senderType === "agent". */
489
+ senderAgentId: string | null;
490
+ type: "message" | "response" | "error" | "system";
321
491
  text: string;
322
- parentMessageId?: string;
492
+ parentMessageId: string | null;
493
+ metadata?: Record<string, unknown> | null;
323
494
  createdAt: string;
324
495
  }
325
496
  interface PersistMessagePayload {
326
- id: string;
327
- senderType: "agent";
328
- senderName: string;
329
- type: "message" | "response" | "error";
497
+ /** Client-generated id (8–64 chars of [A-Za-z0-9_-]) used to dedupe the Ably echo. */
498
+ id?: string;
499
+ /** Post as this hosted agent. Required in session mode, ignored for agent keys. */
500
+ agentId?: string;
501
+ type?: "message" | "response" | "error";
330
502
  text: string;
331
503
  parentMessageId?: string;
504
+ mentions?: string[];
505
+ }
506
+
507
+ /**
508
+ * REST API client wrapping the Jaibber server endpoints.
509
+ *
510
+ * Authenticates either with a session JWT (`login()` / `register()` /
511
+ * `setToken()`) or with an agent-bound API key (`jb_…`). `authHeaders()` is
512
+ * the single choke point: an API key is sent as `X-API-Key`, a session as
513
+ * `Authorization: Bearer`. When both are configured the API key wins.
514
+ */
515
+ declare class JaibberClient {
516
+ private serverUrl;
517
+ private jwt;
518
+ private apiKey;
519
+ userId: string | null;
520
+ username: string | null;
521
+ constructor(serverUrl: string, opts?: {
522
+ apiKey?: string;
523
+ token?: string;
524
+ });
525
+ /** Use an API key (`jb_…`) for all requests. An agent-bound key authenticates AS that agent. */
526
+ setApiKey(apiKey: string): void;
527
+ /** Use an existing session JWT for all requests. */
528
+ setToken(token: string): void;
529
+ /** POST /api/auth/register — create a new account, stores JWT. */
530
+ register(username: string, password: string): Promise<void>;
531
+ /** POST /api/auth/token — login with credentials, stores JWT. */
532
+ login(username: string, password: string): Promise<void>;
533
+ get isAuthenticated(): boolean;
534
+ /** Which credential requests will carry. */
535
+ get authMode(): "apiKey" | "session" | "none";
536
+ private authHeaders;
537
+ /** Authenticated fetch with uniform error reporting. */
538
+ private request;
539
+ /**
540
+ * GET /api/me — who the current credential is: the user (session), the
541
+ * agent (agent-bound key) or the org (org key). Resolves `null` when the
542
+ * server predates the endpoint (404).
543
+ */
544
+ whoAmI(): Promise<WhoAmI | null>;
545
+ /**
546
+ * GET /api/projects — with a session: projects the user is a member of
547
+ * (plus org-admin-visible ones with role "org-admin"); with an agent key:
548
+ * the agent's assigned projects.
549
+ */
550
+ listProjects(): Promise<Project[]>;
551
+ /** POST /api/projects — create a new project (session only), returns it. */
552
+ createProject(name: string, description?: string, orgId?: string): Promise<Project>;
553
+ /**
554
+ * POST /api/me/agents — idempotent upsert of an agent hosted by the
555
+ * logged-in user, keyed by (org, lower(name)). Session only.
556
+ */
557
+ ensureAgent(input: EnsureAgentInput): Promise<AgentRecord>;
558
+ /** GET /api/me/agents — agents hosted by the logged-in user (with assignments). */
559
+ listMyAgents(): Promise<AgentRecord[]>;
560
+ /** POST /api/me/agents/:id/assignments — assign an agent to a project (idempotent). */
561
+ assignAgent(agentId: string, projectId: string): Promise<void>;
562
+ /** DELETE /api/me/agents/:id/assignments?projectId= — remove an assignment. */
563
+ unassignAgent(agentId: string, projectId: string): Promise<boolean>;
564
+ /** POST /api/me/agents/:id/keys — mint an agent-bound API key. The raw key is returned once. */
565
+ createAgentKey(agentId: string, name?: string): Promise<AgentApiKey>;
566
+ /** POST /api/agents/:id/heartbeat — refresh lastSeenAt (host session or the agent's own key). */
567
+ heartbeat(agentId: string): Promise<{
568
+ lastSeenAt: string;
569
+ }>;
570
+ /** POST /api/ably/token — get scoped Ably TokenRequest. */
571
+ getAblyToken(): Promise<object>;
572
+ /**
573
+ * POST /api/projects/{id}/messages — persist a message. This is the only
574
+ * write path for final messages: the server publishes the echo to Ably
575
+ * itself. Idempotent on `id` (201 on create, 200 if it already existed).
576
+ *
577
+ * Identity is derived server-side: in session mode pass `agentId` to post
578
+ * as that hosted agent; with an agent key it is implied.
579
+ *
580
+ * Retries once on network errors / 5xx (safe: ids are idempotent).
581
+ */
582
+ persistMessage(projectId: string, msg: PersistMessagePayload): Promise<ServerMessage>;
583
+ /** GET /api/projects/{id}/messages — fetch recent messages (oldest first). */
584
+ fetchMessages(projectId: string, limit?: number): Promise<ServerMessage[]>;
585
+ /** POST /api/projects/{id}/tasks — create a task. */
586
+ createTask(projectId: string, data: {
587
+ title: string;
588
+ description?: string;
589
+ priority?: string;
590
+ assignedAgentName?: string;
591
+ assignedAgentId?: string;
592
+ parentTaskId?: string;
593
+ sourceMessageId?: string;
594
+ createdByType?: "user" | "agent";
595
+ createdByName?: string;
596
+ createdByAgentId?: string;
597
+ }): Promise<Task>;
598
+ /** PATCH /api/tasks/{taskId} — update task fields. Returns the updated task. */
599
+ updateTask(taskId: string, updates: Partial<Pick<Task, "title" | "description" | "status" | "priority" | "assignedAgentName" | "assignedAgentId">>): Promise<Task>;
600
+ }
601
+
602
+ /**
603
+ * Provider interface for LLM backends.
604
+ * Implementations return an async generator that yields text chunks.
605
+ */
606
+ interface Provider {
607
+ generate(prompt: string, systemPrompt: string, conversationContext: string): AsyncGenerator<string, void, unknown>;
608
+ }
609
+ interface AnthropicProviderOptions {
610
+ /** Anthropic API key (sk-ant-...) */
611
+ apiKey: string;
612
+ /** Model ID (default: "claude-sonnet-5"; e.g. "claude-opus-5" for the most capable tier) */
613
+ model?: string;
614
+ /** Max tokens (default: 8192) */
615
+ maxTokens?: number;
616
+ }
617
+ interface OpenAIProviderOptions {
618
+ /** OpenAI API key (sk-...) */
619
+ apiKey: string;
620
+ /** Model ID (default: "gpt-4o") */
621
+ model?: string;
622
+ /** Max tokens (default: 8192) */
623
+ maxTokens?: number;
624
+ }
625
+ interface GoogleProviderOptions {
626
+ /** Google AI API key (AIza...) */
627
+ apiKey: string;
628
+ /** Model ID (default: "gemini-pro-latest" — Google's auto-updating alias) */
629
+ model?: string;
630
+ /** Max tokens (default: 8192) */
631
+ maxTokens?: number;
632
+ }
633
+ interface ClaudeCLIProviderOptions {
634
+ /** Working directory for Claude CLI (default: cwd) */
635
+ projectDir?: string;
636
+ /** Session ID for --resume (resumes a specific prior session) */
637
+ sessionId?: string;
638
+ /** If true and no sessionId, use --continue to resume last session in project dir */
639
+ continueSession?: boolean;
332
640
  }
333
641
 
334
642
  /**
335
643
  * Headless Jaibber agent.
336
644
  *
337
645
  * 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.
646
+ * channels, handles @mention routing and streams responses.
647
+ *
648
+ * Identity (0.4.0+): every agent is an `agents` row on the server.
649
+ * - Session credentials: logs in as the hosting user, upserts the agent record
650
+ * (`POST /api/me/agents`), assigns it to the joined projects, and posts
651
+ * replies with `agentId` so the server attributes them to the agent.
652
+ * - API key credentials: the agent-bound key IS the identity; the agent id
653
+ * and name come from `GET /api/me` (older servers: the key's Ably clientId
654
+ * `agent:{id}`) and projects are the agent's assignments.
655
+ *
656
+ * Final messages are POSTed to the server (which publishes the Ably echo);
657
+ * only `typing` and `chunk` events are published by the client. Replies are
658
+ * threaded under the message they answer (`parentMessageId`), which is how
659
+ * agent-to-agent chains are reconstructed for loop prevention.
340
660
  *
341
661
  * Usage:
342
662
  * ```ts
343
663
  * const agent = new JaibberAgent({ serverUrl, credentials, agentName });
664
+ * agent.useProvider("anthropic", { apiKey });
344
665
  * await agent.connect();
345
- * agent.onMessage(async (msg, ctx) => ctx.reply('Hello!'));
346
666
  * ```
347
667
  */
348
668
  declare class JaibberAgent extends EventEmitter {
@@ -352,19 +672,65 @@ declare class JaibberAgent extends EventEmitter {
352
672
  private messageHandler;
353
673
  private taskHandler;
354
674
  private provider;
675
+ private providerKind;
355
676
  private connected;
356
677
  private projects;
357
678
  private unsubscribers;
679
+ private heartbeatTimer;
680
+ private agentId;
681
+ private agentRecord;
682
+ private keyIdentity;
358
683
  /** In-memory conversation history per project. */
359
684
  private history;
685
+ /** Recent messages per project (id → author/parent) for chain reconstruction. */
686
+ private messageIndex;
360
687
  /** Track in-flight responses to prevent double-handling. */
361
688
  private activeResponses;
362
689
  /** Session IDs per project for Claude --resume. */
363
690
  private sessionIds;
691
+ /** Messages we POSTed ourselves, keyed by id — for echo dedupe + own-reply history. */
692
+ private ownMessages;
693
+ /** `meta` hints waiting for their server echo. */
694
+ private pendingMeta;
695
+ /**
696
+ * Safety valve: unthreaded agent responses (no `parentMessageId`) seen per
697
+ * project since the last human message. Threaded chains are bounded by the
698
+ * `parentMessageId` walk; this catches agents that post without threading,
699
+ * which would otherwise look like a fresh depth-1 chain every time.
700
+ */
701
+ private unthreadedHops;
364
702
  constructor(config: AgentConfig);
365
- /** Authenticate, connect Ably, subscribe to project channels. */
703
+ /**
704
+ * Default `"error"` listener, registered by the constructor: logs the error
705
+ * and keeps the process alive. To handle errors yourself without the log,
706
+ * remove it: `agent.off("error", JaibberAgent.defaultErrorListener)`.
707
+ */
708
+ static readonly defaultErrorListener: (err: unknown) => void;
709
+ /** Emit `"error"` without ever throwing, even if every listener was removed. */
710
+ private emitError;
711
+ /** The agent's server-side id (available after `connect()`). */
712
+ get id(): string | null;
713
+ /** The agent record returned by the server (session mode only). */
714
+ get record(): AgentRecord | null;
715
+ /** The key's agent identity from `GET /api/me` (API-key mode, on servers that have it). */
716
+ get identity(): AgentIdentity | null;
717
+ /** The underlying REST client (authenticated after `connect()`). */
718
+ get api(): JaibberClient;
719
+ /** Projects this agent has joined. */
720
+ get joinedProjects(): Project[];
721
+ /** Sender id used on client-published typing/chunk events. */
722
+ private get senderId();
723
+ private get maxDepth();
724
+ /** Authenticate, register/resolve the agent, connect Ably, subscribe to project channels. */
366
725
  connect(): Promise<void>;
367
- /** Leave presence, disconnect Ably. */
726
+ /**
727
+ * API-key mode: ask the server who the key is (`GET /api/me`) so the agent
728
+ * id and name are known before Ably connects. Servers that predate the
729
+ * endpoint answer 404; the id is then read from the Ably token's clientId
730
+ * (`agent:{id}`) once connected, as in 0.4.0.
731
+ */
732
+ private resolveKeyIdentity;
733
+ /** Stop heartbeats, leave presence, disconnect Ably. */
368
734
  disconnect(): Promise<void>;
369
735
  /** Register a handler for incoming messages. */
370
736
  onMessage(handler: MessageHandler): void;
@@ -375,6 +741,28 @@ declare class JaibberAgent extends EventEmitter {
375
741
  useProvider(name: "openai", options: OpenAIProviderOptions): void;
376
742
  useProvider(name: "google", options: GoogleProviderOptions): void;
377
743
  useProvider(name: "claude-cli", options?: ClaudeCLIProviderOptions): void;
744
+ /** Provider label stored on the agent record. */
745
+ private resolveProviderKind;
746
+ private startHeartbeat;
747
+ private stopHeartbeat;
748
+ private indexMessage;
749
+ /**
750
+ * Loop prevention for agent-to-agent chains. The server echo carries no
751
+ * chain metadata, so the chain is reconstructed from `parentMessageId`
752
+ * links: every agent response is posted as a reply to the message it
753
+ * answered. Returns the number of consecutive agent hops ending at
754
+ * `payload` (the depth) and the lowercased names of the agents in that run.
755
+ * Mirrors useAbly.ts agentChainFor().
756
+ */
757
+ private agentChainFor;
758
+ private rememberMeta;
759
+ private takeMeta;
760
+ private readonly tracker;
761
+ /**
762
+ * Add one of our own messages to history exactly once — whichever arrives
763
+ * first: the server's Ably echo or the POST response.
764
+ */
765
+ private recordOwnMessage;
378
766
  private handleIncomingMessage;
379
767
  /**
380
768
  * Should this agent respond to the message?
@@ -382,16 +770,28 @@ declare class JaibberAgent extends EventEmitter {
382
770
  */
383
771
  private shouldRespond;
384
772
  private respondToMessage;
773
+ /** Agent instructions, prefixed with the plan-mode directive when requested. */
774
+ private systemPromptFor;
775
+ /** Is a server control event addressed to this agent? */
776
+ private isControlForMe;
777
+ /**
778
+ * `agent-control` events are published by the server on project channels,
779
+ * e.g. `{action: "deregister", agentId, agentName}` when an agent is revoked
780
+ * via the API. Events for other agents are ignored.
781
+ */
782
+ private handleControlEvent;
385
783
  private handleTaskEvent;
386
784
  /** Pass stored session ID to ClaudeCLIProvider before each invocation. */
387
785
  private updateProviderSession;
388
786
  /** After response, capture the session ID from ClaudeCLIProvider if available. */
389
787
  private captureProviderSession;
788
+ /** Is this stored message one of this agent's own prior replies? */
789
+ private isOwnServerMessage;
390
790
  private loadHistory;
391
791
  private addToHistory;
392
792
  /**
393
793
  * Format conversation history for LLM context.
394
- * Matches useAbly.ts lines 77-84 format.
794
+ * Matches useAbly.ts format: `User: text` / `Assistant (Name): text`.
395
795
  */
396
796
  private getFormattedHistory;
397
797
  }
@@ -461,4 +861,18 @@ interface AgentTemplate {
461
861
  declare const AGENT_TEMPLATES: AgentTemplate[];
462
862
  declare function getTemplate(id: string): AgentTemplate | undefined;
463
863
 
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 };
864
+ /**
865
+ * Parse @mentions from message text.
866
+ * Returns lowercase agent names found after @ symbols.
867
+ * Supports multi-word names like "@Testing Agent".
868
+ *
869
+ * Port of src/lib/mentions.ts from the Jaibber frontend.
870
+ */
871
+ declare function parseMentions(text: string): string[];
872
+ /**
873
+ * Check whether a message @mentions a specific agent by name.
874
+ * Case-insensitive, handles multi-word agent names.
875
+ */
876
+ declare function mentionsAgent(text: string, agentName: string): boolean;
877
+
878
+ export { AGENT_TEMPLATES, type AblyMessage, type AgentApiKey, type AgentConfig, type AgentControlEvent, type AgentCredentials, type AgentIdentity, 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, type WhoAmI, getTemplate, mentionsAgent, parseMentions };