@ravi-os/sdk 0.2.1 → 0.260519.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 CHANGED
@@ -1,11 +1,44 @@
1
1
  # @ravi-os/sdk
2
2
 
3
- Type-safe TypeScript client for the Ravi SDK gateway.
3
+ Type-safe TypeScript SDK for controlling a Ravi runtime through the authenticated
4
+ SDK gateway.
4
5
 
5
- `RaviClient` is generated from Ravi's decorated CLI registry, so the SDK mirrors
6
- the same command surface exposed by the gateway. The generated client stays thin:
7
- it builds a flat request body and delegates auth, validation, scope checks, audit,
8
- and HTTP details to a transport.
6
+ Ravi is not just a model wrapper. It is a local-first runtime for long-lived
7
+ agents: sessions, tasks, contacts, artifacts, routes, events, permissions, and
8
+ audit all live behind one command registry. `@ravi-os/sdk` turns that registry
9
+ into a typed client you can use from apps, dashboards, browser extensions,
10
+ workers, tests, and internal tools.
11
+
12
+ ```ts
13
+ import { RaviClient, createHttpTransport } from "@ravi-os/sdk";
14
+
15
+ const ravi = new RaviClient(
16
+ createHttpTransport({
17
+ baseUrl: "http://127.0.0.1:7777",
18
+ contextKey: process.env.RAVI_CONTEXT_KEY!,
19
+ }),
20
+ );
21
+
22
+ const sessions = await ravi.sessions.list({ live: true, limit: "20" });
23
+ const reply = await ravi.sessions.send("main", "Summarize the current work.", {
24
+ wait: true,
25
+ });
26
+ ```
27
+
28
+ ## Why This Exists
29
+
30
+ Use the SDK when you need a programmatic control plane for Ravi:
31
+
32
+ - Build a dashboard that reads sessions, tasks, contacts, and runtime events.
33
+ - Let a browser extension talk to the local Ravi daemon without shelling out.
34
+ - Drive agents from tests or internal automation.
35
+ - Stream live task/session/event updates into another UI.
36
+ - Write a custom app while keeping auth, permissions, validation, and audit in
37
+ Ravi instead of duplicating them.
38
+
39
+ The package is generated from Ravi's decorated CLI registry. If a command exists
40
+ in the registry, the SDK gets the same shape, names, args, options, and return
41
+ typing.
9
42
 
10
43
  ## Install
11
44
 
@@ -13,102 +46,152 @@ and HTTP details to a transport.
13
46
  bun add @ravi-os/sdk
14
47
  ```
15
48
 
16
- The package is ESM-only and expects a runtime with `fetch` available. That means
17
- modern browsers, Node 18+, Bun, Deno, and edge runtimes work with the HTTP
18
- transport.
49
+ The package is ESM-only and works anywhere `fetch` is available: Bun, Node 18+,
50
+ modern browsers, Deno, and edge runtimes.
19
51
 
20
- ## Enable the Gateway
52
+ ## Start The Ravi Gateway
21
53
 
22
- The SDK talks to Ravi's HTTP server. The daemon only starts that server when an
23
- HTTP port is configured:
54
+ The SDK talks to Ravi's HTTP gateway. Enable it on the daemon host:
24
55
 
25
56
  ```bash
26
57
  RAVI_HTTP_PORT=7777
27
58
  RAVI_HTTP_HOST=127.0.0.1
