@jaibber/sdk 0.1.0 → 0.1.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/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`, {
@@ -568,6 +587,211 @@ var AnthropicProvider = class {
568
587
  }
569
588
  };
570
589
 
590
+ // src/providers/openai.ts
591
+ var OPENAI_API_URL = "https://api.openai.com/v1/chat/completions";
592
+ var DEFAULT_MODEL2 = "gpt-4o";
593
+ var DEFAULT_MAX_TOKENS2 = 8192;
594
+ var OpenAIProvider = class {
595
+ apiKey;
596
+ model;
597
+ maxTokens;
598
+ constructor(options) {
599
+ this.apiKey = options.apiKey;
600
+ this.model = options.model ?? DEFAULT_MODEL2;
601
+ this.maxTokens = options.maxTokens ?? DEFAULT_MAX_TOKENS2;
602
+ }
603
+ async *generate(prompt, systemPrompt, conversationContext) {
604
+ let fullText = "";
605
+ if (conversationContext) {
606
+ 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';
607
+ fullText += conversationContext;
608
+ fullText += "\n\n---\n\n";
609
+ }
610
+ fullText += prompt;
611
+ const messages = [];
612
+ if (systemPrompt) {
613
+ messages.push({ role: "system", content: systemPrompt });
614
+ }
615
+ messages.push({ role: "user", content: fullText });
616
+ const response = await fetch(OPENAI_API_URL, {
617
+ method: "POST",
618
+ headers: {
619
+ Authorization: `Bearer ${this.apiKey}`,
620
+ "Content-Type": "application/json"
621
+ },
622
+ body: JSON.stringify({
623
+ model: this.model,
624
+ max_tokens: this.maxTokens,
625
+ stream: true,
626
+ messages
627
+ })
628
+ });
629
+ if (!response.ok) {
630
+ const text = await response.text();
631
+ const status = response.status;
632
+ if (status === 401) {
633
+ throw new Error("Invalid OpenAI API key. Check your API key.");
634
+ } else if (status === 429) {
635
+ throw new Error("OpenAI API rate limit exceeded. Please wait and try again.");
636
+ }
637
+ throw new Error(`OpenAI API returned ${status}: ${text}`);
638
+ }
639
+ if (!response.body) {
640
+ throw new Error("OpenAI API returned no response body");
641
+ }
642
+ const reader = response.body.getReader();
643
+ const decoder = new TextDecoder();
644
+ let buffer = "";
645
+ try {
646
+ while (true) {
647
+ const { done, value } = await reader.read();
648
+ if (done) break;
649
+ buffer += decoder.decode(value, { stream: true });
650
+ while (true) {
651
+ const newlinePos = buffer.indexOf("\n");
652
+ if (newlinePos === -1) break;
653
+ const line = buffer.slice(0, newlinePos).replace(/\r$/, "");
654
+ buffer = buffer.slice(newlinePos + 1);
655
+ if (!line || !line.startsWith("data: ")) continue;
656
+ const data = line.slice(6).trim();
657
+ if (data === "[DONE]") return;
658
+ try {
659
+ const json = JSON.parse(data);
660
+ const content = json?.choices?.[0]?.delta?.content;
661
+ if (content) yield content;
662
+ } catch {
663
+ }
664
+ }
665
+ }
666
+ } finally {
667
+ reader.releaseLock();
668
+ }
669
+ }
670
+ };
671
+
672
+ // src/providers/google.ts
673
+ var DEFAULT_MODEL3 = "gemini-2.0-flash";
674
+ var DEFAULT_MAX_TOKENS3 = 8192;
675
+ var GoogleProvider = class {
676
+ apiKey;
677
+ model;
678
+ maxTokens;
679
+ constructor(options) {
680
+ this.apiKey = options.apiKey;
681
+ this.model = options.model ?? DEFAULT_MODEL3;
682
+ this.maxTokens = options.maxTokens ?? DEFAULT_MAX_TOKENS3;
683
+ }
684
+ async *generate(prompt, systemPrompt, conversationContext) {
685
+ let fullText = "";
686
+ if (conversationContext) {
687
+ 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';
688
+ fullText += conversationContext;
689
+ fullText += "\n\n---\n\n";
690
+ }
691
+ fullText += prompt;
692
+ const url = `https://generativelanguage.googleapis.com/v1beta/models/${this.model}:streamGenerateContent?alt=sse&key=${this.apiKey}`;
693
+ const body = {
694
+ contents: [{ parts: [{ text: fullText }] }],
695
+ generationConfig: {
696
+ maxOutputTokens: this.maxTokens
697
+ }
698
+ };
699
+ if (systemPrompt) {
700
+ body.systemInstruction = { parts: [{ text: systemPrompt }] };
701
+ }
702
+ const response = await fetch(url, {
703
+ method: "POST",
704
+ headers: { "Content-Type": "application/json" },
705
+ body: JSON.stringify(body)
706
+ });
707
+ if (!response.ok) {
708
+ const text = await response.text();
709
+ const status = response.status;
710
+ if (status === 400 || status === 403) {
711
+ throw new Error(`Google AI API error (${status}): ${text}`);
712
+ } else if (status === 429) {
713
+ throw new Error("Google AI API rate limit exceeded. Please wait and try again.");
714
+ }
715
+ throw new Error(`Google AI API returned ${status}: ${text}`);
716
+ }
717
+ if (!response.body) {
718
+ throw new Error("Google AI API returned no response body");
719
+ }
720
+ const reader = response.body.getReader();
721
+ const decoder = new TextDecoder();
722
+ let buffer = "";
723
+ try {
724
+ while (true) {
725
+ const { done, value } = await reader.read();
726
+ if (done) break;
727
+ buffer += decoder.decode(value, { stream: true });
728
+ while (true) {
729
+ const newlinePos = buffer.indexOf("\n");
730
+ if (newlinePos === -1) break;
731
+ const line = buffer.slice(0, newlinePos).replace(/\r$/, "");
732
+ buffer = buffer.slice(newlinePos + 1);
733
+ if (!line || !line.startsWith("data: ")) continue;
734
+ const data = line.slice(6).trim();
735
+ if (data === "[DONE]") return;
736
+ try {
737
+ const json = JSON.parse(data);
738
+ const text = json?.candidates?.[0]?.content?.parts?.[0]?.text;
739
+ if (text) yield text;
740
+ } catch {
741
+ }
742
+ }
743
+ }
744
+ } finally {
745
+ reader.releaseLock();
746
+ }
747
+ }
748
+ };
749
+
750
+ // src/providers/claude-cli.ts
751
+ import { spawn } from "child_process";
752
+ var ClaudeCLIProvider = class {
753
+ projectDir;
754
+ constructor(options = {}) {
755
+ this.projectDir = options.projectDir ?? process.cwd();
756
+ }
757
+ async *generate(prompt, systemPrompt, conversationContext) {
758
+ let fullPrompt = "";
759
+ if (systemPrompt) {
760
+ fullPrompt += `[System Instructions]
761
+ ${systemPrompt}
762
+
763
+ `;
764
+ }
765
+ if (conversationContext) {
766
+ 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';
767
+ fullPrompt += conversationContext;
768
+ fullPrompt += "\n\n---\n\n";
769
+ }
770
+ fullPrompt += prompt;
771
+ const child = spawn("claude", ["--print", "--dangerously-skip-permissions", fullPrompt], {
772
+ cwd: this.projectDir,
773
+ stdio: ["ignore", "pipe", "pipe"],
774
+ shell: true
775
+ });
776
+ let stderr = "";
777
+ child.stderr?.on("data", (chunk) => {
778
+ stderr += chunk.toString();
779
+ });
780
+ const stdout = child.stdout;
781
+ for await (const chunk of stdout) {
782
+ const text = chunk.toString();
783
+ if (text) yield text;
784
+ }
785
+ const exitCode = await new Promise((resolve) => {
786
+ child.on("close", resolve);
787
+ });
788
+ if (exitCode !== 0 && exitCode !== null) {
789
+ if (!stderr.trim()) return;
790
+ throw new Error(`Claude CLI exited with code ${exitCode}: ${stderr.trim()}`);
791
+ }
792
+ }
793
+ };
794
+
571
795
  // src/agent.ts
