@jaibber/sdk 0.2.0 → 0.3.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
@@ -34,6 +34,10 @@ interface GoogleProviderOptions {
34
34
  interface ClaudeCLIProviderOptions {
35
35
  /** Working directory for Claude CLI (default: cwd) */
36
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;
37
41
  }
38
42
 
39
43
  /**
@@ -66,6 +70,16 @@ declare class JaibberClient {
66
70
  persistMessage(projectId: string, msg: PersistMessagePayload): Promise<void>;
67
71
  /** GET /api/projects/{id}/messages — fetch recent messages. */
68
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>;
69
83
  /** PATCH /api/tasks/{taskId} — update task fields. */
70
84
  updateTask(taskId: string, updates: Partial<Task>): Promise<void>;
71
85
  }
@@ -187,6 +201,16 @@ declare class TaskContext {
187
201
  complete(resultText?: string): Promise<void>;
188
202
  /** Mark task as failed, optionally publishing an error message. */
189
203
  fail(errorText?: string): Promise<void>;
204
+ /**
205
+ * Create a follow-up task assigned to another agent.
206
+ * Automatically sets parentTaskId to the current task's ID.
207
+ */
208
+ createFollowUpTask(data: {
209
+ title: string;
210
+ description?: string;
211
+ priority?: "low" | "medium" | "high" | "urgent";
212
+ assignedAgentName?: string;
213
+ }): Promise<Task>;
190
214
  /** Send a chat message (for progress updates). */
191
215
  sendMessage(text: string): Promise<void>;
192
216
  }
@@ -226,6 +250,7 @@ interface Task {
226
250
  createdByType: "user" | "agent";
227
251
  createdByName: string;
228
252
  sourceMessageId: string | null;
253
+ parentTaskId: string | null;
229
254
  createdAt: string;
230
255
  updatedAt: string;
231
256
  }
@@ -334,6 +359,8 @@ declare class JaibberAgent extends EventEmitter {
334
359
  private history;
335
360
  /** Track in-flight responses to prevent double-handling. */
336
361
  private activeResponses;
362
+ /** Session IDs per project for Claude --resume. */
363
+ private sessionIds;
337
364
  constructor(config: AgentConfig);
338
365
  /** Authenticate, connect Ably, subscribe to project channels. */
339
366
  connect(): Promise<void>;
@@ -356,6 +383,10 @@ declare class JaibberAgent extends EventEmitter {
356
383
  private shouldRespond;
357
384
  private respondToMessage;
358
385
  private handleTaskEvent;
386
+ /** Pass stored session ID to ClaudeCLIProvider before each invocation. */
387
+ private updateProviderSession;
388
+ /** After response, capture the session ID from ClaudeCLIProvider if available. */
389
+ private captureProviderSession;
359
390
  private loadHistory;
360
391
  private addToHistory;
361
392
  /**
@@ -403,12 +434,31 @@ declare class GoogleProvider implements Provider {
403
434
 
404
435
  /**
405
436
  * Claude CLI provider — shells out to locally-installed `claude` CLI.
437
+ * Uses `--output-format stream-json` to parse structured output and capture session IDs.
406
438
  * No API key needed; uses whatever auth the local Claude CLI has.
407
439
  */
408
440
  declare class ClaudeCLIProvider implements Provider {
409
441
  private projectDir;
442
+ private sessionId?;
443
+ private continueSession;
444
+ /** Last session ID captured from Claude CLI stream-json output. */
445
+ lastSessionId?: string;
410
446
  constructor(options?: ClaudeCLIProviderOptions);
447
+ /** Update session ID for future --resume calls. */
448
+ setSessionId(id: string): void;
449
+ /** Clear session state (e.g. on conversation clear). */
450
+ clearSession(): void;
411
451
  generate(prompt: string, systemPrompt: string, conversationContext: string): AsyncGenerator<string, void, unknown>;
412
452
  }
413
453
 
414
- export { type AblyMessage, type AgentConfig, 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 };
454
+ interface AgentTemplate {
455
+ id: string;
456
+ name: string;
457
+ description: string;
458
+ agentName: string;
459
+ instructions: string;
460
+ }
461
+ declare const AGENT_TEMPLATES: AgentTemplate[];
462
+ declare function getTemplate(id: string): AgentTemplate | undefined;
463
+
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 };
package/dist/index.js CHANGED
@@ -147,6 +147,23 @@ var JaibberClient = class {
147
147
  return data.data;
148
148
  }
149
149
  // ── Tasks ───────────────────────────────────────────────────────────
150
+ /** POST /api/projects/{id}/tasks — create a task. */
151
+ async createTask(projectId, data) {
152
+ const res = await fetch(
153
+ `${this.serverUrl}/api/projects/${projectId}/tasks`,
154
+ {
155
+ method: "POST",
156
+ headers: this.authHeaders(),
157
+ body: JSON.stringify(data)
158
+ }
159
+ );
160
+ if (!res.ok) {
161
+ const text = await res.text();
162
+ throw new Error(`Failed to create task (${res.status}): ${text}`);
163
+ }
164
+ const result = await res.json();
165
+ return result.data;
166
+ }
150
167
  /** PATCH /api/tasks/{taskId} — update task fields. */
151
168
  async updateTask(taskId, updates) {
152
169
  const res = await fetch(`${this.serverUrl}/api/tasks/${taskId}`, {
@@ -184,7 +201,11 @@ var AblyManager = class {
184
201
  callback(err, null);
185
202
  }
186
203
  },
187
- clientId: this.userId
204
+ clientId: this.userId,
205
+ disconnectedRetryTimeout: 5e3,
206
+ // 5s initial retry on disconnect
207
+ suspendedRetryTimeout: 3e4
208
+ // 30s retry when suspended
188
209
  });
189
210
  this.ably.connection.once("connected", () => {
190
211
  resolve();
@@ -196,6 +217,17 @@ var AblyManager = class {
196
217
  )
197
218
  );
198
219
  });