59
+ ravi daemon start
60
+ ```
61
+
62
+ The gateway is mounted under:
63
+
64
+ ```text
65
+ http://127.0.0.1:7777/api/v1/*
28
66
  ```
29
67
 
30
- The SDK gateway is mounted under `/api/v1/*` on the same listener as webhooks.
31
- Binding to a non-loopback host requires `RAVI_GATEWAY_NETWORK_AUTHORIZED=1`.
32
- Set `RAVI_SDK_GATEWAY_DISABLE=1` to disable SDK routes while leaving the HTTP
33
- server available for other webhook handlers.
68
+ By default Ravi is local-only. If you bind the gateway to a non-loopback host,
69
+ Ravi requires:
34
70
 
35
- ## Auth
71
+ ```bash
72
+ RAVI_GATEWAY_NETWORK_AUTHORIZED=1
73
+ ```
36
74
 
37
- Non-open routes require a runtime context key (`rctx_*`) sent as:
75
+ To keep the HTTP server available for webhooks while disabling SDK routes:
38
76
 
39
- ```text
40
- Authorization: Bearer <rctx_key>
77
+ ```bash
78
+ RAVI_SDK_GATEWAY_DISABLE=1
41
79
  ```
42
80
 
43
- Bootstrap the first admin key on the daemon host:
81
+ ## Create A Context Key
82
+
83
+ Most SDK routes require a runtime context key (`rctx_*`) in the bearer auth
84
+ header. Bootstrap the first admin key on the daemon machine:
44
85
 
45
86
  ```bash
46
87
  ravi daemon init-admin-key
47
88
  ```
48
89
 
49
- For apps, issue scoped child keys instead of shipping the admin key:
90
+ For apps, issue a narrow child key instead of shipping the admin key:
50
91
 
51
92
  ```bash
52
93
  ravi context issue dashboard \
53
94
  --ttl 2h \
54
- --allow view:system:events,view:system:tasks \
95
+ --allow view:system:events,view:system:tasks,access:session:main \
55
96
  --json
56
97
  ```
57
98
 
58
- ## Basic Client
99
+ `createHttpTransport` sends the key as `Authorization: Bearer <rctx_key>`.
100
+
101
+ ## Create A Client
59
102
 
60
103
  ```ts
61
104
  import { RaviClient, createHttpTransport } from "@ravi-os/sdk";
62
105
 
63
- const client = new RaviClient(
64
- createHttpTransport({
65
- baseUrl: "http://127.0.0.1:7777",
66
- contextKey: process.env.RAVI_CONTEXT_KEY!,
67
- timeoutMs: 10_000,
68
- }),
69
- );
70
-
71
- const agents = await client.agents.list();
72
- const route = await client.instances.routes.add(
73
- "main",
74
- "group:120363428558776322",
75
- "ravi-web",
76
- { channel: "whatsapp", session: "ravi-web" },
77
- );
106
+ export function createRaviClient() {
107
+ return new RaviClient(
108
+ createHttpTransport({
109
+ baseUrl: process.env.RAVI_BASE_URL ?? "http://127.0.0.1:7777",
110
+ contextKey: process.env.RAVI_CONTEXT_KEY!,
111
+ timeoutMs: 10_000,
112
+ }),
113
+ );
114
+ }
78
115
  ```
79
116
 
80
- Generated method names are camel-cased. For example:
117
+ Deep imports are available when you want smaller bundles:
81
118
 
82
- - `ravi daemon init-admin-key` becomes `client.daemon.initAdminKey()`
83
- - `ravi instances routes add` becomes `client.instances.routes.add(...)`
84
- - `ravi sdk client check` becomes `client.sdk.client.check()`
119
+ ```ts
120
+ import { RaviClient } from "@ravi-os/sdk/client";
121
+ import { createHttpTransport } from "@ravi-os/sdk/transport/http";
122
+ ```
85
123
 
86
- ## Request Shape
124
+ ## Examples
87
125
 
88
- Every command call maps to:
126
+ ### Read Runtime State
89
127
 
90
- ```text
91
- POST /api/v1/<group-segments>/<command>
128
+ ```ts
129
+ const ravi = createRaviClient();
130
+
131
+ const agents = await ravi.agents.list({ limit: "50" });
132
+ const sessions = await ravi.sessions.list({ live: true, limit: "25" });
133
+ const recentTasks = await ravi.tasks.list({
134
+ status: "running",
135
+ limit: "10",
136
+ });
92
137
  ```
93
138
 
94
- The JSON body is flat. Positional arguments and options are merged at the top
95
- level:
139
+ ### Manage Agents
96
140
 
97
- ```json
98
- {
99
- "name": "main",
100
- "pattern": "group:120363428558776322",
101
- "agent": "ravi-web",
102
- "channel": "whatsapp",
103
- "session": "ravi-web"
104
- }
141
+ ```ts
142
+ // List all agents
143
+ const agents = await ravi.agents.list({ limit: "50" });
144
+
145
+ // Create a new agent rooted at a workspace directory
146
+ await ravi.agents.create("support", "/home/luis/ravi/support");
147
+
148
+ // Inspect and tune
149
+ await ravi.agents.show("support");
150
+ await ravi.agents.set("support", "model", "claude-opus-4-7");
151
+ await ravi.agents.debounce("support", "3000"); // ms
152
+
153
+ // Inspect or reset the agent's primary session
154
+ await ravi.agents.session("support");
155
+ await ravi.agents.reset("support");
156
+
157
+ // Remove an agent permanently
158
+ await ravi.agents.delete("support");
105
159
  ```
106
160
 
107
- Do not wrap inputs as `{ "args": ..., "options": ... }`.
161
+ ### Drive Sessions
162
+
163
+ ```ts
164
+ // List sessions for one agent, with live runtime snapshot
165
+ await ravi.sessions.list({ agent: "support", live: true, limit: "20" });
166
+
167
+ // Send a prompt and wait for the structured response
168
+ const result = await ravi.sessions.send("support", "Resumo do dia.", {
169
+ wait: true,
170
+ });
108
171
 
109
- ## Streaming
172
+ // Walk the message history
173
+ const history = await ravi.sessions.read("support", { count: "10" });
174
+
175
+ // Hand off between sessions (fire-and-forget). Sessions can ask, inform,
176
+ // and answer one another — the runtime delivers as system messages.
177
+ await ravi.sessions.ask("support", "Conseguiu rodar o build?", "agent:main");
178
+ await ravi.sessions.inform("support", "Daemon reiniciado às 11:20.");
179
+ await ravi.sessions.answer("support", "Build OK em 12s.", "agent:main");
180
+
181
+ // Steer / interrupt / rollback the active runtime turn
182
+ await ravi.sessions.runtime.interrupt("support");
183
+ await ravi.sessions.runtime.steer("support", "Mais conciso, por favor.");
184
+ await ravi.sessions.runtime.rollback("support", "1"); // undo last turn
185
+
186
+ // Lifecycle
187
+ await ravi.sessions.reset("support");
188
+ await ravi.sessions.delete("support");
189
+ ```
110
190
 
111
- Use `createStreamClient` or `RaviStreamClient` for server-sent event streams:
191
+ `wait: true` maps to the CLI's `--wait`. Without it, `send` returns immediately
192
+ and the session processes the prompt in the background.
193
+
194
+ ### Stream Session Events
112
195
 
113
196
  ```ts
114
197
  import { createStreamClient } from "@ravi-os/sdk/streaming";
@@ -118,36 +201,205 @@ const stream = createStreamClient({
118
201
  contextKey: process.env.RAVI_CONTEXT_KEY!,
119
202
  });
120
203
 
121
- for await (const event of stream.events({ subject: "ravi.session.>", noClaude: true })) {
204
+ for await (const event of stream.session("main", { timeout: 60 })) {
122
205
  console.log(event.event, event.data);
123
206
  }
124
207
  ```
125
208
 
126
- Available streams:
209
+ ### Stream System Events
210
+
211
+ ```ts
212
+ for await (const event of stream.events({
213
+ subject: "ravi.session.>",
214
+ noClaude: true,
215
+ noHeartbeat: true,
216
+ })) {
217
+ console.log(event.data.topic, event.data.type);
218
+ }
219
+ ```
220
+
221
+ Available stream helpers:
127
222
 
128
223
  - `stream.events(...)` -> `GET /api/v1/_stream/events`
129
224
  - `stream.tasks(...)` -> `GET /api/v1/_stream/tasks`
130
225
  - `stream.session(name, ...)` -> `GET /api/v1/_stream/sessions/<name>`
131
226
  - `stream.audit(...)` -> `GET /api/v1/_stream/audit`
132
227
 
133
- Streaming routes always require a valid context key. They also check scoped
134
- permissions such as `view:system:events`, `view:system:tasks`,
135
- `access:session:<name>`, or `view:system:audit`.
228
+ Streams always require a valid context key and the matching scope, such as
229
+ `view:system:events`, `view:system:tasks`, `access:session:<name>`, or
230
+ `view:system:audit`.
136
231
 
137
- ## Binary Responses
232
+ ### Manage Contacts
138
233
 
139
- Commands marked with `@Returns.binary()` return a raw `Response` for successful
140
- 2xx calls. Error responses are still parsed and mapped to `RaviError`
141
- subclasses.
234
+ ```ts
235
+ // Approval queue: incoming DMs land here until you allow them
236
+ const pending = await ravi.contacts.pending();
237
+ await ravi.contacts.approve("contact_5511…", "auto", { agent: "support" });
238
+
239
+ // Or add a contact manually (also acts as allow)
240
+ await ravi.contacts.add("+5511999999999", "Alice", {
241
+ kind: "person",
242
+ agent: "support",
243
+ });
244
+
245
+ // Browse and drill into a contact
246
+ const list = await ravi.contacts.list({ status: "approved", limit: "50" });
247
+ const card = await ravi.contacts.profile("contact_123", { includeCrm: true });
248
+ const recent = await ravi.contacts.messages("contact_123", { limit: "20" });
249
+
250
+ // Tag, untag, find by tag
251
+ await ravi.contacts.tag("contact_123", "lifecycle:active");
252
+ await ravi.contacts.untag("contact_123", "lifecycle:new");
253
+ const matches = await ravi.contacts.find("lifecycle:active", { tag: true });
254
+
255
+ // Scoped custom metadata (one row per source)
256
+ await ravi.contacts.metadata.set("contact_123", "billing_id", "cus_42", {
257
+ scope: "stripe",
258
+ source: "dashboard",
259
+ });
260
+
261
+ // Append a note to the contact timeline
262
+ await ravi.contacts.note("contact_123", "Cliente pediu desconto em call.", {
263
+ source: "crm",
264
+ });
265
+
266
+ // Moderation
267
+ await ravi.contacts.block("contact_spam");
268
+ ```
269
+
270
+ CRM-specific helpers (accounts, opportunities, lifecycle facts) live under
271
+ `ravi.crm.*`:
142
272
 
143
273
  ```ts
144
- const response = await client.artifacts.blob("art_123");
274
+ const crmCards = await ravi.crm.contacts({ limit: "20" });
275
+ const nextActions = await ravi.crm.next({ owner: "agent:main", limit: "10" });
276
+
277
+ await ravi.crm.contact.set("contact_123", "lifecycle", "active", {
278
+ source: "dashboard",
279
+ });
280
+ ```
281
+
282
+ ### Tag Anything
283
+
284
+ Ravi tags are first-class. The same tag slug can bind contacts, sessions,
285
+ agents, projects, tasks, chats, instances, artifacts, and more — Ravi
286
+ maintains the inverse index so you can query the graph from either end.
287
+
288
+ ```ts
289
+ // Define the tag once
290
+ await ravi.tags.create("priority:high", {
291
+ label: "High priority",
292
+ kind: "user",
293
+ });
294
+
295
+ // Attach to any target type — the option key picks the binding
296
+ await ravi.tags.attach("priority:high", { contact: "contact_123" });
297
+ await ravi.tags.attach("priority:high", { session: "support" });
298
+ await ravi.tags.attach("priority:high", { chat: "5511999@s.whatsapp.net" });
299
+ await ravi.tags.attach("priority:high", { task: "task_42" });
300
+
301
+ // Search bindings — pivot from tag to all assets, or from one asset to its tags
302
+ const tagged = await ravi.tags.search({ tag: "priority:high", limit: "100" });
303
+ const onContact = await ravi.tags.search({ contact: "contact_123" });
304
+
305
+ // Browse the catalog
306
+ await ravi.tags.list({ kind: "user", query: "lifecycle" });
307
+ await ravi.tags.show("priority:high");
308
+
309
+ // Detach (mirror of attach)
310
+ await ravi.tags.detach("priority:high", { contact: "contact_123" });
311
+ ```
312
+
313
+ ### Create And Version Artifacts
314
+
315
+ ```ts
316
+ const artifact = await ravi.artifacts.create({
317
+ title: "Weekly summary",
318
+ output: "# Summary\n\nDone.",
319
+ mime: "text/markdown",
320
+ session: "main",
321
+ tags: "summary,weekly",
322
+ });
323
+
324
+ await ravi.artifacts.snapshot("art_123", {
325
+ label: "v1",
326
+ message: "First published summary",
327
+ });
328
+ ```
329
+
330
+ Binary artifact commands return the raw `Response` on success:
331
+
332
+ ```ts
333
+ const response = await ravi.artifacts.blob("art_123");
145
334
  const bytes = await response.arrayBuffer();
146
335
  ```
147
336
 
337
+ ### Use A Custom Transport In Tests
338
+
339
+ The generated client only depends on the `Transport` interface. You can mock it
340
+ without starting a daemon:
341
+
342
+ ```ts
343
+ import { RaviClient, type Transport } from "@ravi-os/sdk";
344
+
345
+ const calls: unknown[] = [];
346
+
347
+ const mockTransport: Transport = {
348
+ async call(input) {
349
+ calls.push(input);
350
+ return { ok: true };
351
+ },
352
+ };
353
+
354
+ const ravi = new RaviClient(mockTransport);
355
+ await ravi.sessions.send("main", "hello");
356
+ ```
357
+
358
+ ## Method Naming
359
+
360
+ Generated method names mirror the CLI:
361
+
362
+ - `ravi daemon init-admin-key` -> `ravi.daemon.initAdminKey()`
363
+ - `ravi sessions send main "hello" --wait` -> `ravi.sessions.send("main", "hello", { wait: true })`
364
+ - `ravi crm contact set <contact> lifecycle active` -> `ravi.crm.contact.set(contact, "lifecycle", "active")`
365
+ - `ravi sdk client check` -> `ravi.sdk.client.check()`
366
+
367
+ Positional args become positional method parameters. CLI options become the final
368
+ `options` object. Most string-like CLI flags stay typed as strings because the
369
+ registry mirrors the CLI parser; boolean flags are booleans.
370
+
371
+ ## Wire Contract
372
+
373
+ Every command call becomes:
374
+
375
+ ```text
376
+ POST /api/v1/<group-segments>/<command>
377
+ ```
378
+
379
+ The request body is flat JSON. Positional args and options are merged at the top
380
+ level:
381
+
382
+ ```json
383
+ {
384
+ "name": "main",
385
+ "pattern": "group:120363428558776322",
386
+ "agent": "ravi-web",
387
+ "channel": "whatsapp",
388
+ "session": "ravi-web"
389
+ }
390
+ ```
391
+
392
+ Do not wrap input as `{ "args": ..., "options": ... }`.
393
+
394
+ The HTTP transport adds:
395
+
396
+ - `Authorization: Bearer <rctx_key>`
397
+ - `x-ravi-sdk-version`
398
+ - `x-ravi-registry-hash`
399
+
148
400
  ## Errors
149
401
 
150
- Every transport throws the same typed error hierarchy:
402
+ All transports throw the same error hierarchy:
151
403
 
152
404
  - `RaviAuthError` - 401, missing/invalid/expired/revoked context key
153
405
  - `RaviPermissionError` - 403, scope denied
@@ -155,13 +407,11 @@ Every transport throws the same typed error hierarchy:
155
407
  - `RaviInternalError` - 5xx from the gateway or command handler
156
408
  - `RaviTransportError` - network failure, timeout, or unexpected transport error
157
409
 
158
- All inherit from `RaviError`:
159
-
160
410
  ```ts
161
411
  import { RaviError, RaviValidationError } from "@ravi-os/sdk/errors";
162
412
 
163
413
  try {
164
- await client.artifacts.show("missing");
414
+ await ravi.artifacts.show("missing");
165
415
  } catch (error) {
166
416
  if (error instanceof RaviValidationError) {
167
417
  console.error(error.issues);
@@ -171,7 +421,7 @@ try {
171
421
  }
172
422
  ```
173
423
 
174
- ## Codegen and Drift
424
+ ## Codegen And Drift
175
425
 
176
426
  Generated files are committed as the canonical package surface:
177
427
 
@@ -190,16 +440,24 @@ bun run sdk:check
190
440
  OpenAPI and Swift SDK snapshots are generated from the same registry:
191
441
 
192
442
  ```bash
193
- bun src/cli/index.ts sdk openapi emit --out docs/openapi.json
443
+ bun run docs:openapi
194
444
  bun src/cli/index.ts sdk swift generate
195
445
  ```
196
446
 
197
- The source of truth is the `RegistrySnapshot` from
198
- `src/cli/registry-snapshot.ts`, not the OpenAPI file.
447
+ The source of truth is `src/cli/registry-snapshot.ts`, not the OpenAPI file.
199
448
 
200
449
  ## Published Exports
201
450
 
202
- Published consumers can import:
451
+ ```ts
452
+ import { RaviClient } from "@ravi-os/sdk";
453
+ import { RaviClient as DeepClient } from "@ravi-os/sdk/client";
454
+ import { createHttpTransport } from "@ravi-os/sdk/transport/http";
455
+ import { createStreamClient } from "@ravi-os/sdk/streaming";
456
+ import { RaviError } from "@ravi-os/sdk/errors";
457
+ import type { SessionsListReturn } from "@ravi-os/sdk/types";
458
+ ```
459
+
460
+ Published exports:
203
461
 
204
462
  - `@ravi-os/sdk`
205
463
  - `@ravi-os/sdk/client`
@@ -209,5 +467,5 @@ Published consumers can import:
209
467
  - `@ravi-os/sdk/types`
210
468
  - `@ravi-os/sdk/schemas`
211
469
 
212
- `src/transport/in-process.ts` is monorepo-internal and is not exported by the
213
- published package.
470
+ `packages/ravi-os-sdk/src/transport/in-process.ts` is monorepo-internal and is
471
+ not exported by the published package.