@jaibber/sdk 0.1.9 → 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.cjs CHANGED
@@ -30,13 +30,15 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // src/index.ts
31
31
  var index_exports = {};
32
32
  __export(index_exports, {
33
+ AGENT_TEMPLATES: () => AGENT_TEMPLATES,
33
34
  AnthropicProvider: () => AnthropicProvider,
34
35
  ClaudeCLIProvider: () => ClaudeCLIProvider,
35
36
  GoogleProvider: () => GoogleProvider,
36
37
  JaibberAgent: () => JaibberAgent,
37
38
  MessageContext: () => MessageContext,
38
39
  OpenAIProvider: () => OpenAIProvider,
39
- TaskContext: () => TaskContext
40
+ TaskContext: () => TaskContext,
41
+ getTemplate: () => getTemplate
40
42
  });
41
43
  module.exports = __toCommonJS(index_exports);
42
44
 
@@ -189,6 +191,23 @@ var JaibberClient = class {
189
191
  return data.data;
190
192
  }
191
193
  // ── Tasks ───────────────────────────────────────────────────────────
194
+ /** POST /api/projects/{id}/tasks — create a task. */
195
+ async createTask(projectId, data) {
196
+ const res = await fetch(
197
+ `${this.serverUrl}/api/projects/${projectId}/tasks`,
198
+ {
199
+ method: "POST",
200
+ headers: this.authHeaders(),
201
+ body: JSON.stringify(data)
202
+ }
203
+ );
204
+ if (!res.ok) {
205
+ const text = await res.text();
206
+ throw new Error(`Failed to create task (${res.status}): ${text}`);
207
+ }
208
+ const result = await res.json();
209
+ return result.data;
210
+ }
192
211
  /** PATCH /api/tasks/{taskId} — update task fields. */
193
212
  async updateTask(taskId, updates) {
194
213
  const res = await fetch(`${this.serverUrl}/api/tasks/${taskId}`, {
@@ -226,7 +245,11 @@ var AblyManager = class {
226
245
  callback(err, null);
227
246
  }
228
247
  },
229
- clientId: this.userId
248
+ clientId: this.userId,
249
+ disconnectedRetryTimeout: 5e3,
250
+ // 5s initial retry on disconnect
251
+ suspendedRetryTimeout: 3e4
252
+ // 30s retry when suspended
230
253
  });
231
254
  this.ably.connection.once("connected", () => {
232
255
  resolve();
@@ -238,6 +261,17 @@ var AblyManager = class {
238
261
  )
239
262
  );
240
263
  });
264
+ this.ably.connection.on("disconnected", () => {
265
+ console.warn("[sdk] Ably disconnected, will retry...");
266
+ });
267
+ this.ably.connection.on("suspended", () => {
268
+ console.warn("[sdk] Ably connection suspended (extended outage)");
269
+ });
270
+ this.ably.connection.on("connected", () => {
271
+ if (this.channels.size > 0) {
272
+ console.log("[sdk] Ably reconnected");
273
+ }
274
+ });
241
275
  });
242
276
  }
243
277
  /** Enter global presence channel (jaibber:presence). */
@@ -499,6 +533,18 @@ var TaskContext = class {
499
533
  }).catch((err) => console.error("[sdk] Failed to persist:", err));
500
534
  }
501
535
  }
536
+ /**
537
+ * Create a follow-up task assigned to another agent.
538
+ * Automatically sets parentTaskId to the current task's ID.
539
+ */
540
+ async createFollowUpTask(data) {
541
+ return this.client.createTask(this.projectId, {
542
+ ...data,
543
+ parentTaskId: this.task.id,
544
+ createdByType: "agent",
545
+ createdByName: this.agentName
546
+ });
547
+ }
502
548
  /** Send a chat message (for progress updates). */
