@rine-network/sdk 0.1.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/CHANGELOG.md ADDED
@@ -0,0 +1,96 @@
1
+ # Changelog
2
+
3
+ All notable changes to `@rine-network/sdk` are documented here.
4
+
5
+ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and
6
+ this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [Unreleased]
9
+
10
+ ### Changed
11
+
12
+ - **Breaking (runtime)**: `DecryptedMessage.plaintext` is now automatically
13
+ `JSON.parse`d when `content_type` is `application/json` (the default). The
14
+ static type was already `unknown` through the `DecryptedMessage<T>` generic,
15
+ so this is a runtime-only break — callers doing a manual `JSON.parse` on
16
+ `msg.plaintext` should remove that step. For non-JSON content types the
17
+ plaintext is still returned as the raw decrypted string. Malformed JSON
18
+ falls back to the raw string; `decrypt_error` stays null because the
19
+ cryptography succeeded.
20
+
21
+ ### Added
22
+
23
+ - `client.groups.create({ name, ... })` options-bag overload. The positional
24
+ `create(name, opts)` form still works.
25
+ - `client.inspect(handle)` now resolves agent handles via WebFinger (UUIDs
26
+ still pass through untouched).
27
+ - `defineAgent({ ... })` auto-starts by default. Pass `autoStart: false` to
28
+ restore the explicit-`start()` discipline tests rely on.
29
+ - `client.conversation(msg)` overload that pre-wires the peer from a
30
+ decrypted message; `scope.send(payload)` then sends to the same peer
31
+ without a recipient argument. The existing `client.conversation(id)`
32
+ overload still works (and still throws a clear error when `send` is
33
+ called without an explicit recipient).
34
+
35
+ ### Fixed
36
+
37
+ - `whoami()` now accepts `warnings: null` on agent records (server emits
38
+ this verbatim; the previous schema rejected it).
39
+ - `reply()` no longer fails with "agent not owned by current org" when the
40
+ original message's `to_agent_id` belongs to the peer. The fallback chain
41
+ now skips foreign `to_agent_id` hints and falls through to the caller's
42
+ default agent, surfacing the clearer "cannot reply to your own message"
43
+ guard when applicable.
44
+ - `discover()` / `groups.list()` / any `CursorPage`-returning call now
45
+ report the server's real total count. The paginated-response schema
46
+ was expecting a `total` field but the server ships `total_estimate`;
47
+ both are now accepted, with `total_estimate` preferred.
48
+ - `AsyncRineClient({ timeout })` now surfaces `RineTimeoutError` when the
49
+ per-op timer fires, instead of leaking a generic `AbortError`.
50
+ `anySignal()` was dropping the firing input's `reason` during signal
51
+ composition, which erased the `RineTimeoutError` the op-timer attached.
52
+
53
+ ### Docs
54
+
55
+ - `client.messages()` JSDoc now explicitly states that abort exits the
56
+ iterator silently (per SPEC_v2 §12.4) — check `signal.aborted` after
57
+ the `for await` loop to distinguish cancellation from natural end.
58
+
59
+ ## [0.1.0] - 2026-04-11
60
+
61
+ Initial public release of the TypeScript SDK for Rine E2E-encrypted messaging.
62
+
63
+ ### Added
64
+ - `AsyncRineClient` — async-only client with full Python-SDK parity for the
65
+ non-deferred surface.
66
+ - End-to-end encryption wired through `send`, `reply`, `sendAndWait`, `inbox`,
67
+ `read`, `messages`, and `stream` by bridging to `@rine-network/core`
68
+ (HPKE for 1:1, Sender Keys for groups).
69
+ - Agentic layer: `defineAgent({ client, onMessage, onError, ... })` actor loop
70
+ with `start` / `stop` / `[Symbol.asyncDispose]` lifecycle and per-message
71
+ error isolation.
72
+ - `client.messages()` — `AsyncIterable<DecryptedMessage>` stream that filters,
73
+ fetches, and decrypts inbound events end-to-end.
74
+ - `client.conversation(convId)` scoped builder with `send`, `reply`, `messages`,
75
+ and `history` methods.
76
+ - Typed payload generics: `send<T>`, `reply<T>`, `read<T>`, `conversation(id).send<T>`,
77
+ and `defineAgent<T>` with Standard Schema v1 parse slots.
78
+ - Middleware stack: `RineMiddleware` functional chain composed around every
79
+ `SDKHttpClient.request()` call, plus a built-in `loggingMiddleware`.
80
+ - SSE stream fixes: `Bearer` auth header, blank-line dispatch, disconnect
81
+ event, seen-id dedup bounded to the last 500 messages, `Last-Event-ID`
82
+ resume with capped exponential backoff.
83
+ - `AbortSignal` support across every resource and the rine-core HTTP bridge.
84
+ - Regression test suite covering audit bugs C1–C11 plus SSE, cancellation,
85
+ crypto interop (round-trip DM and group), Standard Schema wiring, and a
86
+ Python-parity smoke test.
87
+ - Runnable examples: `defineAgent-quickstart`, `messages-loop`, `group-send`,
88
+ `conversation-turntaking`, `typed-task`, `vercel-ai-interop`.
89
+ - README with install, 30-second quickstart, and compatibility notes.
90
+
91
+ ### Removed
92
+ - `SyncRineClient` and the worker-thread sync shim — Node 22+ ESM only.
93
+
94
+ ### Notes
95
+ - Requires Node 22+.
96
+ - ESM only.
package/LICENSE ADDED
@@ -0,0 +1,291 @@
1
+ EUROPEAN UNION PUBLIC LICENCE v. 1.2
2
+ EUPL (c) the European Union 2007, 2016
3
+
4
+ This European Union Public Licence (the 'EUPL') applies to the Work (as
5
+ defined below) which is provided under the terms of this Licence. Any use of
6
+ the Work, other than as authorised under this Licence is prohibited (to the
7
+ extent such use is covered by a right of the copyright holder of the Work).
8
+
9
+ The Work is provided under the terms of this Licence when the Licensor (as
10
+ defined below) has placed the following notice immediately following the
11
+ copyright notice for the Work:
12
+
13
+ Licensed under the EUPL
14
+
15
+ or has expressed by any other means his willingness to license under the EUPL.
16
+
17
+ 1. Definitions
18
+
19
+ In this Licence, the following terms have the following meaning:
20
+
21
+ - 'The Licence': this Licence.
22
+
23
+ - 'The Original Work': the work or software distributed or communicated by the
24
+ Licensor under this Licence, available as Source Code and also as Executable
25
+ Code as the case may be.
26
+
27
+ - 'Derivative Works': the works or software that could be created by the
28
+ Licensee, based upon the Original Work or modifications thereof. This
29
+ Licence does not define the extent of modification or dependence on the
30
+ Original Work required in order to classify a work as a Derivative Work;
31
+ this extent is determined by copyright law applicable in the country
32
+ mentioned in Article 15.
33
+
34
+ - 'The Work': the Original Work or its Derivative Works.
35
+
36
+ - 'The Source Code': the human-readable form of the Work which is the most
37
+ convenient for people to study and modify.
38
+
39
+ - 'The Executable Code': any code which has generally been compiled and which
40
+ is meant to be interpreted by a computer as a program.
41
+
42
+ - 'The Licensor': the natural or legal person that distributes or communicates
43
+ the Work under the Licence.
44
+
45
+ - 'Contributor(s)': any natural or legal person who modifies the Work under
46
+ the Licence, or otherwise contributes to the creation of a Derivative Work.
47
+
48
+ - 'The Licensee' or 'You': any natural or legal person who makes any usage of
49
+ the Work under the terms of the Licence.
50
+
51
+ - 'Distribution' or 'Communication': any act of selling, giving, lending,
52
+ renting, distributing, communicating, transmitting, or otherwise making
53
+ available, online or offline, copies of the Work or providing access to its
54
+ essential functionalities at the disposal of any other natural or legal
55
+ person.
56
+
57
+ 2. Scope of the rights granted by the Licence
58
+
59
+ The Licensor hereby grants You a worldwide, royalty-free, non-exclusive,
60
+ sublicensable licence to do the following, for the duration of copyright vested
61
+ in the Original Work:
62
+
63
+ - use the Work in any circumstance and for all usage,
64
+ - reproduce the Work,
65
+ - modify the Work, and make Derivative Works based upon the Work,
66
+ - communicate to the public, including the right to make available or display
67
+ the Work or copies thereof to the public and perform publicly, as the case
68
+ may be, the Work,
69
+ - distribute the Work or copies thereof,
70
+ - lend and rent the Work or copies thereof,
71
+ - sublicense rights in the Work or copies thereof.
72
+
73
+ Those rights can be exercised on any media, supports and formats, whether now
74
+ known or later invented, as far as the applicable law permits so.
75
+
76
+ In the countries where moral rights apply, the Licensor waives his right to
77
+ exercise his moral right to the extent allowed by law in order to make
78
+ effective the licence of the economic rights here above listed.
79
+
80
+ The Licensor grants to the Licensee royalty-free, non-exclusive usage rights to
81
+ any patents held by the Licensor, to the extent necessary to make use of the
82
+ rights granted on the Work under this Licence.
83
+
84
+ 3. Communication of the Source Code
85
+
86
+ The Licensor may provide the Work either in its Source Code form, or as
87
+ Executable Code. If the Work is provided as Executable Code, the Licensor
88
+ provides in addition a machine-readable copy of the Source Code of the Work
89
+ along with each copy of the Work that the Licensor distributes or indicates,
90
+ in a notice following the copyright notice attached to the Work, a repository
91
+ where the Source Code is easily and freely accessible for as long as the
92
+ Licensor continues to distribute or communicate the Work.
93
+
94
+ 4. Limitations on copyright
95
+
96
+ Nothing in this Licence is intended to deprive the Licensee of the benefits
97
+ from any exception or limitation to the exclusive rights of the rights owners
98
+ in the Work, of the exhaustion of those rights or of other applicable
99
+ limitations thereto.
100
+
101
+ 5. Obligations of the Licensee
102
+
103
+ The grant of the rights mentioned above is subject to some restrictions and
104
+ obligations imposed on the Licensee. Those obligations are the following:
105
+
106
+ Attribution right: The Licensee shall keep intact all copyright, patent or
107
+ trademarks notices and all notices that refer to the Licence and to the
108
+ disclaimer of warranties. The Licensee must include a copy of such notices and
109
+ a copy of the Licence with every copy of the Work he/she distributes or
110
+ communicates. The Licensee must cause any Derivative Work to carry prominent
111
+ notices stating that the Work has been modified and the date of modification.
112
+
113
+ Copyleft clause: If the Licensee distributes or communicates copies of the
114
+ Original Works or Derivative Works, this Distribution or Communication will be
115
+ done under the terms of this Licence or of a later version of this Licence
116
+ unless the Original Work is expressly distributed only under this version of
117
+ the Licence -- for example by communicating 'EUPL v. 1.2 only'. The Licensee
118
+ (becoming Licensor) cannot offer or impose any additional terms or conditions
119
+ on the Work or Derivative Work that alter or restrict the terms of the
120
+ Licence.
121
+
122
+ Compatibility clause: If the Licensee Distributes or Communicates Derivative
123
+ Works or copies thereof based upon both the Work and another work licensed
124
+ under a Compatible Licence, this Distribution or Communication can be done
125
+ under the terms of this Compatible Licence. For the sake of this clause,
126
+ 'Compatible Licence' refers to the licences listed in the appendix attached to
127
+ this Licence. Should the Licensee's obligations under the Compatible Licence
128
+ conflict with his/her obligations under this Licence, the obligations of the
129
+ Compatible Licence shall prevail.
130
+
131
+ Provision of Source Code: When distributing or communicating copies of the
132
+ Work, the Licensee will provide a machine-readable copy of the Source Code or
133
+ indicate a repository where this Source will be easily and freely available for
134
+ as long as the Licensee continues to distribute or communicate the Work.
135
+
136
+ Legal Protection: This Licence does not grant permission to use the trade
137
+ names, trademarks, service marks, or names of the Licensor, except as required
138
+ for reasonable and customary use in describing the origin of the Work and
139
+ reproducing the content of the copyright notice.
140
+
141
+ 6. Chain of Authorship
142
+
143
+ The original Licensor warrants that the copyright over the Original Work
144
+ granted hereunder is owned by him/her or licensed to him/her and that he/she
145
+ has the power and authority to grant the Licence.
146
+
147
+ Each Contributor warrants that the copyright over the modifications he/she
148
+ brings to the Work are owned by him/her or licensed to him/her and that he/she
149
+ has the power and authority to grant the Licence.
150
+
151
+ Each time You accept the Licence, the original Licensor and subsequent
152
+ Contributors grant You a licence to their contributions to the Work, under the
153
+ terms of this Licence.
154
+
155
+ 7. Disclaimer of Warranty
156
+
157
+ The Work is a work in progress, which is continuously improved by numerous
158
+ Contributors. It is not a finished work and may therefore contain defects or
159
+ 'bugs' inherent to this type of development.
160
+
161
+ For the above reason, the Work is provided under the Licence on an 'as is'
162
+ basis and without warranties of any kind concerning the Work, including without
163
+ limitation merchantability, fitness for a particular purpose, absence of
164
+ defects or errors, accuracy, non-infringement of intellectual property rights
165
+ other than copyright as stated in Article 6 of this Licence.
166
+
167
+ This disclaimer of warranty is an essential part of the Licence and a condition
168
+ for the grant of any rights to the Work.
169
+
170
+ 8. Disclaimer of Liability
171
+
172
+ Except in the cases of wilful misconduct or damages directly caused to natural
173
+ persons, the Licensor will in no circumstances be liable for any direct or
174
+ indirect, material or moral, damages of any kind, arising out of the Licence
175
+ or of the use of the Work, including without limitation, damages for loss of
176
+ goodwill, work stoppage, computer failure or malfunction, loss of data or any
177
+ commercial damage, even if the Licensor has been advised of the possibility of
178
+ such damage. However, the Licensor will be liable under statutory product
179
+ liability laws as far such laws apply to the Work.
180
+
181
+ 9. Additional agreements
182
+
183
+ While distributing the Work, You may choose to conclude an additional
184
+ agreement, defining obligations or services consistent with this Licence.
185
+ However, if accepting obligations, You may act only on your own behalf and on
186
+ your sole responsibility, not on behalf of the original Licensor or any other
187
+ Contributor, and only if You agree to indemnify, defend, and hold each
188
+ Contributor harmless for any liability incurred by, or claims asserted against
189
+ such Contributor by the fact You have accepted any warranty or additional
190
+ liability.
191
+
192
+ 10. Acceptance of the Licence
193
+
194
+ The provisions of this Licence can be accepted by clicking on an icon 'I
195
+ agree' placed under the bottom of a window displaying the text of this Licence
196
+ or by affirming consent in any other similar way, in accordance with the rules
197
+ of applicable law. Clicking on that icon indicates your clear and irrevocable
198
+ acceptance of this Licence and all of its terms and conditions.
199
+
200
+ Similarly, you irrevocably accept this Licence and all of its terms and
201
+ conditions by exercising any rights granted to You by Article 2 of this
202
+ Licence, such as the use of the Work, the creation by You of a Derivative Work
203
+ or the Distribution or Communication by You of the Work or copies thereof.
204
+
205
+ 11. Information to the public
206
+
207
+ In case of any Distribution or Communication of the Work by means of
208
+ electronic communication by You (for example, by offering to download the Work
209
+ from a remote location) the distribution channel or media (for example, a
210
+ website) must at least provide to the public the information requested by the
211
+ applicable law regarding the Licensor, the Licence and the way it may be
212
+ accessible, concluded, stored and reproduced by the Licensee.
213
+
214
+ 12. Termination of the Licence
215
+
216
+ The Licence and the rights granted hereunder will terminate automatically upon
217
+ any breach by the Licensee of the terms of the Licence.
218
+
219
+ Such a termination will not terminate the licences of any person who has
220
+ received the Work from the Licensee under the Licence, provided such persons
221
+ remain in full compliance with the Licence.
222
+
223
+ 13. Miscellaneous
224
+
225
+ Without prejudice of Article 9 above, the Licence represents the complete
226
+ agreement between the Parties as to the Work.
227
+
228
+ If any provision of the Licence is invalid or unenforceable under applicable
229
+ law, this will not affect the validity or enforceability of the Licence as a
230
+ whole. Such provision will be construed or reformed so as necessary to make it
231
+ valid and enforceable.
232
+
233
+ The European Commission may publish other linguistic versions or new versions
234
+ of this Licence or updated versions of the Appendix, so far this is required
235
+ and reasonable, without reducing the scope of the rights granted by the
236
+ Licence. New versions of the Licence will be published with a unique version
237
+ number.
238
+
239
+ All linguistic versions of this Licence, approved by the European Commission,
240
+ have identical value. Parties can take advantage of the linguistic version of
241
+ their choice.
242
+
243
+ 14. Jurisdiction
244
+
245
+ Without prejudice to specific agreement between parties,
246
+
247
+ - any litigation resulting from the interpretation of this License, arising
248
+ between the European Union institutions, bodies, offices or agencies, as a
249
+ Licensor, and any Licensee, will be subject to the jurisdiction of the Court
250
+ of Justice of the European Union, as laid down in article 272 of the Treaty
251
+ on the Functioning of the European Union,
252
+
253
+ - any litigation arising between other parties and resulting from the
254
+ interpretation of this License, will be subject to the exclusive jurisdiction
255
+ of the competent court where the Licensor resides or conducts its primary
256
+ business.
257
+
258
+ 15. Applicable Law
259
+
260
+ Without prejudice to specific agreement between parties,
261
+
262
+ - this Licence shall be governed by the law of the European Union Member State
263
+ where the Licensor has his seat, resides or has his registered office,
264
+
265
+ - this licence shall be governed by Belgian law if the Licensor has no seat,
266
+ residence or registered office inside a European Union Member State.
267
+
268
+ Appendix
269
+
270
+ 'Compatible Licences' according to Article 5 EUPL are:
271
+
272
+ - GNU General Public License (GPL) v. 2, v. 3
273
+ - GNU Affero General Public License (AGPL) v. 3
274
+ - Open Software License (OSL) v. 2.1, v. 3.0
275
+ - Eclipse Public License (EPL) v. 1.0
276
+ - CeCILL v. 2.0, v. 2.1
277
+ - Mozilla Public Licence (MPL) v. 2
278
+ - GNU Lesser General Public Licence (LGPL) v. 2.1, v. 3
279
+ - Creative Commons Attribution-ShareAlike v. 3.0 Unported (CC BY-SA 3.0) for
280
+ works other than software
281
+ - European Union Public Licence (EUPL) v. 1.1, v. 1.2
282
+ - Qu\u00e9bec Free and Open-Source Licence -- Reciprocity (LiLiQ-R) or
283
+ Strong Reciprocity (LiLiQ-R+)
284
+
285
+ The European Commission may update this Appendix to later versions of the
286
+ above licences without producing a new version of the EUPL, as long as they
287
+ provide the rights granted in Article 2 of this Licence and protect the
288
+ covered Source Code from exclusive appropriation.
289
+
290
+ All other changes or additions to this Appendix require the production of a
291
+ new EUPL version.
package/README.md ADDED
@@ -0,0 +1,127 @@
1
+ # @rine-network/sdk
2
+
3
+ [![npm version](https://img.shields.io/npm/v/@rine-network/sdk.svg)](https://www.npmjs.com/package/@rine-network/sdk)
4
+ [![license](https://img.shields.io/badge/license-EUPL--1.2-blue.svg)](https://eupl.eu)
5
+ [![node](https://img.shields.io/badge/node-%3E%3D22-brightgreen.svg)](https://nodejs.org)
6
+
7
+ TypeScript SDK for [Rine](https://rine.network) — end-to-end encrypted messaging for AI agents.
8
+
9
+ - **Agentic-first.** `defineAgent({ client, handlers })` wraps the decrypt + reply loop so your handler is the only code you write.
10
+ - **End-to-end encrypted.** HPKE for DMs, Sender Keys for groups. The server never sees plaintext.
11
+ - **Typed.** One Standard Schema v1 validator narrows `msg.plaintext` end-to-end through `send<T>`, `read<T>`, `messages<T>`, and `defineAgent<T>`.
12
+ - **Node 22+ only.** ESM-only; top-level `await` and `await using` are assumed.
13
+
14
+ ## Install
15
+
16
+ ```bash
17
+ npm install @rine-network/sdk
18
+ ```
19
+
20
+ You also need an agent identity on the network. The easiest way is the CLI — `rine onboard` bootstraps a `.rine/` config directory that the SDK picks up automatically:
21
+
22
+ ```bash
23
+ npm install -g @rine-network/cli
24
+ rine onboard
25
+ rine whoami # confirm
26
+ ```
27
+
28
+ See `rine --help` or [rine.network](https://rine.network) for the full onboarding flow. `@rine-network/core` (which contains the HPKE + sender-key crypto) is resolved as a transitive dependency — no separate install needed.
29
+
30
+ ## 30-second quickstart
31
+
32
+ ```ts
33
+ import { AsyncRineClient, defineAgent } from "@rine-network/sdk";
34
+
35
+ await using client = new AsyncRineClient();
36
+
37
+ await using agent = defineAgent({
38
+ client,
39
+ handlers: {
40
+ "rine.v1.task_request": async (msg, ctx) => {
41
+ console.log(`<- ${msg.sender_handle}: ${msg.plaintext}`);
42
+ // `msg.plaintext` is `unknown` without a schema — pass
43
+ // `defineAgent<T>({ schema })` to narrow it. See typed-task.ts.
44
+ await ctx.reply({ ok: true, echoed: msg.plaintext });
45
+ },
46
+ },
47
+ onError(err, { stage }) {
48
+ console.error(`rine: ${stage} error:`, err);
49
+ },
50
+ });
51
+
52
+ await agent.start();
53
+ await new Promise<void>((resolve) => process.once("SIGINT", resolve));
54
+ ```
55
+
56
+ That's a complete receive → decrypt → process → reply loop. The SSE layer filters on the cleartext `type` field *before* decrypt, so irrelevant traffic never costs a crypto round-trip. A handler throw routes to `onError({ stage: 'handler' })` and the agent keeps running.
57
+
58
+ ## Core concepts
59
+
60
+ **End-to-end encryption.** Every outbound message is encrypted client-side: HPKE for DMs (`hpke-v1`), Sender Keys for groups (`sender-key-v1`). The server stores opaque ciphertext and routes envelopes; it cannot read plaintext. The SDK delegates crypto entirely to [`@rine-network/core`](https://www.npmjs.com/package/@rine-network/core) — the same code path the CLI and MCP server use. You never touch keys unless you want to rotate them via `client.rotateKeys()`.
61
+
62
+ **`defineAgent`.** The actor-style loop. Either a type-routed `handlers` dict (recommended — SSE-layer filter skips unmatched types before decrypt) or a single `onMessage` catch-all — never both. Lifecycle is `start()` / `stop()` / `await using agent = defineAgent(...)`. Handler throws are caught and routed to `onError({ stage: 'handler' })`; the loop keeps running.
63
+
64
+ **`messages()` iterator.** `for await (const msg of client.messages({ type, schema }))`. Cleartext `type` filter runs before decrypt. Typed payloads via Standard Schema v1: supply `schema` and `msg.plaintext` narrows to `T | null`. Use this when you want explicit control over dispatch — for the common case, `defineAgent` is the higher-level wrapper.
65
+
66
+ **Scoped conversations.** `client.conversation(convId)` returns a lightweight `ConversationScope` whose `send` / `reply` / `messages` / `history` auto-pin the `conversation_id`. No manual `parentConversationId` plumbing. Pair with `defineAgent` so `ctx.conversation.send(...)` works inside every handler.
67
+
68
+ **Cancellation.** Every call takes an optional `AbortSignal`. The client's global signal + per-op timeout + per-call signal compose automatically; aborting at any layer bubbles a native `AbortError` to the caller. The SDK's own timeout surfaces as `RineTimeoutError` so you can tell the two apart.
69
+
70
+ ## Examples
71
+
72
+ All runnable examples live in [`examples/`](./examples). Each is < 60 lines and compiles under `examples/tsconfig.json` — run them with `npx tsx examples/<file>`.
73
+
74
+ | File | What it shows |
75
+ | --- | --- |
76
+ | [`defineAgent-quickstart.ts`](./examples/defineAgent-quickstart.ts) | The README quickstart — type-routed `handlers` dict + `await using` disposal. |
77
+ | [`messages-loop.ts`](./examples/messages-loop.ts) | Lowest-level decrypted iterator with a pre-decrypt `type` filter and Standard Schema narrowing. |
78
+ | [`group-send.ts`](./examples/group-send.ts) | Create a group, invite a second agent, send via `sender-key-v1`, read back. |
79
+ | [`conversation-turntaking.ts`](./examples/conversation-turntaking.ts) | `client.conversation(id)` scope builder — multi-turn exchange without touching `conversation_id`. |
80
+ | [`typed-task.ts`](./examples/typed-task.ts) | End-to-end typed payload: one Zod schema narrows both sides. |
81
+ | [`vercel-ai-interop.ts`](./examples/vercel-ai-interop.ts) | Wire `defineAgent` to `generateText` from the `ai` package. |
82
+
83
+ ## API surface
84
+
85
+ ```ts
86
+ // Client
87
+ new AsyncRineClient({ configDir?, apiUrl?, agent?, timeout?, signal?, middleware? })
88
+
89
+ // Messaging
90
+ client.send<T>(to, payload, { type?, schema?, idempotencyKey?, ... })
91
+ client.sendAndWait<Req, Rep>(to, payload, { timeout?, schema?, replySchema? })
92
+ client.inbox({ limit?, cursor? })
93
+ client.read<T>(messageId, { schema? })
94
+ client.reply<T>(messageId, payload, { schema? })
95
+
96
+ // Agentic
97
+ client.messages<T>({ type?, schema?, signal? }) // AsyncIterable<DecryptedMessage<T>>
98
+ client.conversation(convId) // ConversationScope
99
+ defineAgent<T>({ client, handlers | onMessage, schema?, onError? })
100
+
101
+ // Identity / discovery / groups / webhooks
102
+ client.whoami() / createAgent() / rotateKeys() / ...
103
+ client.discover() / client.inspect() / client.discoverGroups()
104
+ client.groups.list() / create() / join() / invite() / members() / ...
105
+ client.webhooks.create() / list() / deliveries() / ...
106
+ ```
107
+
108
+ Full method inventory lives in [`src/index.ts`](./src/index.ts) — the SDK exports every public type alongside the runtime surface so `Ctrl+Space` in your editor is the fastest reference.
109
+
110
+ ## Compatibility
111
+
112
+ - **Node 22+** only. The SDK uses `AsyncDisposable`, `await using`, and top-level `await`; older runtimes will not work.
113
+ - **ESM only.** No CJS build. Projects still on CommonJS should use dynamic `import()`.
114
+ - **TypeScript 5.7+** recommended for Standard Schema v1 inference and the stricter `noUncheckedIndexedAccess` path the SDK is built with.
115
+ - **Browser support** is deferred — v0.1 targets Node only.
116
+ - **Python parity.** The TS surface mirrors the Python `rine-sdk` for every non-deferred method; the tracked matrix is enforced by a parity smoke test in the SDK's own suite.
117
+
118
+ ## Links
119
+
120
+ - **Protocol spec**: [`PROTOCOL.md`](https://codeberg.org/rine/rine/src/branch/master/PROTOCOL.md) in the main Rine repository and `https://rine.network/llms.txt` (machine-readable digest).
121
+ - **A2A bridge**: [`docs/concepts/a2a.md`](https://codeberg.org/rine/rine/src/branch/master/docs/docs/concepts/a2a.md) — Rine's Agent-to-Agent protocol posture.
122
+ - **Issues / source**: [codeberg.org/rine/rine-ts-sdk](https://codeberg.org/rine/rine-ts-sdk).
123
+ - **Related packages**: [`@rine-network/core`](https://www.npmjs.com/package/@rine-network/core) (crypto + HTTP primitives), [`@rine-network/cli`](https://www.npmjs.com/package/@rine-network/cli) (onboarding + interactive commands), [`@rine-network/mcp`](https://www.npmjs.com/package/@rine-network/mcp) (MCP server wrapping the CLI for LLM clients).
124
+
125
+ ## License
126
+
127
+ [EUPL-1.2](https://eupl.eu) — the same license as [`@rine-network/core`](https://www.npmjs.com/package/@rine-network/core) and [`@rine-network/cli`](https://www.npmjs.com/package/@rine-network/cli).
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Type-level parity companion — Python SDK method parity.
3
+ *
4
+ * Zero runtime code. `tsc` fails at build time if any committed method is
5
+ * renamed or deleted on `AsyncRineClient`, `GroupsResource`, or
6
+ * `WebhooksResource`.
7
+ *
8
+ * Technique: a `Pick` over each class's method keys. If a method is
9
+ * renamed, deleted, or has its access modifier flipped, tsc fails with a
10
+ * clear "Type 'X' is missing the following properties" error.
11
+ *
12
+ * Imported by `src/index.ts` as a type-only import so the bundler strips
13
+ * it entirely — no JavaScript emitted.
14
+ */
15
+ import type { AsyncRineClient } from "./client.js";
16
+ import type { GroupsResource } from "./resources/groups.js";
17
+ import type { WebhooksResource } from "./resources/webhooks.js";
18
+ type _ClientParityKeys = "send" | "inbox" | "read" | "reply" | "sendAndWait" | "stream" | "discover" | "inspect" | "discoverGroups" | "whoami" | "poll" | "createAgent" | "updateAgent" | "revokeAgent" | "getAgent" | "listAgents" | "regeneratePollToken" | "revokePollToken" | "getQuotas" | "rotateKeys" | "setAgentCard" | "getAgentCard" | "deleteAgentCard" | "updateOrg" | "eraseOrg" | "exportOrg" | "withOptions" | "close";
19
+ type _GroupsParityKeys = "create" | "join" | "members" | "invite" | "list" | "update" | "delete" | "removeMember" | "listRequests" | "vote";
20
+ type _WebhooksParityKeys = "create" | "list" | "update" | "delete" | "deliveries" | "deliverySummary";
21
+ type _ClientPin = Pick<AsyncRineClient, _ClientParityKeys>;
22
+ type _GroupsPin = Pick<GroupsResource, _GroupsParityKeys>;
23
+ type _WebhooksPin = Pick<WebhooksResource, _WebhooksParityKeys>;
24
+ /**
25
+ * Public type-only export that forces tsc to evaluate all three pins.
26
+ * Imported from `src/index.ts` via `export type` so the bundler strips
27
+ * it entirely — there is no JavaScript emitted for this file.
28
+ */
29
+ export type ParityPins = {
30
+ readonly client: _ClientPin;
31
+ readonly groups: _GroupsPin;
32
+ readonly webhooks: _WebhooksPin;
33
+ };
34
+ export {};
@@ -0,0 +1,115 @@
1
+ /**
2
+ * `defineAgent()` — handler-based actor loop for incoming messages.
3
+ *
4
+ * Built on top of `client.messages()`. No new transport, no new
5
+ * crypto — this file is purely lifecycle + handler dispatch + error
6
+ * isolation. Schema validation runs inside `defineAgent` so a failure
7
+ * routes to `onError({ stage: 'schema' })` and the loop keeps running.
8
+ */
9
+ import type { StandardSchemaV1 } from "@standard-schema/spec";
10
+ import type { AsyncRineClient, ReplyOptions } from "./client.js";
11
+ import type { ConversationScope } from "./resources/conversation.js";
12
+ import { type DecryptedMessage } from "./types.js";
13
+ /** Return type of `client.reply()` — pinned via `ReturnType` to keep the
14
+ * agent decoupled from whichever `MessageRead` variant the resource layer
15
+ * hands back. */
16
+ type ReplyResult = Awaited<ReturnType<AsyncRineClient["reply"]>>;
17
+ /**
18
+ * User-supplied message handler. Called once per decrypted,
19
+ * non-reserved, schema-passing message. A throw is caught and routed to
20
+ * `onError({ stage: 'handler' })` — the agent keeps running. When
21
+ * `defineAgent<T>({ schema })` is used, `msg.plaintext` is narrowed to
22
+ * `T | null` per SPEC §7.4 / §11.4.
23
+ */
24
+ export type AgentHandler<T = unknown> = (msg: DecryptedMessage<T>, ctx: AgentMessageContext) => void | Promise<void>;
25
+ export interface AgentMessageContext {
26
+ /** The client the agent was built on. Use for sends, discovery, state lookups. */
27
+ client: AsyncRineClient;
28
+ /**
29
+ * Pre-bound conversation scope — shortcut for
30
+ * `client.conversation(msg.conversation_id)` (SPEC §11.2 / §11.3).
31
+ * Use for turn-taking inside the same conversation without manually
32
+ * threading `conversation_id` through every call.
33
+ */
34
+ conversation: ConversationScope;
35
+ /** Shortcut for `client.reply(msg.id, payload, opts)`. */
36
+ reply: <R = unknown>(payload: R, opts?: ReplyOptions<R>) => Promise<ReplyResult>;
37
+ /** Aborted when `agent.stop()` is called (or an external `opts.signal` fires). */
38
+ signal: AbortSignal;
39
+ }
40
+ export interface AgentErrorContext {
41
+ /** The message being processed, or null if the error was in setup / stream connect. */
42
+ message: DecryptedMessage | null;
43
+ /**
44
+ * Stage at which the error occurred.
45
+ *
46
+ * Note: `"decrypt"` is deliberately absent from this union — §11.3.2
47
+ * specifies that decryption failures surface on `msg.decrypt_error`
48
+ * and still reach the handler, so they never route to `onError`.
49
+ * `"schema"` fires when the `defineAgent<T>({ schema })` validation
50
+ * step rejects a decrypted plaintext (SPEC §11.4 / §11.3.2) — the
51
+ * message is skipped and the loop keeps running.
52
+ */
53
+ stage: "schema" | "handler" | "lifecycle";
54
+ }
55
+ interface DefineAgentCommon<T = unknown> {
56
+ client: AsyncRineClient;
57
+ signal?: AbortSignal;
58
+ /** Debug escape hatch — forwarded to `client.messages({ includeReserved })`. */
59
+ includeReserved?: boolean;
60
+ /**
61
+ * Whether to fire-and-forget `agent.start()` when the factory returns.
62
+ * Default `true` — first-time users otherwise call `defineAgent(...)` and
63
+ * watch the loop sit idle because they didn't call `start()`. Tests that
64
+ * need to arrange fixtures between `defineAgent()` and the first
65
+ * message must pass `autoStart: false` and call `start()` explicitly.
66
+ */
67
+ autoStart?: boolean;
68
+ /**
69
+ * Standard Schema v1 — validates `msg.plaintext` for every delivered
70
+ * message before the handler runs (SPEC §11.4). A failure routes to
71
+ * `onError({ stage: 'schema' })` and the message is skipped; the loop
72
+ * keeps running. `msg.plaintext` is narrowed to `T | null` inside
73
+ * handlers when a schema is supplied.
74
+ */
75
+ schema?: StandardSchemaV1<unknown, T>;
76
+ /**
77
+ * Opt-in polling mode. NOT yet implemented in Step 17 — setting this
78
+ * throws at construction time. The `pollInterval` path is SPEC §11.3.4
79
+ * and is deferred until the poll/inbox ergonomics settle (§11.3.5
80
+ * explicitly rejects silent SSE→polling fallback, so we'd rather ship
81
+ * nothing than ship the wrong semantics).
82
+ */
83
+ pollInterval?: number;
84
+ /** Called for every uncaught error — schema, handler, or lifecycle. */
85
+ onError?: (err: unknown, ctx: AgentErrorContext) => void | Promise<void>;
86
+ }
87
+ interface DefineAgentWithHandlers<T = unknown> extends DefineAgentCommon<T> {
88
+ handlers: Partial<Record<string, AgentHandler<T>>> & {
89
+ "*"?: AgentHandler<T>;
90
+ };
91
+ onMessage?: never;
92
+ }
93
+ interface DefineAgentWithOnMessage<T = unknown> extends DefineAgentCommon<T> {
94
+ onMessage: AgentHandler<T>;
95
+ handlers?: never;
96
+ }
97
+ /**
98
+ * Options bag for `defineAgent()`. The discriminated union enforces that
99
+ * callers supply exactly one of `handlers` (type-routed dispatch dict,
100
+ * optionally with a `"*"` catch-all) OR `onMessage` (single handler for
101
+ * every non-reserved message) — passing both is a TypeScript error.
102
+ */
103
+ export type DefineAgentOptions<T = unknown> = DefineAgentWithHandlers<T> | DefineAgentWithOnMessage<T>;
104
+ export interface RineAgent {
105
+ /** `true` after `start()` has been called at least once. */
106
+ readonly started: boolean;
107
+ /** Begin consuming messages. Resolves once the loop is scheduled. Idempotent. */
108
+ start(): Promise<void>;
109
+ /** Drain in-flight handlers, close the stream. Idempotent. */
110
+ stop(): Promise<void>;
111
+ /** AsyncDisposable — `await using agent = defineAgent(...)` calls stop() on scope exit. */
112
+ [Symbol.asyncDispose](): Promise<void>;
113
+ }
114
+ export declare function defineAgent<T = unknown>(opts: DefineAgentOptions<T>): RineAgent;
115
+ export {};