@jaibber/sdk 0.1.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.
@@ -0,0 +1,348 @@
1
+ import { EventEmitter } from 'events';
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
+
19
+ /**
20
+ * REST API client wrapping the Jaibber server endpoints.
21
+ * Handles JWT auth (login), project listing, message persistence,
22
+ * task updates, and Ably token requests.
23
+ */
24
+ declare class JaibberClient {
25
+ private serverUrl;
26
+ private jwt;
27
+ userId: string | null;
28
+ username: string | null;
29
+ constructor(serverUrl: string);
30
+ /** POST /api/auth/token — login with credentials, stores JWT. */
31
+ login(username: string, password: string): Promise<void>;
32
+ get isAuthenticated(): boolean;
33
+ private authHeaders;
34
+ /** GET /api/projects — list all projects user is member of. */
35
+ listProjects(): Promise<Project[]>;
36
+ /** POST /api/ably/token — get scoped Ably TokenRequest. */
37
+ getAblyToken(): Promise<object>;
38
+ /**
39
+ * POST /api/projects/{id}/messages — persist a message (idempotent).
40
+ * Passing a client-generated `id` makes the server skip Ably re-publish.
41
+ */
42
+ persistMessage(projectId: string, msg: PersistMessagePayload): Promise<void>;
43
+ /** GET /api/projects/{id}/messages — fetch recent messages. */
44
+ fetchMessages(projectId: string, limit?: number): Promise<ServerMessage[]>;
45
+ /** PATCH /api/tasks/{taskId} — update task fields. */
46
+ updateTask(taskId: string, updates: Partial<Task>): Promise<void>;
47
+ }
48
+
49
+ /** Presence data entered on each project channel. */
50
+ interface AgentPresenceData {
51
+ userId: string;
52
+ username: string;
53
+ isAgent: boolean;
54
+ agentName: string;
55
+ agentInstructions?: string;
56
+ agents?: Array<{
57
+ agentName: string;
58
+ agentInstructions?: string;
59
+ }>;
60
+ machineName?: string;
61
+ }
62
+ /**
63
+ * Manages the Ably Realtime connection, channel subscriptions, and presence.
64
+ * Node.js equivalent of the frontend's src/lib/ably.ts + useAbly.ts subscription logic.
65
+ */
66
+ declare class AblyManager {
67
+ private client;
68
+ private userId;
69
+ private username;
70
+ private ably;
71
+ private channels;
72
+ private presenceChannel;
73
+ constructor(client: JaibberClient, userId: string, username: string);
74
+ /** Create Ably Realtime client with token auth callback. */
75
+ connect(): Promise<void>;
76
+ /** Enter global presence channel (jaibber:presence). */
77
+ enterGlobalPresence(projectIds: string[]): Promise<void>;
78
+ /**
79
+ * Subscribe to a project channel and enter per-project presence.
80
+ * Returns an unsubscribe function.
81
+ */
82
+ subscribeToProject(project: Project, presenceData: AgentPresenceData, onMessage: (msg: AblyMessage) => void, onTask: (data: TaskEvent) => void): Promise<() => void>;
83
+ /** Publish a message on a project channel. */
84
+ publish(channelName: string, eventName: string, data: AblyMessage): Promise<void>;
85
+ /** Get the Ably connection ID (used for skip logic). */
86
+ get connectionId(): string | undefined;
87
+ /** Leave presence on all channels and close the connection. */
88
+ disconnect(): Promise<void>;
89
+ }
90
+
91
+ /**
92
+ * Context passed to message handlers.
93
+ * Provides `reply()` for one-shot responses and `stream()` for streaming.
94
+ * Handles the full Ably publish protocol: typing → chunks → response.
95
+ */
96
+ declare class MessageContext {
97
+ /** Formatted conversation history for LLM prompts. */
98
+ readonly conversationHistory: string;
99
+ /** The project ID this message was received on. */
100
+ readonly projectId: string;
101
+ private responseId;
102
+ private ablyManager;
103
+ private channelName;
104
+ private userId;
105
+ private agentName;
106
+ private client;
107
+ private responseDepth;
108
+ private respondingChain;
109
+ private chunkBatchMs;
110
+ constructor(opts: {
111
+ projectId: string;
112
+ channelName: string;
113
+ conversationHistory: string;
114
+ ablyManager: AblyManager;
115
+ userId: string;
116
+ agentName: string;
117
+ client: JaibberClient;
118
+ incomingDepth: number;
119
+ incomingChain: string[];
120
+ chunkBatchMs: number;
121
+ });
122
+ /** One-shot reply: publishes typing → response in sequence. */
123
+ reply(text: string): Promise<void>;
124
+ /**
125
+ * Streaming reply: consumes an async generator, batches chunks to Ably
126
+ * every chunkBatchMs (default 200ms), then publishes the final response.
127
+ *
128
+ * Mirrors useAbly.ts lines 86-102 chunk batching pattern.
129
+ */
130
+ stream(generator: () => AsyncGenerator<string, void, unknown>): Promise<void>;
131
+ private publishTyping;
132
+ private publishChunk;
133
+ private publishResponse;
134
+ private publishError;
135
+ /** Fire-and-forget persist to server. */
136
+ private persistAsync;
137
+ }
138
+ /**
139
+ * Context passed to task handlers.
140
+ * Provides `complete()` and `fail()` to update task status,
141
+ * plus `sendMessage()` for progress updates in chat.
142
+ */
143
+ declare class TaskContext {
144
+ readonly task: Task;
145
+ readonly projectId: string;
146
+ readonly conversationHistory: string;
147
+ private ablyManager;
148
+ private channelName;
149
+ private userId;
150
+ private agentName;
151
+ private client;
152
+ constructor(opts: {
153
+ task: Task;
154
+ projectId: string;
155
+ channelName: string;
156
+ conversationHistory: string;
157
+ ablyManager: AblyManager;
158
+ userId: string;
159
+ agentName: string;
160
+ client: JaibberClient;
161
+ });
162
+ /** Mark task as completed, optionally publishing a response message. */
163
+ complete(resultText?: string): Promise<void>;
164
+ /** Mark task as failed, optionally publishing an error message. */
165
+ fail(errorText?: string): Promise<void>;
166
+ /** Send a chat message (for progress updates). */
167
+ sendMessage(text: string): Promise<void>;
168
+ }
169
+
170
+ type ExecutionMode = "auto" | "plan";
171
+ interface AblyMessage {
172
+ from: string;
173
+ fromUsername: string;
174
+ projectId: string;
175
+ text: string;
176
+ messageId: string;
177
+ type: "message" | "response" | "typing" | "done" | "error" | "chunk" | "task-created" | "task-updated" | "task-deleted";
178
+ responseId?: string;
179
+ agentName?: string;
180
+ mentions?: string[];
181
+ executionMode?: ExecutionMode;
182
+ isAgentMessage?: boolean;
183
+ responseDepth?: number;
184
+ respondingChain?: string[];
185
+ isTaskNotification?: boolean;
186
+ attachments?: MessageAttachment[];
187
+ }
188
+ type TaskStatus = "submitted" | "working" | "input-required" | "completed" | "failed" | "cancelled";
189
+ type TaskPriority = "low" | "medium" | "high" | "urgent";
190
+ interface Task {
191
+ id: string;
192
+ projectId: string;
193
+ title: string;
194
+ description: string | null;
195
+ status: TaskStatus;
196
+ priority: TaskPriority;
197
+ assignedAgentName: string | null;
198
+ createdBy: string;
199
+ createdByType: "user" | "agent";
200
+ createdByName: string;
201
+ sourceMessageId: string | null;
202
+ createdAt: string;
203
+ updatedAt: string;
204
+ }
205
+ interface MessageAttachment {
206
+ id: string;
207
+ filename: string;
208
+ mimeType: string;
209
+ fileSize: number;
210
+ blobUrl: string;
211
+ }
212
+ interface Project {
213
+ id: string;
214
+ name: string;
215
+ description: string | null;
216
+ ablyChannelName: string;
217
+ role: string;
218
+ }
219
+ interface IncomingMessage {
220
+ id: string;
221
+ projectId: string;
222
+ from: string;
223
+ fromUsername: string;
224
+ text: string;
225
+ type: string;
226
+ responseDepth: number;
227
+ respondingChain: string[];
228
+ executionMode?: ExecutionMode;
229
+ isAgentMessage?: boolean;
230
+ attachments?: MessageAttachment[];
231
+ }
232
+ interface TaskEvent {
233
+ type: "task-created" | "task-updated" | "task-deleted";
234
+ task: Task;
235
+ projectId: string;
236
+ }
237
+ interface AgentConfig {
238
+ /** Jaibber server URL (e.g. "https://api.jaibber.com") */
239
+ serverUrl: string;
240
+ /** Login credentials for the agent's Jaibber account */
241
+ credentials: {
242
+ username: string;
243
+ password: string;
244
+ };
245
+ /** Agent display name (used for @mention routing and presence) */
246
+ agentName: string;
247
+ /** System prompt prepended to every LLM call */
248
+ agentInstructions?: string;
249
+ /** Machine identifier shown in presence */
250
+ machineName?: string;
251
+ /** Specific project IDs to join. Omit to join all user's projects. */
252
+ projectIds?: string[];
253
+ /** Max depth for agent-to-agent chains (default: 3) */
254
+ maxResponseDepth?: number;
255
+ /** Chunk batching interval in ms (default: 200) */
256
+ chunkBatchMs?: number;
257
+ /** Number of recent messages for conversation context (default: 20) */
258
+ contextWindowSize?: number;
259
+ }
260
+ type MessageHandler = (message: IncomingMessage, context: MessageContext) => Promise<void>;
261
+ type TaskHandler = (task: Task, context: TaskContext) => Promise<void>;
262
+ interface ServerMessage {
263
+ id: string;
264
+ projectId: string;
265
+ senderId: string;
266
+ senderType: "user" | "agent" | "api";
267
+ senderName: string;
268
+ type: "message" | "response" | "error";
269
+ text: string;
270
+ createdAt: string;
271
+ }
272
+ interface PersistMessagePayload {
273
+ id: string;
274
+ senderType: "agent";
275
+ senderName: string;
276
+ type: "message" | "response" | "error";
277
+ text: string;
278
+ }
279
+
280
+ /**
281
+ * Headless Jaibber agent.
282
+ *
283
+ * Connects to the Jaibber server via REST + Ably, subscribes to project
284
+ * channels, handles @mention routing, streams responses, and dual-writes
285
+ * to the server for persistence.
286
+ *
287
+ * Usage:
288
+ * ```ts
289
+ * const agent = new JaibberAgent({ serverUrl, credentials, agentName });
290
+ * await agent.connect();
291
+ * agent.onMessage(async (msg, ctx) => ctx.reply('Hello!'));
292
+ * ```
293
+ */
294
+ declare class JaibberAgent extends EventEmitter {
295
+ private config;
296
+ private client;
297
+ private ablyManager;
298
+ private messageHandler;
299
+ private taskHandler;
300
+ private provider;
301
+ private connected;
302
+ private projects;
303
+ private unsubscribers;
304
+ /** In-memory conversation history per project. */
305
+ private history;
306
+ /** Track in-flight responses to prevent double-handling. */
307
+ private activeResponses;
308
+ constructor(config: AgentConfig);
309
+ /** Authenticate, connect Ably, subscribe to project channels. */
310
+ connect(): Promise<void>;
311
+ /** Leave presence, disconnect Ably. */
312
+ disconnect(): Promise<void>;
313
+ /** Register a handler for incoming messages. */
314
+ onMessage(handler: MessageHandler): void;
315
+ /** Register a handler for assigned tasks. */
316
+ onTask(handler: TaskHandler): void;
317
+ /** Use a built-in LLM provider. */
318
+ useProvider(name: "anthropic", options: AnthropicProviderOptions): void;
319
+ private handleIncomingMessage;
320
+ /**
321
+ * Should this agent respond to the message?
322
+ * Mirrors useAbly.ts shouldAgentRespond() logic.
323
+ */
324
+ private shouldRespond;
325
+ private respondToMessage;
326
+ private handleTaskEvent;
327
+ private loadHistory;
328
+ private addToHistory;
329
+ /**
330
+ * Format conversation history for LLM context.
331
+ * Matches useAbly.ts lines 77-84 format.
332
+ */
333
+ private getFormattedHistory;
334
+ }
335
+
336
+ /**
337
+ * Anthropic Messages API provider.
338
+ * Streams responses via SSE, same pattern as src-tauri/src/claude_api.rs.
339
+ */
340
+ declare class AnthropicProvider implements Provider {
341
+ private apiKey;
342
+ private model;
343
+ private maxTokens;
344
+ constructor(options: AnthropicProviderOptions);
345
+ generate(prompt: string, systemPrompt: string, conversationContext: string): AsyncGenerator<string, void, unknown>;
346
+ }
347
+
348
+ export { type AblyMessage, type AgentConfig, AnthropicProvider, type AnthropicProviderOptions, type ExecutionMode, type IncomingMessage, JaibberAgent, type MessageAttachment, MessageContext, type MessageHandler, type Project, type Provider, type Task, TaskContext, type TaskHandler, type TaskPriority, type TaskStatus };