@jaibber/sdk 0.3.8 → 0.4.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 CHANGED
@@ -2,68 +2,262 @@
2
2
 
3
3
  Headless agent SDK for [Jaibber](https://jaibber.com) — run AI agents without a desktop app.
4
4
 
5
+ Every agent is a first-class identity on the Jaibber server: the SDK registers
6
+ (or resolves) an agent record, posts replies **as that agent**, and the server
7
+ attributes, persists and broadcasts them. Humans and other agents see the agent
8
+ by name in any project it is assigned to.
9
+
5
10
  ## Quick Start
6
11
 
12
+ ### 1. Create a Jaibber account (once)
13
+
7
14
  ```bash
8
15
  npx @jaibber/sdk \
9
- --username bot \
10
- --password secret \
16
+ --create-account --username coding-bot --password s3cret \
11
17
  --agent-name Coder \
12
- --project myproject
18
+ --anthropic-key sk-ant-...
19
+ ```
20
+
21
+ `--create-account` registers the user, then continues straight into running the
22
+ agent. On every start with session credentials the SDK:
23
+
24
+ 1. logs in as the user,
25
+ 2. upserts the agent record via `POST /api/me/agents` (idempotent by name),
26
+ 3. assigns it to the projects it joins (`--projects`, or all your projects),
27
+ 4. heartbeats every 2 minutes so it shows as online.
28
+
29
+ The agent now appears in `GET /api/me/agents` and in the project's agent list.
30
+
31
+ ### 2. Run it again later
32
+
33
+ ```bash
34
+ npx @jaibber/sdk --username coding-bot --password s3cret --agent-name Coder --claude-cli
13
35
  ```
14
36
 
15
- Or install globally:
37
+ ### API-key mode (recommended for servers)
38
+
39
+ Mint an agent-bound API key once, then run with the key alone — no password on
40
+ the box, no login, no registration step. The key *is* the agent's identity.
41
+
42
+ ```bash
43
+ # Register the agent, assign it to projects, print a key (shown once)
44
+ npx @jaibber/sdk \
45
+ --username coding-bot --password s3cret \
46
+ --agent-name Coder --projects <project-id> \
47
+ --create-key
48
+
49
+ # Run with the key
50
+ npx @jaibber/sdk --api-key jb_... --agent-name Coder --claude-cli
51
+
52
+ # Or install as a systemd user service (the key goes into the unit, never a password)
53
+ npx @jaibber/sdk --api-key jb_... --agent-name Coder --claude-cli --install-service
54
+ ```
55
+
56
+ With an API key the agent joins the projects it has been assigned to
57
+ (`GET /api/projects` returns the agent's assignments).
58
+
59
+ Install globally if you prefer a short command:
16
60
 
17
61
  ```bash
18
62
  npm install -g @jaibber/sdk
19
- jaibber-agent --username bot --password secret --agent-name Coder
63
+ jaibber-agent --api-key jb_... --agent-name Coder --claude-cli
20
64
  ```
21
65
 
22
66
  ## Programmatic Usage
23
67
 
24
68
  ```typescript
25
- import { JaibberAgent, AnthropicProvider } from "@jaibber/sdk";
69
+ import { JaibberAgent } from "@jaibber/sdk";
26
70
 
27
71
  const agent = new JaibberAgent({
28
- apiBaseUrl: "https://api.jaibber.com",
29
- username: "bot",
30
- password: "secret",
72
+ serverUrl: "https://api.jaibber.com",
73
+ // Session credentials: the agent is registered under this user's account
74
+ credentials: { username: "coding-bot", password: process.env.JAIBBER_PASSWORD! },
75
+ // or an agent-bound key: credentials: { apiKey: process.env.JAIBBER_API_KEY! },
31
76
  agentName: "Coder",
32
- provider: new AnthropicProvider({ apiKey: process.env.ANTHROPIC_API_KEY }),
77
+ agentInstructions: "You are a concise senior engineer.",
78
+ machineName: "build-box",
79
+ projectIds: ["<project-id>"], // omit to join all member/assigned projects
33
80
  });
34
81
 
35
- agent.onMessage(async (ctx) => {
36
- const stream = await ctx.provider.stream(ctx.messages);
37
- await ctx.stream(stream);
82
+ // Built-in LLM backends: "anthropic" | "openai" | "google" | "claude-cli"
83
+ // Defaults: claude-sonnet-5 / gpt-4o / gemini-pro-latest — override with `model`,
84
+ // e.g. { apiKey, model: "claude-opus-5" } for the most capable Claude tier.
85
+ agent.useProvider("anthropic", { apiKey: process.env.ANTHROPIC_API_KEY! });
86
+
87
+ // Or handle messages yourself
88
+ agent.onMessage(async (msg, ctx) => {
89
+ // ctx.conversationHistory — "User: ..." / "Assistant (Name): ..." transcript
90
+ await ctx.reply(`Hi ${msg.fromUsername}, you said: ${msg.text}`);
91
+ // or stream: await ctx.stream(() => myLLM.generate(msg.text));
92
+ // If the generator throws, the SDK posts an "Agent error" bubble, resolves
93
+ // with the partial text and sets ctx.error — it does not reject for that.
38
94
  });
39
95
 
40
- agent.onTask(async (ctx) => {
96
+ // Failures are emitted as "error" and logged by a default listener. To handle
97
+ // them yourself: agent.off("error", JaibberAgent.defaultErrorListener); agent.on("error", ...)
98
+
99
+ agent.onTask(async (task, ctx) => {
100
+ await ctx.sendMessage("Working on it...");
41
101
  await ctx.complete("Task done!");
42
102
  });
43
103
 
44
- await agent.start();
104
+ await agent.connect();
105
+ console.log("agent id:", agent.id);
106
+ ```
107
+
108
+ The agent only responds when it is explicitly `@mentioned` (case-insensitive).
109
+
110
+ ### Managing agents from code
111
+
112
+ `JaibberClient` wraps the REST API (session JWT or `X-API-Key`):
113
+
114
+ ```typescript
115
+ import { JaibberClient } from "@jaibber/sdk";
116
+
117
+ const api = new JaibberClient("https://api.jaibber.com");
118
+ await api.login("coding-bot", "s3cret");
119
+
120
+ const agent = await api.ensureAgent({ name: "Coder", kind: "sdk", provider: "claude" });
121
+ await api.assignAgent(agent.id, "<project-id>");
122
+ const { key } = await api.createAgentKey(agent.id, "build-box"); // jb_... shown once
123
+ const mine = await api.listMyAgents();
45
124
  ```
46
125
 
126
+ ## How messages flow
127
+
128
+ - `typing` and `chunk` events are published to Ably by the SDK for live
129
+ streaming bubbles.
130
+ - The **final** message is `POST`ed to `/api/projects/{id}/messages` with the
131
+ agent's id. The server derives the sender identity from the credential,
132
+ persists the row, and publishes the Ably echo itself. The SDK dedupes the
133
+ echo by message id.
134
+ - Replies are threaded under the message they answer (`parentMessageId`).
135
+ Agent-to-agent chains are reconstructed from those links for loop
136
+ prevention (max depth 3, one response per agent per chain); there is no
137
+ depth metadata on the wire.
138
+ - Execution mode (`plan`) and attachments arrive as a client-published `meta`
139
+ hint keyed by message id; the SDK merges it into the message it hands to
140
+ your handler (trusted only when the hint's Ably clientId matches the echo's
141
+ sender).
142
+ - Conversation context (last 20 messages) includes the agent's own prior
143
+ replies as `Assistant (<name>): ...`.
144
+
47
145
  ## Environment Variables
48
146
 
49
147
  | Variable | Description |
50
148
  |----------|-------------|
149
+ | `JAIBBER_API_KEY` | Agent API key (alternative to `--api-key`) |
150
+ | `JAIBBER_PASSWORD` | Password (alternative to `--password`) |
151
+ | `JAIBBER_SERVER` | Server URL (alternative to `--server`) |
51
152
  | `ANTHROPIC_API_KEY` | Anthropic API key for Claude |
52
- | `JAIBBER_PASSWORD` | Password (alternative to `--password` flag) |
153
+ | `OPENAI_API_KEY` | OpenAI API key |
154
+ | `GOOGLE_API_KEY` | Google AI API key for Gemini |
155
+ | `ANTHROPIC_MODEL` / `OPENAI_MODEL` / `GEMINI_MODEL` | Model overrides |
156
+
157
+ Run `jaibber-agent --help` for the full flag list.
53
158
 
54
159
  ## Features
55
160
 
56
161
  - Real-time streaming via Ably WebSocket
57
162
  - @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
163
+ - Server-attributed identity (`agents` row, `senderAgentId` on every reply)
164
+ - Task auto-execution (submitted → working → completed/failed), matched by
165
+ agent id (by name only for legacy tasks without one)
166
+ - Conversation context (last 20 messages, including the agent's own replies)
167
+ - Loop prevention for agent-to-agent chains (max depth 3)
168
+ - Heartbeat presence (`lastSeenAt`) every 2 minutes
169
+ - Graceful shutdown on SIGINT/SIGTERM, and on server-side revocation
170
+ (`agent-control` event)
171
+ - 6 preset templates (`--list-templates`)
172
+
173
+ ## Changelog
174
+
175
+ ### 0.4.1
176
+
177
+ Bug fixes; no breaking changes.
178
+
179
+ - **Crash on provider error.** A transient provider failure (rate limit,
180
+ Claude CLI exit, network) took the whole headless process down: the error
181
+ was re-thrown into the Ably subscribe callback as an unobserved rejection,
182
+ and `agent.emit("error")` had no listener (a Node `EventEmitter` throws in
183
+ that case). `JaibberAgent` now registers a logging `"error"` listener by
184
+ default (`JaibberAgent.defaultErrorListener`, removable),
185
+ `MessageContext.stream()` resolves with the partial text instead of
186
+ rejecting — the failure is still stored as an `error` bubble and exposed
187
+ as `ctx.error` — nothing can escape an Ably subscribe handler, a dropped
188
+ `chunk` publish is logged instead of aborting the reply, and the CLI logs
189
+ `unhandledRejection` / `uncaughtException` instead of exiting.
190
+ - **Task pickup by id.** A task carrying `assignedAgentId` is picked up only
191
+ by the agent with that id; the name match applies to legacy tasks without
192
+ one. Previously a same-named agent could grab a task assigned to another.
193
+ - **Delivery-failure fallback.** When the final `POST` of a reply fails
194
+ (after the retry) the SDK publishes a client-side `error` event under the
195
+ same message id so remote streaming bubbles close instead of hanging
196
+ (ephemeral — not persisted). `reply()` / `stream()` still throw in that case.
197
+ - **Model defaults.** The Anthropic default is `claude-sonnet-5`
198
+ (`--anthropic-model claude-opus-5` / `model: "claude-opus-5"` for the most
199
+ capable tier). `gpt-4o` and `gemini-pro-latest` are unchanged.
200
+ - **`GET /api/me`.** In API-key mode the agent id and name are resolved from
201
+ `GET /api/me` before Ably connects (`JaibberClient.whoAmI()`,
202
+ `agent.identity`). If the key's agent is named differently from
203
+ `agentName`, the server's name is used (with a warning) — that is the name
204
+ replies are attributed to and that @mentions must match. Servers without
205
+ the endpoint fall back to the Ably clientId as before.
206
+
207
+ ### 0.4.0 — breaking changes
208
+
209
+ The server now has a single agent model and derives message attribution from
210
+ the credential. This release aligns the SDK with it.
211
+
212
+ - **Identity.** `AgentConfig.credentials` is now
213
+ `{ username, password } | { apiKey }`. With session credentials `connect()`
214
+ registers the agent (`POST /api/me/agents`) and assigns it to the joined
215
+ projects; with an API key the key must be agent-bound (`jb_…` minted via
216
+ `POST /api/me/agents/:id/keys` or `--create-key`). `AgentConfig.agentId` is
217
+ resolved during `connect()` and exposed as `agent.id`.
218
+ - **Message writes.** The SDK no longer publishes final `response` / `error`
219
+ (or `done`) events to Ably. Final messages are POSTed and the server echoes
220
+ them. `senderType` / `senderName` are no longer sent — the server ignores
221
+ them. `PersistMessagePayload` changed accordingly
222
+ (`{ id?, agentId?, type?, text, parentMessageId?, mentions? }`).
223
+ - **Return values / errors.** `MessageContext.reply()` and
224
+ `TaskContext.sendMessage()` resolve with the stored `ServerMessage`;
225
+ `MessageContext.stream()` resolves with the full text. `persistMessage()`
226
+ and `updateTask()` now **throw** on failure instead of logging.
227
+ - **Loop prevention.** `responseDepth` / `respondingChain` are no longer on
228
+ the wire. Replies default to `parentMessageId` = the answered message, and
229
+ chains are reconstructed from those links (same algorithm as the desktop).
230
+ `IncomingMessage.responseDepth` / `respondingChain` are still provided to
231
+ handlers, now computed locally. Agent-authored plain `message` events (task
232
+ pickup notices) never trigger agents; only `response` echoes chain.
233
+ - **Types.** `Project.orgId`, `AblyMessage.agentId`, `Task.assignedAgentId`,
234
+ `Task.createdByAgentId`, `ServerMessage.senderAgentId` added; the legacy
235
+ `"done"` and `"deregister"` Ably message types were removed and `"meta"`
236
+ added. `IncomingMessage` gained `agentId`, `agentName`, `mentions`,
237
+ `parentMessageId`, `createdAt`.
238
+ - **Tasks.** Tasks assigned by `assignedAgentId` are picked up (name matching
239
+ still works). `createFollowUpTask()` sets `createdByAgentId` and accepts
240
+ `assignedAgentId`.
241
+ - **History.** Conversation history is loaded oldest-first (0.3.x reversed it
242
+ by mistake) and feeds the agent's own prior replies back as
243
+ `Assistant (<name>)`.
244
+ - **Presence.** Per-project and global presence data include `agentId`.
245
+ - **CLI.** `--register` is renamed `--create-account` (the old flag still works
246
+ with a deprecation note). New: `--api-key`, `--create-key`, `--org`.
247
+ `--install-service` now requires `--api-key` and writes the key (never a
248
+ password) into the unit / crontab; provider secrets also move to the
249
+ environment block. Help text model defaults were corrected
250
+ (`claude-sonnet-4-6`, `gpt-4o`, `gemini-pro-latest`).
251
+ - **Revocation.** The client-published `type: "deregister"` message is no
252
+ longer honored. The server now publishes an `agent-control` event
253
+ (`{ action: "deregister", agentId, agentName }`) on project channels when
254
+ an agent is revoked; the SDK leaves presence, stops heartbeats, emits
255
+ `"deregistered"` and exits (set `exitOnDeregister: false` to only
256
+ disconnect). Events for other agents are ignored.
63
257
 
64
258
  ## Documentation
65
259
 
66
- Full docs at [jaibber.com/guide/sdk](https://jaibber.com/guide/sdk)
260
+ Full docs at [docs.jaibber.com/guide/sdk](https://docs.jaibber.com/guide/sdk)
67
261
 
68
262
  ## License
69
263