@jaibber/sdk 0.1.0 → 0.1.2

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/README.md ADDED
@@ -0,0 +1,70 @@
1
+ # @jaibber/sdk
2
+
3
+ Headless agent SDK for [Jaibber](https://jaibber.com) — run AI agents without a desktop app.
4
+
5
+ ## Quick Start
6
+
7
+ ```bash
8
+ npx @jaibber/sdk \
9
+ --username bot \
10
+ --password secret \
11
+ --agent-name Coder \
12
+ --project myproject
13
+ ```
14
+
15
+ Or install globally:
16
+
17
+ ```bash
18
+ npm install -g @jaibber/sdk
19
+ jaibber-agent --username bot --password secret --agent-name Coder
20
+ ```
21
+
22
+ ## Programmatic Usage
23
+
24
+ ```typescript
25
+ import { JaibberAgent, AnthropicProvider } from "@jaibber/sdk";
26
+
27
+ const agent = new JaibberAgent({
28
+ apiBaseUrl: "https://api.jaibber.com",
29
+ username: "bot",
30
+ password: "secret",
31
+ agentName: "Coder",
32
+ provider: new AnthropicProvider({ apiKey: process.env.ANTHROPIC_API_KEY }),
33
+ });
34
+
35
+ agent.onMessage(async (ctx) => {
36
+ const stream = await ctx.provider.stream(ctx.messages);
37
+ await ctx.stream(stream);
38
+ });
39
+
40
+ agent.onTask(async (ctx) => {
41
+ await ctx.complete("Task done!");
42
+ });
43
+
44
+ await agent.start();
45
+ ```
46
+
47
+ ## Environment Variables
48
+
49
+ | Variable | Description |
50
+ |----------|-------------|
51
+ | `ANTHROPIC_API_KEY` | Anthropic API key for Claude |
52
+ | `JAIBBER_PASSWORD` | Password (alternative to `--password` flag) |
53
+
54
+ ## Features
55
+
56
+ - Real-time streaming via Ably WebSocket
57
+ - @mention routing — only responds when addressed
58
+ - Task auto-execution (submitted → working → completed/failed)
59
+ - Conversation context (last 20 messages)
60
+ - Loop prevention (max depth 3)
61
+ - Graceful shutdown on SIGINT/SIGTERM
62
+ - Dual-write: responses published to both Ably and REST API
63
+
64
+ ## Documentation
65
+
66
+ Full docs at [jaibber.com/guide/sdk](https://jaibber.com/guide/sdk)
67
+
68
+ ## License
69
+
70
+ MIT
package/dist/cli.js CHANGED
@@ -14,6 +14,25 @@ var JaibberClient = class {
14
14
  this.serverUrl = serverUrl2.replace(/\/+$/, "");
15
15
  }
16
16
  // ── Auth ────────────────────────────────────────────────────────────
17
+ /** POST /api/auth/register — create a new account, stores JWT. */
18
+ async register(username2, password2) {
19
+ const res = await fetch(`${this.serverUrl}/api/auth/register`, {
20
+ method: "POST",
21
+ headers: { "Content-Type": "application/json" },
22
+ body: JSON.stringify({ username: username2, password: password2 })
23
+ });
24
+ if (!res.ok) {
25
+ const text = await res.text();
26
+ if (res.status === 409) {
27
+ throw new Error(`Username "${username2}" is already taken.`);
28
+ }
29
+ throw new Error(`Registration failed (${res.status}): ${text}`);
30
+ }
31
+ const data = await res.json();
32
+ this.jwt = data.token;
33
+ this.userId = data.userId;
34
+ this.username = data.username;
35
+ }
17
36
  /** POST /api/auth/token — login with credentials, stores JWT. */
18
37
  async login(username2, password2) {
19
38
  const res = await fetch(`${this.serverUrl}/api/auth/token`, {
@@ -62,6 +81,26 @@ var JaibberClient = class {
62
81
  role: p.role
63
82
  }));
64
83
  }
84
+ /** POST /api/projects — create a new project, returns it. */
85
+ async createProject(name, description) {
86
+ const res = await fetch(`${this.serverUrl}/api/projects`, {
87
+ method: "POST",
88
+ headers: this.authHeaders(),
89
+ body: JSON.stringify({ name, description })
90
+ });
91
+ if (!res.ok) {
92
+ const text = await res.text();
93
+ throw new Error(`Failed to create project (${res.status}): ${text}`);
94
+ }
95
+ const data = await res.json();
96
+ return {
97
+ id: data.id,
98
+ name: data.name,
99
+ description: data.description,
100
+ ablyChannelName: data.ablyChannelName,
101
+ role: data.role
102
+ };
103
+ }
65
104
  // ── Ably token ──────────────────────────────────────────────────────
66
105
  /** POST /api/ably/token — get scoped Ably TokenRequest. */
67
106
  async getAblyToken() {
@@ -568,6 +607,211 @@ var AnthropicProvider = class {
568
607
  }
569
608
  };
570
609
 
610
+ // src/providers/openai.ts
611
+ var OPENAI_API_URL = "https://api.openai.com/v1/chat/completions";
612
+ var DEFAULT_MODEL2 = "gpt-4o";
613
+ var DEFAULT_MAX_TOKENS2 = 8192;
614
+ var OpenAIProvider = class {
615
+ apiKey;
616
+ model;
617
+ maxTokens;
618
+ constructor(options) {
619
+ this.apiKey = options.apiKey;
620
+ this.model = options.model ?? DEFAULT_MODEL2;
621
+ this.maxTokens = options.maxTokens ?? DEFAULT_MAX_TOKENS2;
622
+ }
623
+ async *generate(prompt, systemPrompt, conversationContext) {
624
+ let fullText = "";
625
+ if (conversationContext) {
626
+ fullText += 'Below is the recent conversation history for context. Respond ONLY to the final user message. Be conversational and concise \u2014 reply directly to the user as a chat participant. Do NOT narrate your thought process, planning steps, or internal reasoning. Do NOT describe actions you would take (e.g. "I should...", "Let me...", "I will..."). Just answer.\n\n';
627
+ fullText += conversationContext;
628
+ fullText += "\n\n---\n\n";
629
+ }
630
+ fullText += prompt;
631
+ const messages = [];
632
+ if (systemPrompt) {
633
+ messages.push({ role: "system", content: systemPrompt });
634
+ }
635
+ messages.push({ role: "user", content: fullText });
636
+ const response = await fetch(OPENAI_API_URL, {
637
+ method: "POST",
638
+ headers: {
639
+ Authorization: `Bearer ${this.apiKey}`,
640
+ "Content-Type": "application/json"
641
+ },
642
+ body: JSON.stringify({
643
+ model: this.model,
644
+ max_tokens: this.maxTokens,
645
+ stream: true,
646
+ messages
647
+ })
648
+ });
649
+ if (!response.ok) {
650
+ const text = await response.text();
651
+ const status = response.status;
652
+ if (status === 401) {
653
+ throw new Error("Invalid OpenAI API key. Check your API key.");
654
+ } else if (status === 429) {
655
+ throw new Error("OpenAI API rate limit exceeded. Please wait and try again.");
656
+ }
657
+ throw new Error(`OpenAI API returned ${status}: ${text}`);
658
+ }
659
+ if (!response.body) {
660
+ throw new Error("OpenAI API returned no response body");
661
+ }
662
+ const reader = response.body.getReader();
663
+ const decoder = new TextDecoder();
664
+ let buffer = "";
665
+ try {
666
+ while (true) {
667
+ const { done, value } = await reader.read();
668
+ if (done) break;
669
+ buffer += decoder.decode(value, { stream: true });
670
+ while (true) {
671
+ const newlinePos = buffer.indexOf("\n");
672
+ if (newlinePos === -1) break;
673
+ const line = buffer.slice(0, newlinePos).replace(/\r$/, "");
674
+ buffer = buffer.slice(newlinePos + 1);
675
+ if (!line || !line.startsWith("data: ")) continue;
676
+ const data = line.slice(6).trim();
677
+ if (data === "[DONE]") return;
678
+ try {
679
+ const json = JSON.parse(data);
680
+ const content = json?.choices?.[0]?.delta?.content;
681
+ if (content) yield content;
682
+ } catch {
683
+ }
684
+ }
685
+ }
686
+ } finally {
687
+ reader.releaseLock();
688
+ }
689
+ }
690
+ };
691
+
692
+ // src/providers/google.ts
693
+ var DEFAULT_MODEL3 = "gemini-2.0-flash";
694
+ var DEFAULT_MAX_TOKENS3 = 8192;
695
+ var GoogleProvider = class {
696
+ apiKey;
697
+ model;
698
+ maxTokens;
699
+ constructor(options) {
700
+ this.apiKey = options.apiKey;
701
+ this.model = options.model ?? DEFAULT_MODEL3;
702
+ this.maxTokens = options.maxTokens ?? DEFAULT_MAX_TOKENS3;
703
+ }
704
+ async *generate(prompt, systemPrompt, conversationContext) {
705
+ let fullText = "";
706
+ if (conversationContext) {
707
+ fullText += 'Below is the recent conversation history for context. Respond ONLY to the final user message. Be conversational and concise \u2014 reply directly to the user as a chat participant. Do NOT narrate your thought process, planning steps, or internal reasoning. Do NOT describe actions you would take (e.g. "I should...", "Let me...", "I will..."). Just answer.\n\n';
708
+ fullText += conversationContext;
709
+ fullText += "\n\n---\n\n";
710
+ }
711
+ fullText += prompt;
712
+ const url = `https://generativelanguage.googleapis.com/v1beta/models/${this.model}:streamGenerateContent?alt=sse&key=${this.apiKey}`;
713
+ const body = {
714
+ contents: [{ parts: [{ text: fullText }] }],
715
+ generationConfig: {
716
+ maxOutputTokens: this.maxTokens
717
+ }
718
+ };
719
+ if (systemPrompt) {
720
+ body.systemInstruction = { parts: [{ text: systemPrompt }] };
721
+ }
722
+ const response = await fetch(url, {
723
+ method: "POST",
724
+ headers: { "Content-Type": "application/json" },
725
+ body: JSON.stringify(body)
726
+ });
727
+ if (!response.ok) {
728
+ const text = await response.text();
729
+ const status = response.status;
730
+ if (status === 400 || status === 403) {
731
+ throw new Error(`Google AI API error (${status}): ${text}`);
732
+ } else if (status === 429) {
733
+ throw new Error("Google AI API rate limit exceeded. Please wait and try again.");
734
+ }
735
+ throw new Error(`Google AI API returned ${status}: ${text}`);
736
+ }
737
+ if (!response.body) {
738
+ throw new Error("Google AI API returned no response body");
739
+ }
740
+ const reader = response.body.getReader();
741
+ const decoder = new TextDecoder();
742
+ let buffer = "";
743
+ try {
744
+ while (true) {
745
+ const { done, value } = await reader.read();
746
+ if (done) break;
747
+ buffer += decoder.decode(value, { stream: true });
748
+ while (true) {
749
+ const newlinePos = buffer.indexOf("\n");
750
+ if (newlinePos === -1) break;
751
+ const line = buffer.slice(0, newlinePos).replace(/\r$/, "");
752
+ buffer = buffer.slice(newlinePos + 1);
753
+ if (!line || !line.startsWith("data: ")) continue;
754
+ const data = line.slice(6).trim();
755
+ if (data === "[DONE]") return;
756
+ try {
757
+ const json = JSON.parse(data);
758
+ const text = json?.candidates?.[0]?.content?.parts?.[0]?.text;
759
+ if (text) yield text;
760
+ } catch {
761
+ }
762
+ }
763
+ }
764
+ } finally {
765
+ reader.releaseLock();
766
+ }
767
+ }
768
+ };
769
+
770
+ // src/providers/claude-cli.ts
771
+ import { spawn } from "child_process";
772
+ var ClaudeCLIProvider = class {
773
+ projectDir;
774
+ constructor(options = {}) {
775
+ this.projectDir = options.projectDir ?? process.cwd();
776
+ }
777
+ async *generate(prompt, systemPrompt, conversationContext) {
778
+ let fullPrompt = "";
779
+ if (systemPrompt) {
780
+ fullPrompt += `[System Instructions]
781
+ ${systemPrompt}
782
+
783
+ `;
784
+ }
785
+ if (conversationContext) {
786
+ fullPrompt += 'Below is the recent conversation history for context. Respond ONLY to the final user message. Be conversational and concise \u2014 reply directly to the user as a chat participant. Do NOT narrate your thought process, planning steps, or internal reasoning. Do NOT describe actions you would take (e.g. "I should...", "Let me...", "I will..."). Just answer.\n\n';
787
+ fullPrompt += conversationContext;
788
+ fullPrompt += "\n\n---\n\n";
789
+ }
790
+ fullPrompt += prompt;
791
+ const child = spawn("claude", ["--print", "--dangerously-skip-permissions", fullPrompt], {
792
+ cwd: this.projectDir,
793
+ stdio: ["ignore", "pipe", "pipe"],
794
+ shell: true
795
+ });
796
+ let stderr = "";
797
+ child.stderr?.on("data", (chunk) => {
798
+ stderr += chunk.toString();
799
+ });
800
+ const stdout = child.stdout;
801
+ for await (const chunk of stdout) {
802
+ const text = chunk.toString();
803
+ if (text) yield text;
804
+ }
805
+ const exitCode = await new Promise((resolve) => {
806
+ child.on("close", resolve);
807
+ });
808
+ if (exitCode !== 0 && exitCode !== null) {
809
+ if (!stderr.trim()) return;
810
+ throw new Error(`Claude CLI exited with code ${exitCode}: ${stderr.trim()}`);
811
+ }
812
+ }
813
+ };
814
+
571
815
  // src/agent.ts
572
816
  var DEFAULT_MAX_DEPTH = 3;
573
817
  var DEFAULT_CHUNK_BATCH_MS = 200;
@@ -666,10 +910,20 @@ var JaibberAgent = class extends EventEmitter {
666
910
  onTask(handler) {
667
911
  this.taskHandler = handler;
668
912
  }
669
- /** Use a built-in LLM provider. */
670
913
  useProvider(name, options) {
671
- if (name === "anthropic") {
672
- this.provider = new AnthropicProvider(options);
914
+ switch (name) {
915
+ case "anthropic":
916
+ this.provider = new AnthropicProvider(options);
917
+ break;
918
+ case "openai":
919
+ this.provider = new OpenAIProvider(options);
920
+ break;
921
+ case "google":
922
+ this.provider = new GoogleProvider(options);
923
+ break;
924
+ case "claude-cli":
925
+ this.provider = new ClaudeCLIProvider(options);
926
+ break;
673
927
  }
674
928
  }
675
929
  // ── Message handling ────────────────────────────────────────────────
@@ -915,31 +1169,59 @@ REQUIRED:
915
1169
  --password <pass> Jaibber account password
916
1170
  --agent-name <name> Agent display name (used for @mention routing)
917
1171
 
1172
+ PROVIDER (at least one required \u2014 first match wins):
1173
+ --anthropic-key <key> Anthropic API key (Claude)
1174
+ --openai-key <key> OpenAI API key (GPT-4o)
1175
+ --google-key <key> Google AI API key (Gemini)
1176
+ --claude-cli Use local Claude CLI (no API key needed)
1177
+
918
1178
  OPTIONAL:
1179
+ --register Create a new account (instead of logging into an existing one)
1180
+ --create-project <name> Create a new project and join it (prints project ID on start)
919
1181
  --server <url> Server URL (default: https://api.jaibber.com)
920
- --anthropic-key <key> Anthropic API key \u2014 enables built-in Claude provider
921
1182
  --instructions <text> System prompt for the agent
922
1183
  --machine-name <name> Machine identifier shown in presence
923
1184
  --projects <id,id,...> Comma-separated project IDs to join (default: all)
1185
+ --project-dir <path> Working directory for Claude CLI (default: cwd)
924
1186
  --help Show this help message
925
1187
 
926
1188
  EXAMPLES:
927
- # Basic agent with Claude provider
1189
+ # With Anthropic API key
928
1190
  npx @jaibber/sdk \\
929
1191
  --username coding-bot --password s3cret \\
930
1192
  --agent-name "CodingAgent" \\
931
1193
  --anthropic-key sk-ant-api03-...
932
1194
 
933
- # Agent for specific projects with custom instructions
1195
+ # With OpenAI
1196
+ npx @jaibber/sdk \\
1197
+ --username coding-bot --password s3cret \\
1198
+ --agent-name "CodingAgent" \\
1199
+ --openai-key sk-...
1200
+
1201
+ # With local Claude CLI (no API key)
1202
+ npx @jaibber/sdk \\
1203
+ --username coding-bot --password s3cret \\
1204
+ --agent-name "CodingAgent" \\
1205
+ --claude-cli --project-dir /path/to/project
1206
+
1207
+ # Create a new project on first run
934
1208
  npx @jaibber/sdk \\
1209
+ --username coding-bot --password s3cret \\
1210
+ --agent-name "CodingAgent" \\
1211
+ --create-project "my-ubuntu-server" \\
1212
+ --claude-cli
1213
+
1214
+ # Register new account + Gemini
1215
+ npx @jaibber/sdk \\
1216
+ --register \\
935
1217
  --username tester --password p4ss \\
936
1218
  --agent-name "TestBot" \\
937
- --anthropic-key sk-ant-api03-... \\
938
- --instructions "You are a QA engineer. Review code for bugs." \\
939
- --projects "uuid-1,uuid-2"
1219
+ --google-key AIza...
940
1220
 
941
1221
  ENVIRONMENT VARIABLES:
942
1222
  ANTHROPIC_API_KEY Alternative to --anthropic-key
1223
+ OPENAI_API_KEY Alternative to --openai-key
1224
+ GOOGLE_API_KEY Alternative to --google-key
943
1225
  JAIBBER_PASSWORD Alternative to --password
944
1226
  `);
945
1227
  process.exit(0);
@@ -949,8 +1231,14 @@ var password = args["password"] || process.env.JAIBBER_PASSWORD;
949
1231
  var agentName = args["agent-name"];
950
1232
  var serverUrl = args["server"] || "https://api.jaibber.com";
951
1233
  var anthropicKey = args["anthropic-key"] || process.env.ANTHROPIC_API_KEY;
1234
+ var openaiKey = args["openai-key"] || process.env.OPENAI_API_KEY;
1235
+ var googleKey = args["google-key"] || process.env.GOOGLE_API_KEY;
1236
+ var useClaudeCli = args["claude-cli"] === "true";
1237
+ var projectDir = args["project-dir"];
952
1238
  var instructions = args["instructions"];
953
1239
  var machineName = args["machine-name"];
1240
+ var shouldRegister = args["register"] === "true";
1241
+ var createProjectName = args["create-project"];
954
1242
  var projectIds = args["projects"] ? args["projects"].split(",").map((s) => s.trim()) : void 0;
955
1243
  if (!username) {
956
1244
  console.error("Error: --username is required");
@@ -966,20 +1254,60 @@ if (!agentName) {
966
1254
  console.error("Error: --agent-name is required");
967
1255
  process.exit(1);
968
1256
  }
1257
+ if (shouldRegister) {
1258
+ console.log(`[cli] Registering new account "${username}"...`);
1259
+ const client = new JaibberClient(serverUrl);
1260
+ try {
1261
+ await client.register(username, password);
1262
+ console.log(`[cli] Account created successfully.`);
1263
+ } catch (err) {
1264
+ console.error(
1265
+ `[cli] Registration failed: ${err instanceof Error ? err.message : err}`
1266
+ );
1267
+ process.exit(1);
1268
+ }
1269
+ }
1270
+ var resolvedProjectIds = projectIds;
1271
+ if (createProjectName) {
1272
+ console.log(`[cli] Creating project "${createProjectName}"...`);
1273
+ const client = new JaibberClient(serverUrl);
1274
+ try {
1275
+ await client.login(username, password);
1276
+ const project = await client.createProject(createProjectName);
1277
+ console.log(`[cli] Project created: ${project.name}`);
1278
+ console.log(`[cli] Project ID: ${project.id}`);
1279
+ console.log(`[cli] Share this ID with teammates to join the project.`);
1280
+ resolvedProjectIds = [project.id];
1281
+ } catch (err) {
1282
+ console.error(
1283
+ `[cli] Failed to create project: ${err instanceof Error ? err.message : err}`
1284
+ );
1285
+ process.exit(1);
1286
+ }
1287
+ }
969
1288
  var agent = new JaibberAgent({
970
1289
  serverUrl,
971
1290
  credentials: { username, password },
972
1291
  agentName,
973
1292
  agentInstructions: instructions,
974
1293
  machineName,
975
- projectIds
1294
+ projectIds: resolvedProjectIds
976
1295
  });
977
1296
  if (anthropicKey) {
978
1297
  agent.useProvider("anthropic", { apiKey: anthropicKey });
979
- console.log(`[cli] Using Anthropic provider`);
1298
+ console.log(`[cli] Using Anthropic provider (Claude)`);
1299
+ } else if (openaiKey) {
1300
+ agent.useProvider("openai", { apiKey: openaiKey });
1301
+ console.log(`[cli] Using OpenAI provider (GPT-4o)`);
1302
+ } else if (googleKey) {
1303
+ agent.useProvider("google", { apiKey: googleKey });
1304
+ console.log(`[cli] Using Google provider (Gemini)`);
1305
+ } else if (useClaudeCli) {
1306
+ agent.useProvider("claude-cli", { projectDir });
1307
+ console.log(`[cli] Using Claude CLI provider (local auth)`);
980
1308
  } else {
981
1309
  console.log(
982
- "[cli] No --anthropic-key provided. Register a message handler in code, or pass --anthropic-key."
1310
+ "[cli] No provider configured. Pass --anthropic-key, --openai-key, --google-key, or --claude-cli."
983
1311
  );
984
1312
  console.log(
985
1313
  "[cli] Agent will connect but won't respond to messages without a provider."