220
+ this.ably.connection.on("disconnected", () => {
221
+ console.warn("[sdk] Ably disconnected, will retry...");
222
+ });
223
+ this.ably.connection.on("suspended", () => {
224
+ console.warn("[sdk] Ably connection suspended (extended outage)");
225
+ });
226
+ this.ably.connection.on("connected", () => {
227
+ if (this.channels.size > 0) {
228
+ console.log("[sdk] Ably reconnected");
229
+ }
230
+ });
199
231
  });
200
232
  }
201
233
  /** Enter global presence channel (jaibber:presence). */
@@ -457,6 +489,18 @@ var TaskContext = class {
457
489
  }).catch((err) => console.error("[sdk] Failed to persist:", err));
458
490
  }
459
491
  }
492
+ /**
493
+ * Create a follow-up task assigned to another agent.
494
+ * Automatically sets parentTaskId to the current task's ID.
495
+ */
496
+ async createFollowUpTask(data) {
497
+ return this.client.createTask(this.projectId, {
498
+ ...data,
499
+ parentTaskId: this.task.id,
500
+ createdByType: "agent",
501
+ createdByName: this.agentName
502
+ });
503
+ }
460
504
  /** Send a chat message (for progress updates). */
461
505
  async sendMessage(text) {
462
506
  const msgId = uuidv4();
@@ -481,13 +525,6 @@ var TaskContext = class {
481
525
  };
482
526
 
483
527
  // src/mentions.ts
484
- function parseMentions(text) {
485
- const mentions = [];
486
- for (const match of text.matchAll(/@(\w+(?:\s+\w+)*)/g)) {
487
- mentions.push(match[1].toLowerCase());
488
- }
489
- return mentions;
490
- }
491
528
  function mentionsAgent(text, agentName) {
492
529
  const pattern = new RegExp(`@${escapeRegex(agentName)}(?!\\w)`, "i");
493
530
  return pattern.test(text);
@@ -773,10 +810,28 @@ var GoogleProvider = class {
773
810
 
774
811
  // src/providers/claude-cli.ts
775
812
  import { spawn } from "child_process";
813
+ import { createInterface } from "readline";
776
814
  var ClaudeCLIProvider = class {
777
815
  projectDir;
816
+ sessionId;
817
+ continueSession;
818
+ /** Last session ID captured from Claude CLI stream-json output. */
819
+ lastSessionId;
778
820
  constructor(options = {}) {
779
821
  this.projectDir = options.projectDir ?? process.cwd();
822
+ this.sessionId = options.sessionId;
823
+ this.continueSession = options.continueSession ?? false;
824
+ }
825
+ /** Update session ID for future --resume calls. */
826
+ setSessionId(id) {
827
+ this.sessionId = id;
828
+ this.continueSession = false;
829
+ }
830
+ /** Clear session state (e.g. on conversation clear). */
831
+ clearSession() {
832
+ this.sessionId = void 0;
833
+ this.lastSessionId = void 0;
834
+ this.continueSession = false;
780
835
  }
781
836
  async *generate(prompt, systemPrompt, conversationContext) {
782
837
  let fullPrompt = "";
@@ -792,7 +847,15 @@ ${systemPrompt}
792
847
  fullPrompt += "\n\n---\n\n";
793
848
  }
794
849
  fullPrompt += prompt;
795
- const child = spawn("claude", ["--print", "--dangerously-skip-permissions"], {
850
+ const args = ["--print", "--output-format", "stream-json", "--dangerously-skip-permissions"];
851
+ if (this.sessionId) {
852
+ if (/^[a-zA-Z0-9-]+$/.test(this.sessionId)) {
853
+ args.push("--resume", this.sessionId);
854
+ }
855
+ } else if (this.continueSession) {
856
+ args.push("--continue");
857
+ }
858
+ const child = spawn("claude", args, {
796
859
  cwd: this.projectDir,
797
860
  stdio: ["pipe", "pipe", "pipe"],
798
861
  shell: false
@@ -803,16 +866,40 @@ ${systemPrompt}
803
866
  child.stderr?.on("data", (chunk) => {
804
867
  stderr += chunk.toString();
805
868
  });
806
- const stdout = child.stdout;
807
- for await (const chunk of stdout) {
808
- const text = chunk.toString();
809
- if (text) yield text;
869
+ const rl = createInterface({ input: child.stdout, crlfDelay: Infinity });
870
+ let gotOutput = false;
871
+ for await (const line of rl) {
872
+ try {
873
+ const json = JSON.parse(line);
874
+ if (json.session_id && typeof json.session_id === "string") {
875
+ this.lastSessionId = json.session_id;
876
+ }
877
+ if (json.delta?.text) {
878
+ gotOutput = true;
879
+ yield json.delta.text;
880
+ continue;
881
+ }
882
+ const content = json.content ?? json.message?.content;
883
+ if (Array.isArray(content)) {
884
+ for (const item of content) {
885
+ if (item.type === "text" && item.text) {
886
+ gotOutput = true;
887
+ yield item.text;
888
+ }
889
+ }
890
+ }
891
+ } catch {
892
+ if (line.trim()) {
893
+ gotOutput = true;
894
+ yield line + "\n";
895
+ }
896
+ }
810
897
  }
811
898
  const exitCode = await new Promise((resolve) => {
812
899
  child.on("close", resolve);
813
900
  });
814
901
  if (exitCode !== 0 && exitCode !== null) {
815
- if (!stderr.trim()) return;
902
+ if (gotOutput || !stderr.trim()) return;
816
903
  throw new Error(`Claude CLI exited with code ${exitCode}: ${stderr.trim()}`);
817
904
  }
818
905
  }
@@ -836,6 +923,8 @@ var JaibberAgent = class extends EventEmitter {
836
923
  history = /* @__PURE__ */ new Map();
837
924
  /** Track in-flight responses to prevent double-handling. */
838
925
  activeResponses = /* @__PURE__ */ new Set();
926
+ /** Session IDs per project for Claude --resume. */
927
+ sessionIds = /* @__PURE__ */ new Map();
839
928
  constructor(config) {
840
929
  super();
841
930
  this.config = config;
@@ -946,6 +1035,10 @@ var JaibberAgent = class extends EventEmitter {
946
1035
  }
947
1036
  if (payload.isTaskNotification) return;
948
1037
  if (payload.type !== "message" && payload.type !== "response") return;
1038
+ if (payload.text && payload.text.length > 1e5) {
1039
+ console.warn(`[sdk] Ignoring oversized message (${payload.text.length} chars)`);
1040
+ return;
1041
+ }
949
1042
  this.addToHistory(project.id, {
950
1043
  sender: payload.isAgentMessage ? "agent" : "user",
951
1044
  senderName: payload.fromUsername,
@@ -973,8 +1066,7 @@ var JaibberAgent = class extends EventEmitter {
973
1066
  const maxDepth = this.config.maxResponseDepth ?? DEFAULT_MAX_DEPTH;
974
1067
  if (depth >= maxDepth) return false;
975
1068
  if (chain.includes(this.config.agentName.toLowerCase())) return false;
976
- const mentions = parseMentions(text);
977
- if (mentions.length > 0 && !mentionsAgent(text, this.config.agentName)) return false;
1069
+ if (!mentionsAgent(text, this.config.agentName)) return false;
978
1070
  return true;
979
1071
  }
980
1072
  async respondToMessage(payload, project, incomingDepth, incomingChain) {
@@ -1012,10 +1104,12 @@ var JaibberAgent = class extends EventEmitter {
1012
1104
  return;
1013
1105
  }
1014
1106
  if (this.provider) {
1107
+ this.updateProviderSession(project.id);
1015
1108
  const systemPrompt = this.config.agentInstructions ?? "";
1016
1109
  await ctx.stream(
1017
1110
  () => this.provider.generate(payload.text, systemPrompt, conversationHistory)
1018
1111
  );
1112
+ this.captureProviderSession(project.id);
1019
1113
  return;
1020
1114
  }
1021
1115
  console.warn(
@@ -1068,6 +1162,7 @@ var JaibberAgent = class extends EventEmitter {
1068
1162
  return;
1069
1163
  }
1070
1164
  if (this.provider) {
1165
+ this.updateProviderSession(project.id);
1071
1166
  const taskPrompt = task.description ? `Task: ${task.title}
1072
1167
 
1073
1168
  ${task.description}` : `Task: ${task.title}`;
@@ -1092,6 +1187,7 @@ ${task.description}` : `Task: ${task.title}`;
1092
1187
  conversationHistory
1093
1188
  )
1094
1189
  );
1190
+ this.captureProviderSession(project.id);
1095
1191
  await this.client.updateTask(task.id, { status: "completed" });
1096
1192
  } catch {
1097
1193
  await this.client.updateTask(task.id, { status: "failed" });
@@ -1109,6 +1205,27 @@ ${task.description}` : `Task: ${task.title}`;
1109
1205
  }
1110
1206
  }
1111
1207
  }
1208
+ // ── Session management (Claude --resume) ────────────────────────────
1209
+ /** Pass stored session ID to ClaudeCLIProvider before each invocation. */
1210
+ updateProviderSession(projectId) {
1211
+ if (this.provider instanceof ClaudeCLIProvider) {
1212
+ const sid = this.sessionIds.get(projectId);
1213
+ if (sid) {
1214
+ this.provider.setSessionId(sid);
1215
+ } else {
1216
+ this.provider.clearSession();
1217
+ }
1218
+ }
1219
+ }
1220
+ /** After response, capture the session ID from ClaudeCLIProvider if available. */
1221
+ captureProviderSession(projectId) {
1222
+ if (this.provider instanceof ClaudeCLIProvider) {
1223
+ const sid = this.provider.lastSessionId;
1224
+ if (sid) {
1225
+ this.sessionIds.set(projectId, sid);
1226
+ }
1227
+ }
1228
+ }
1112
1229
  // ── Conversation history ────────────────────────────────────────────
1113
1230
  async loadHistory(projectId) {
1114
1231
  const contextSize = this.config.contextWindowSize ?? DEFAULT_CONTEXT_WINDOW;
@@ -1152,13 +1269,64 @@ ${task.description}` : `Task: ${task.title}`;
1152
1269
  }).join("\n\n");
1153
1270
  }
1154
1271
  };
1272
+
1273
+ // src/templates.ts
1274
+ var AGENT_TEMPLATES = [
1275
+ {
1276
+ id: "code-writer",
1277
+ name: "Code Writer",
1278
+ description: "General-purpose coding agent",
1279
+ agentName: "Coder",
1280
+ instructions: "You are a skilled software engineer. When given a coding task:\n- Write clean, well-structured code that follows the project's existing patterns\n- Keep changes minimal and focused on the request\n- If you need to read files for context, do so before making changes\n- Prefer editing existing files over creating new ones\n- Do not add unnecessary comments, type annotations, or refactoring beyond the scope of the task"
1281
+ },
1282
+ {
1283
+ id: "pr-reviewer",
1284
+ name: "PR Reviewer",
1285
+ description: "Reviews code changes, suggests improvements",
1286
+ agentName: "Reviewer",
1287
+ instructions: "You are a thorough code reviewer. When reviewing changes:\n- Focus on correctness, security, and maintainability\n- Point out potential bugs, edge cases, and performance issues\n- Suggest concrete improvements with code examples\n- Be direct and concise \u2014 no filler praise\n- If the code looks good, say so briefly"
1288
+ },
1289
+ {
1290
+ id: "test-writer",
1291
+ name: "Test Writer",
1292
+ description: "Generates tests for existing code",
1293
+ agentName: "Tester",
1294
+ instructions: "You are a testing specialist. When asked to write tests:\n- Match the project's existing test framework and patterns\n- Cover happy paths, edge cases, and error conditions\n- Write tests that are readable and self-documenting\n- Use descriptive test names that explain the expected behavior\n- Prefer integration tests over unit tests when testing API endpoints"
1295
+ },
1296
+ {
1297
+ id: "devops",
1298
+ name: "DevOps",
1299
+ description: "Infrastructure, deployment, CI/CD tasks",
1300
+ agentName: "DevOps",
1301
+ instructions: "You are a DevOps engineer. When working on infrastructure tasks:\n- Prioritize reliability and security over convenience\n- Use environment variables for secrets \u2014 never hardcode them\n- Write idempotent scripts and configurations\n- Document any manual steps that can't be automated"
1302
+ },
1303
+ {
1304
+ id: "bug-hunter",
1305
+ name: "Bug Hunter",
1306
+ description: "Analyzes errors, traces bugs, suggests fixes",
1307
+ agentName: "BugHunter",
1308
+ instructions: "You are a debugging specialist. When investigating bugs:\n- Start by reading error messages and stack traces carefully\n- Trace the execution path from the error back to the root cause\n- Look at recent changes that might have introduced the bug\n- Propose a minimal fix that addresses the root cause, not just the symptom"
1309
+ },
1310
+ {
1311
+ id: "architect",
1312
+ name: "Architect",
1313
+ description: "High-level design and refactoring guidance",
1314
+ agentName: "Architect",
1315
+ instructions: "You are a software architect. When advising on design:\n- Consider the existing codebase architecture before proposing changes\n- Favor simplicity over cleverness\n- Think about maintainability, testability, and team knowledge\n- Provide concrete file paths and code examples, not just abstract guidance"
1316
+ }
1317
+ ];
1318
+ function getTemplate(id) {
1319
+ return AGENT_TEMPLATES.find((t) => t.id === id);
1320
+ }
1155
1321
  export {
1322
+ AGENT_TEMPLATES,
1156
1323
  AnthropicProvider,
1157
1324
  ClaudeCLIProvider,
1158
1325
  GoogleProvider,
1159
1326
  JaibberAgent,
1160
1327
  MessageContext,
1161
1328
  OpenAIProvider,
1162
- TaskContext
1329
+ TaskContext,
1330
+ getTemplate
1163
1331
  };
1164
1332
  //# sourceMappingURL=index.js.map