572
796
  var DEFAULT_MAX_DEPTH = 3;
573
797
  var DEFAULT_CHUNK_BATCH_MS = 200;
@@ -666,10 +890,20 @@ var JaibberAgent = class extends EventEmitter {
666
890
  onTask(handler) {
667
891
  this.taskHandler = handler;
668
892
  }
669
- /** Use a built-in LLM provider. */
670
893
  useProvider(name, options) {
671
- if (name === "anthropic") {
672
- this.provider = new AnthropicProvider(options);
894
+ switch (name) {
895
+ case "anthropic":
896
+ this.provider = new AnthropicProvider(options);
897
+ break;
898
+ case "openai":
899
+ this.provider = new OpenAIProvider(options);
900
+ break;
901
+ case "google":
902
+ this.provider = new GoogleProvider(options);
903
+ break;
904
+ case "claude-cli":
905
+ this.provider = new ClaudeCLIProvider(options);
906
+ break;
673
907
  }
674
908
  }
675
909
  // ── Message handling ────────────────────────────────────────────────
@@ -915,31 +1149,51 @@ REQUIRED:
915
1149
  --password <pass> Jaibber account password
916
1150
  --agent-name <name> Agent display name (used for @mention routing)
917
1151
 
1152
+ PROVIDER (at least one required \u2014 first match wins):
1153
+ --anthropic-key <key> Anthropic API key (Claude)
1154
+ --openai-key <key> OpenAI API key (GPT-4o)
1155
+ --google-key <key> Google AI API key (Gemini)
1156
+ --claude-cli Use local Claude CLI (no API key needed)
1157
+
918
1158
  OPTIONAL:
1159
+ --register Create a new account (instead of logging into an existing one)
919
1160
  --server <url> Server URL (default: https://api.jaibber.com)
920
- --anthropic-key <key> Anthropic API key \u2014 enables built-in Claude provider
921
1161
  --instructions <text> System prompt for the agent
922
1162
  --machine-name <name> Machine identifier shown in presence
923
1163
  --projects <id,id,...> Comma-separated project IDs to join (default: all)
1164
+ --project-dir <path> Working directory for Claude CLI (default: cwd)
924
1165
  --help Show this help message
925
1166
 
926
1167
  EXAMPLES:
927
- # Basic agent with Claude provider
1168
+ # With Anthropic API key
928
1169
  npx @jaibber/sdk \\
929
1170
  --username coding-bot --password s3cret \\
930
1171
  --agent-name "CodingAgent" \\
931
1172
  --anthropic-key sk-ant-api03-...
932
1173
 
933
- # Agent for specific projects with custom instructions
1174
+ # With OpenAI
934
1175
  npx @jaibber/sdk \\
1176
+ --username coding-bot --password s3cret \\
1177
+ --agent-name "CodingAgent" \\
1178
+ --openai-key sk-...
1179
+
1180
+ # With local Claude CLI (no API key)
1181
+ npx @jaibber/sdk \\
1182
+ --username coding-bot --password s3cret \\
1183
+ --agent-name "CodingAgent" \\
1184
+ --claude-cli --project-dir /path/to/project
1185
+
1186
+ # Register new account + Gemini
1187
+ npx @jaibber/sdk \\
1188
+ --register \\
935
1189
  --username tester --password p4ss \\
936
1190
  --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"
1191
+ --google-key AIza...
940
1192
 
941
1193
  ENVIRONMENT VARIABLES:
942
1194
  ANTHROPIC_API_KEY Alternative to --anthropic-key
1195
+ OPENAI_API_KEY Alternative to --openai-key
1196
+ GOOGLE_API_KEY Alternative to --google-key
943
1197
  JAIBBER_PASSWORD Alternative to --password
944
1198
  `);
945
1199
  process.exit(0);
@@ -949,8 +1203,13 @@ var password = args["password"] || process.env.JAIBBER_PASSWORD;
949
1203
  var agentName = args["agent-name"];
950
1204
  var serverUrl = args["server"] || "https://api.jaibber.com";
951
1205
  var anthropicKey = args["anthropic-key"] || process.env.ANTHROPIC_API_KEY;
1206
+ var openaiKey = args["openai-key"] || process.env.OPENAI_API_KEY;
1207
+ var googleKey = args["google-key"] || process.env.GOOGLE_API_KEY;
1208
+ var useClaudeCli = args["claude-cli"] === "true";
1209
+ var projectDir = args["project-dir"];
952
1210
  var instructions = args["instructions"];
953
1211
  var machineName = args["machine-name"];
1212
+ var shouldRegister = args["register"] === "true";
954
1213
  var projectIds = args["projects"] ? args["projects"].split(",").map((s) => s.trim()) : void 0;
955
1214
  if (!username) {
956
1215
  console.error("Error: --username is required");
@@ -966,6 +1225,19 @@ if (!agentName) {
966
1225
  console.error("Error: --agent-name is required");
967
1226
  process.exit(1);
968
1227
  }
1228
+ if (shouldRegister) {
1229
+ console.log(`[cli] Registering new account "${username}"...`);
1230
+ const client = new JaibberClient(serverUrl);
1231
+ try {
1232
+ await client.register(username, password);
1233
+ console.log(`[cli] Account created successfully.`);
1234
+ } catch (err) {
1235
+ console.error(
1236
+ `[cli] Registration failed: ${err instanceof Error ? err.message : err}`
1237
+ );
1238
+ process.exit(1);
1239
+ }
1240
+ }
969
1241
  var agent = new JaibberAgent({
970
1242
  serverUrl,
971
1243
  credentials: { username, password },
@@ -976,10 +1248,19 @@ var agent = new JaibberAgent({
976
1248
  });
977
1249
  if (anthropicKey) {
978
1250
  agent.useProvider("anthropic", { apiKey: anthropicKey });
979
- console.log(`[cli] Using Anthropic provider`);
1251
+ console.log(`[cli] Using Anthropic provider (Claude)`);
1252
+ } else if (openaiKey) {
1253
+ agent.useProvider("openai", { apiKey: openaiKey });
1254
+ console.log(`[cli] Using OpenAI provider (GPT-4o)`);
1255
+ } else if (googleKey) {
1256
+ agent.useProvider("google", { apiKey: googleKey });
1257
+ console.log(`[cli] Using Google provider (Gemini)`);
1258
+ } else if (useClaudeCli) {
1259
+ agent.useProvider("claude-cli", { projectDir });
1260
+ console.log(`[cli] Using Claude CLI provider (local auth)`);
980
1261
  } else {
981
1262
  console.log(
982
- "[cli] No --anthropic-key provided. Register a message handler in code, or pass --anthropic-key."
1263
+ "[cli] No provider configured. Pass --anthropic-key, --openai-key, --google-key, or --claude-cli."
983
1264
  );
984
1265
  console.log(
985
1266
  "[cli] Agent will connect but won't respond to messages without a provider."