503
549
  async sendMessage(text) {
504
550
  const msgId = (0, import_uuid.v4)();
@@ -523,13 +569,6 @@ var TaskContext = class {
523
569
  };
524
570
 
525
571
  // src/mentions.ts
526
- function parseMentions(text) {
527
- const mentions = [];
528
- for (const match of text.matchAll(/@(\w+(?:\s+\w+)*)/g)) {
529
- mentions.push(match[1].toLowerCase());
530
- }
531
- return mentions;
532
- }
533
572
  function mentionsAgent(text, agentName) {
534
573
  const pattern = new RegExp(`@${escapeRegex(agentName)}(?!\\w)`, "i");
535
574
  return pattern.test(text);
@@ -815,10 +854,28 @@ var GoogleProvider = class {
815
854
 
816
855
  // src/providers/claude-cli.ts
817
856
  var import_child_process = require("child_process");
857
+ var import_readline = require("readline");
818
858
  var ClaudeCLIProvider = class {
819
859
  projectDir;
860
+ sessionId;
861
+ continueSession;
862
+ /** Last session ID captured from Claude CLI stream-json output. */
863
+ lastSessionId;
820
864
  constructor(options = {}) {
821
865
  this.projectDir = options.projectDir ?? process.cwd();
866
+ this.sessionId = options.sessionId;
867
+ this.continueSession = options.continueSession ?? false;
868
+ }
869
+ /** Update session ID for future --resume calls. */
870
+ setSessionId(id) {
871
+ this.sessionId = id;
872
+ this.continueSession = false;
873
+ }
874
+ /** Clear session state (e.g. on conversation clear). */
875
+ clearSession() {
876
+ this.sessionId = void 0;
877
+ this.lastSessionId = void 0;
878
+ this.continueSession = false;
822
879
  }
823
880
  async *generate(prompt, systemPrompt, conversationContext) {
824
881
  let fullPrompt = "";
@@ -834,7 +891,15 @@ ${systemPrompt}
834
891
  fullPrompt += "\n\n---\n\n";
835
892
  }
836
893
  fullPrompt += prompt;
837
- const child = (0, import_child_process.spawn)("claude", ["--print", "--dangerously-skip-permissions"], {
894
+ const args = ["--print", "--output-format", "stream-json", "--dangerously-skip-permissions"];
895
+ if (this.sessionId) {
896
+ if (/^[a-zA-Z0-9-]+$/.test(this.sessionId)) {
897
+ args.push("--resume", this.sessionId);
898
+ }
899
+ } else if (this.continueSession) {
900
+ args.push("--continue");
901
+ }
902
+ const child = (0, import_child_process.spawn)("claude", args, {
838
903
  cwd: this.projectDir,
839
904
  stdio: ["pipe", "pipe", "pipe"],
840
905
  shell: false
@@ -845,16 +910,40 @@ ${systemPrompt}
845
910
  child.stderr?.on("data", (chunk) => {
846
911
  stderr += chunk.toString();
847
912
  });
848
- const stdout = child.stdout;
849
- for await (const chunk of stdout) {
850
- const text = chunk.toString();
851
- if (text) yield text;
913
+ const rl = (0, import_readline.createInterface)({ input: child.stdout, crlfDelay: Infinity });
914
+ let gotOutput = false;
915
+ for await (const line of rl) {
916
+ try {
917
+ const json = JSON.parse(line);
918
+ if (json.session_id && typeof json.session_id === "string") {
919
+ this.lastSessionId = json.session_id;
920
+ }
921
+ if (json.delta?.text) {
922
+ gotOutput = true;
923
+ yield json.delta.text;
924
+ continue;
925
+ }
926
+ const content = json.content ?? json.message?.content;
927
+ if (Array.isArray(content)) {
928
+ for (const item of content) {
929
+ if (item.type === "text" && item.text) {
930
+ gotOutput = true;
931
+ yield item.text;
932
+ }
933
+ }
934
+ }
935
+ } catch {
936
+ if (line.trim()) {
937
+ gotOutput = true;
938
+ yield line + "\n";
939
+ }
940
+ }
852
941
  }
853
942
  const exitCode = await new Promise((resolve) => {
854
943
  child.on("close", resolve);
855
944
  });
856
945
  if (exitCode !== 0 && exitCode !== null) {
857
- if (!stderr.trim()) return;
946
+ if (gotOutput || !stderr.trim()) return;
858
947
  throw new Error(`Claude CLI exited with code ${exitCode}: ${stderr.trim()}`);
859
948
  }
860
949
  }
@@ -878,6 +967,8 @@ var JaibberAgent = class extends import_events.EventEmitter {
878
967
  history = /* @__PURE__ */ new Map();
879
968
  /** Track in-flight responses to prevent double-handling. */
880
969
  activeResponses = /* @__PURE__ */ new Set();
970
+ /** Session IDs per project for Claude --resume. */
971
+ sessionIds = /* @__PURE__ */ new Map();
881
972
  constructor(config) {
882
973
  super();
883
974
  this.config = config;
@@ -977,8 +1068,21 @@ var JaibberAgent = class extends import_events.EventEmitter {
977
1068
  // ── Message handling ────────────────────────────────────────────────
978
1069
  async handleIncomingMessage(payload, project) {
979
1070
  if (payload._connectionId && payload._connectionId === this.ablyManager?.connectionId) return;
1071
+ if (payload.type === "deregister") {
1072
+ const targetName = payload.agentName?.toLowerCase();
1073
+ if (!targetName || targetName === this.config.agentName.toLowerCase()) {
1074
+ console.log(`[sdk] Received deregister command. Shutting down...`);
1075
+ await this.disconnect();
1076
+ process.exit(0);
1077
+ }
1078
+ return;
1079
+ }
980
1080
  if (payload.isTaskNotification) return;
981
1081
  if (payload.type !== "message" && payload.type !== "response") return;
1082
+ if (payload.text && payload.text.length > 1e5) {
1083
+ console.warn(`[sdk] Ignoring oversized message (${payload.text.length} chars)`);
1084
+ return;
1085
+ }
982
1086
  this.addToHistory(project.id, {
983
1087
  sender: payload.isAgentMessage ? "agent" : "user",
984
1088
  senderName: payload.fromUsername,
@@ -1006,8 +1110,7 @@ var JaibberAgent = class extends import_events.EventEmitter {
1006
1110
  const maxDepth = this.config.maxResponseDepth ?? DEFAULT_MAX_DEPTH;
1007
1111
  if (depth >= maxDepth) return false;
1008
1112
  if (chain.includes(this.config.agentName.toLowerCase())) return false;
1009
- const mentions = parseMentions(text);
1010
- if (mentions.length > 0 && !mentionsAgent(text, this.config.agentName)) return false;
1113
+ if (!mentionsAgent(text, this.config.agentName)) return false;
1011
1114
  return true;
1012
1115
  }
1013
1116
  async respondToMessage(payload, project, incomingDepth, incomingChain) {
@@ -1045,10 +1148,12 @@ var JaibberAgent = class extends import_events.EventEmitter {
1045
1148
  return;
1046
1149
  }
1047
1150
  if (this.provider) {
1151
+ this.updateProviderSession(project.id);
1048
1152
  const systemPrompt = this.config.agentInstructions ?? "";
1049
1153
  await ctx.stream(
1050
1154
  () => this.provider.generate(payload.text, systemPrompt, conversationHistory)
1051
1155
  );
1156
+ this.captureProviderSession(project.id);
1052
1157
  return;
1053
1158
  }
1054
1159
  console.warn(
@@ -1101,6 +1206,7 @@ var JaibberAgent = class extends import_events.EventEmitter {
1101
1206
  return;
1102
1207
  }
1103
1208
  if (this.provider) {
1209
+ this.updateProviderSession(project.id);
1104
1210
  const taskPrompt = task.description ? `Task: ${task.title}
1105
1211
 
1106
1212
  ${task.description}` : `Task: ${task.title}`;
@@ -1125,6 +1231,7 @@ ${task.description}` : `Task: ${task.title}`;
1125
1231
  conversationHistory
1126
1232
  )
1127
1233
  );
1234
+ this.captureProviderSession(project.id);
1128
1235
  await this.client.updateTask(task.id, { status: "completed" });
1129
1236
  } catch {
1130
1237
  await this.client.updateTask(task.id, { status: "failed" });
@@ -1142,6 +1249,27 @@ ${task.description}` : `Task: ${task.title}`;
1142
1249
  }
1143
1250
  }
1144
1251
  }
1252
+ // ── Session management (Claude --resume) ────────────────────────────
1253
+ /** Pass stored session ID to ClaudeCLIProvider before each invocation. */
1254
+ updateProviderSession(projectId) {
1255
+ if (this.provider instanceof ClaudeCLIProvider) {
1256
+ const sid = this.sessionIds.get(projectId);
1257
+ if (sid) {
1258
+ this.provider.setSessionId(sid);
1259
+ } else {
1260
+ this.provider.clearSession();
1261
+ }
1262
+ }
1263
+ }
1264
+ /** After response, capture the session ID from ClaudeCLIProvider if available. */
1265
+ captureProviderSession(projectId) {
1266
+ if (this.provider instanceof ClaudeCLIProvider) {
1267
+ const sid = this.provider.lastSessionId;
1268
+ if (sid) {
1269
+ this.sessionIds.set(projectId, sid);
1270
+ }
1271
+ }
1272
+ }
1145
1273
  // ── Conversation history ────────────────────────────────────────────
1146
1274
  async loadHistory(projectId) {
1147
1275
  const contextSize = this.config.contextWindowSize ?? DEFAULT_CONTEXT_WINDOW;
@@ -1185,14 +1313,65 @@ ${task.description}` : `Task: ${task.title}`;
1185
1313
  }).join("\n\n");
1186
1314
  }
1187
1315
  };
1316
+
1317
+ // src/templates.ts
1318
+ var AGENT_TEMPLATES = [
1319
+ {
1320
+ id: "code-writer",
1321
+ name: "Code Writer",
1322
+ description: "General-purpose coding agent",
1323
+ agentName: "Coder",
1324
+ 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"
1325
+ },
1326
+ {
1327
+ id: "pr-reviewer",
1328
+ name: "PR Reviewer",
1329
+ description: "Reviews code changes, suggests improvements",
1330
+ agentName: "Reviewer",
1331
+ 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"
1332
+ },
1333
+ {
1334
+ id: "test-writer",
1335
+ name: "Test Writer",
1336
+ description: "Generates tests for existing code",
1337
+ agentName: "Tester",
1338
+ 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"
1339
+ },
1340
+ {
1341
+ id: "devops",
1342
+ name: "DevOps",
1343
+ description: "Infrastructure, deployment, CI/CD tasks",
1344
+ agentName: "DevOps",
1345
+ 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"
1346
+ },
1347
+ {
1348
+ id: "bug-hunter",
1349
+ name: "Bug Hunter",
1350
+ description: "Analyzes errors, traces bugs, suggests fixes",
1351
+ agentName: "BugHunter",
1352
+ 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"
1353
+ },
1354
+ {
1355
+ id: "architect",
1356
+ name: "Architect",
1357
+ description: "High-level design and refactoring guidance",
1358
+ agentName: "Architect",
1359
+ 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"
1360
+ }
1361
+ ];
1362
+ function getTemplate(id) {
1363
+ return AGENT_TEMPLATES.find((t) => t.id === id);
1364
+ }
1188
1365
  // Annotate the CommonJS export names for ESM import in node:
1189
1366
  0 && (module.exports = {
1367
+ AGENT_TEMPLATES,
1190
1368
  AnthropicProvider,
1191
1369
  ClaudeCLIProvider,
1192
1370
  GoogleProvider,
1193
1371
  JaibberAgent,
1194
1372
  MessageContext,
1195
1373
  OpenAIProvider,
1196
- TaskContext
1374
+ TaskContext,
1375
+ getTemplate
1197
1376
  });
1198
1377
  //# sourceMappingURL=index.cjs.map