@niadra/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 +28 -0
- package/LICENSE +201 -0
- package/README.md +361 -0
- package/dist/index.cjs +2389 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +1441 -0
- package/dist/index.d.ts +1441 -0
- package/dist/index.js +2355 -0
- package/dist/index.js.map +1 -0
- package/package.json +74 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this package are documented here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the package follows [Semantic Versioning](https://semver.org/).
|
|
4
|
+
|
|
5
|
+
## [0.1.0] - 2026-09-23
|
|
6
|
+
|
|
7
|
+
First public release, with the same surface as the Python SDK.
|
|
8
|
+
|
|
9
|
+
### Added
|
|
10
|
+
|
|
11
|
+
- `Niadra` client with the endpoint derived from the source key (`https://<space>.<region>.api.niadra.com`), overridable with `baseURL`.
|
|
12
|
+
- `context()` with a per-conversation cache: TTL, stale-while-revalidate with one deduplicated refresh per pack, last good value on failure, and ETag revalidation through `known_etag`. 401 and 403 drop cached packs, and a `degraded` answer never replaces a good one. Plain and delta reads of a conversation share one entry, and each delta is handed out once.
|
|
13
|
+
- History navigation: `search()`, `timeline()` and `open()`.
|
|
14
|
+
- `tools(subject)`: the navigation kit as function-calling definitions, with the customer bound outside the model.
|
|
15
|
+
- `subjectToken()` for binding a customer to an MCP session.
|
|
16
|
+
- Writes: `track()`, `action()`, `identify()`, `verify()` and `handoff()`, through a bounded queue that batches by count and time, retries with backoff and sends a coverage heartbeat once a minute.
|
|
17
|
+
- `conversation()` helper that reads the pack the server pins, asks for deltas after the first read and keeps them until the pack changes, captures turns and emits `conversation.ended`.
|
|
18
|
+
- `task()` helper for internal agents that centers its pack on its object, keeps deltas and stamps like a conversation, captures the agent's answers and emits `task.ended`; `verify()` on a task, whose `tools()` follow its level.
|
|
19
|
+
- `markInjected()` and `contextStamp` on conversations and tasks: the agent's turns and actions carry the etag of the pack its prompt held and when it went in, as the event's `context_stamp`.
|
|
20
|
+
- `wrap()` for OpenAI-compatible clients: injects the pack and the suffix into `chat.completions.create` and `parse` (also under `beta`), stamps the injection, records the answer, streams included, keeps `.withResponse()` working, and never lets a capture failure reach the caller. `injectContext()` places a pack in a message list by the same rule.
|
|
21
|
+
- `objectState()` and `objectTimeline()` for business objects.
|
|
22
|
+
- `feedback()` to retract or correct a fact, resolve an open item or record a conversation's outcome.
|
|
23
|
+
- `uploadMedia()`: reserves an upload, sends the bytes to the signed URL with exactly the headers it names (HTTPS
|
|
24
|
+
only, never the key) and resolves with `media_ref` and `media_sha256`; optionally bound to a `subject`.
|
|
25
|
+
- Fail-open behavior on every public method, and `strict: true` to throw instead.
|
|
26
|
+
- Per-method time budgets, 421 retries for moved spaces, and `problem+json` errors mapped to typed classes.
|
|
27
|
+
- Flush on `beforeExit` in Node, `flush()` and `shutdown()` everywhere else.
|
|
28
|
+
- Handle builders and wire types for every contract model.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "{}"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 Niadra
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,361 @@
|
|
|
1
|
+
# Niadra TypeScript SDK
|
|
2
|
+
|
|
3
|
+
[](https://www.npmjs.com/package/@niadra/sdk)
|
|
4
|
+
[](LICENSE)
|
|
5
|
+
|
|
6
|
+
**Niadra is the shared customer memory for every AI agent in a company.** The WhatsApp agent, the
|
|
7
|
+
voice agent, the billing agent and the human team read the same memory before they act and write
|
|
8
|
+
back what they said and did. This package connects a TypeScript or JavaScript agent to it, on Node
|
|
9
|
+
18+ and on edge runtimes (Vercel, Cloudflare Workers, Deno).
|
|
10
|
+
|
|
11
|
+
[Website](https://niadra.com/en) · [Documentation](https://niadra.com/en/docs) ·
|
|
12
|
+
[Talk to us](https://niadra.com/en/enterprise) · [Python SDK](https://github.com/ainiadra/niadra-sdk-python)
|
|
13
|
+
|
|
14
|
+
```sh
|
|
15
|
+
npm install @niadra/sdk
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## The problem it solves
|
|
19
|
+
|
|
20
|
+
A customer tells your WhatsApp agent that order 4471 arrived with a broken lid and that she needs a
|
|
21
|
+
replacement by Friday. An hour later she calls. Without shared memory, the voice agent asks her to
|
|
22
|
+
explain everything again, and nobody remembers the Friday promise. With Niadra, the voice agent
|
|
23
|
+
starts the call knowing about the open replacement and its deadline, and when the billing agent
|
|
24
|
+
credits her invoice, the other agents see it within seconds.
|
|
25
|
+
|
|
26
|
+
Niadra does the remembering for you:
|
|
27
|
+
|
|
28
|
+
- it turns conversations and system events into facts, open items and promises, each with the
|
|
29
|
+
turns that prove it;
|
|
30
|
+
- it ties them to the right person across phone numbers, e-mails, WhatsApp ids and CRM ids, and to
|
|
31
|
+
the companies and partners that person acts for;
|
|
32
|
+
- it compiles a short context for each agent, holding back what the customer's verification level
|
|
33
|
+
does not allow, and records a receipt of every read.
|
|
34
|
+
|
|
35
|
+
Your agents keep their own models, prompts and vendors. Niadra is the memory layer they share.
|
|
36
|
+
|
|
37
|
+
## Quickstart
|
|
38
|
+
|
|
39
|
+
```ts
|
|
40
|
+
import { Niadra, handles } from "@niadra/sdk";
|
|
41
|
+
|
|
42
|
+
const niadra = new Niadra({ apiKey: process.env.NIADRA_API_KEY });
|
|
43
|
+
const marina = handles.phone("+5511987654321");
|
|
44
|
+
const convo = niadra.conversation({ subject: marina, channel: "whatsapp", conversation_id: "wa-8812" });
|
|
45
|
+
|
|
46
|
+
convo.customer(inbound.text, { idempotency_key: inbound.id }); // what the customer wrote
|
|
47
|
+
const ctx = await convo.context(); // what this agent needs to know now
|
|
48
|
+
convo.markInjected(ctx);
|
|
49
|
+
const reply = await callModel(instructions + "\n\n" + ctx.text, history, ctx.suffix);
|
|
50
|
+
convo.agent(reply); // what the agent answered
|
|
51
|
+
await convo.end();
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Three moments cover most agents: read the context before the model call, record the turns after
|
|
55
|
+
it, and record an `action()` when the agent does something in a system (a refund, a new delivery
|
|
56
|
+
date). `wrap()` does the reading and recording for you around an OpenAI-compatible client. Ships
|
|
57
|
+
ESM and CommonJS builds with full type definitions; it only needs `fetch`.
|
|
58
|
+
|
|
59
|
+
## What your agent gets
|
|
60
|
+
|
|
61
|
+
| Call | What it returns |
|
|
62
|
+
|---|---|
|
|
63
|
+
| `context()` | a few lines about this customer, compiled from every channel and agent, pinned for the conversation |
|
|
64
|
+
| `search()`, `timeline()`, `open()` | the full history on demand, with how often a problem happened before |
|
|
65
|
+
| `tools()` | the same history as function-calling tools bound to one customer, for any model provider |
|
|
66
|
+
| `subjectToken()` | a token that binds an MCP connection to one customer |
|
|
67
|
+
| `track()`, `action()` | messages, system events and actions, sent in the background, never blocking the agent |
|
|
68
|
+
| `identify()`, `verify()` | which ids belong to the same person, and what the conversation proved about who is there |
|
|
69
|
+
| `objectState()`, `objectTimeline()` | a business object (an order, an invoice, a ticket) as the systems of record reported it |
|
|
70
|
+
| `feedback()` | a correction of what Niadra derived, audited like any other event |
|
|
71
|
+
|
|
72
|
+
## Questions people ask
|
|
73
|
+
|
|
74
|
+
**How do I give my AI agent memory of past conversations on other channels?** Record the turns
|
|
75
|
+
with `track()` or `conversation()` in every agent, and read `context()` before each model call.
|
|
76
|
+
Niadra ties the turns to the person, whichever id each channel uses.
|
|
77
|
+
|
|
78
|
+
**How is this different from keeping chat history in my database or in a vector store?** Stored
|
|
79
|
+
history is raw text for one channel. Niadra keeps derived facts and open items with evidence,
|
|
80
|
+
resolves identity across channels and systems, closes items when a system of record confirms an
|
|
81
|
+
action, and filters what each agent may read by the verification level of the conversation.
|
|
82
|
+
|
|
83
|
+
**What happens if Niadra is slow or down?** The agent keeps answering without the memory. Every
|
|
84
|
+
call has its own time budget (150 ms for voice context, 300 ms otherwise) and resolves with an
|
|
85
|
+
error value instead of throwing, unless you ask for strict mode.
|
|
86
|
+
|
|
87
|
+
**What about privacy and LGPD or GDPR?** Items carry a verification level and a purpose, and the
|
|
88
|
+
policy decides what each agent sees. Every read leaves a receipt, and a person can be erased or
|
|
89
|
+
exported on request. The SDK never logs handles or message text.
|
|
90
|
+
|
|
91
|
+
**Which models and frameworks does it work with?** Any. The context is text you place in your
|
|
92
|
+
prompt, the tools follow the common function-calling format, and `wrap()` covers
|
|
93
|
+
OpenAI-compatible clients.
|
|
94
|
+
|
|
95
|
+
## Concepts
|
|
96
|
+
|
|
97
|
+
### Keys and endpoints
|
|
98
|
+
|
|
99
|
+
A source key looks like `nia_sk_<live|test>_<region>_<space>_<key_id>_<secret>`. The SDK derives the endpoint from it, `https://<space>.<region>.api.niadra.com`, so there is nothing else to configure. `live` keys reach production spaces and `test` keys reach sandbox spaces, which never share data.
|
|
100
|
+
|
|
101
|
+
Pass `baseURL` (or set `NIADRA_BASE_URL`) to point at the local emulator or a private endpoint.
|
|
102
|
+
|
|
103
|
+
### Handles
|
|
104
|
+
|
|
105
|
+
A handle identifies a customer in some channel or system. Use the builders so the type and scope are right:
|
|
106
|
+
|
|
107
|
+
```ts
|
|
108
|
+
handles.phone("+5511987654321");
|
|
109
|
+
handles.email("marina@example.com");
|
|
110
|
+
handles.waId("5511987654321");
|
|
111
|
+
handles.systemId("C-0042", "crm"); // scope: the system that issued the id
|
|
112
|
+
handles.emailDomain("acme.com"); // an organization, not a person
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
Handles are personal data. The SDK only ever sends them in request bodies, never in URLs, and never writes them to logs.
|
|
116
|
+
|
|
117
|
+
### Context
|
|
118
|
+
|
|
119
|
+
```ts
|
|
120
|
+
const ctx = await niadra.context({
|
|
121
|
+
subject: marina,
|
|
122
|
+
conversation_id: "wa-8812",
|
|
123
|
+
view: "chat", // "voice", "brief", "full", "account", "task:billing", ...
|
|
124
|
+
verification: "V1", // what the customer has proven in this conversation
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
const system = `${agentInstructions}\n\n${ctx.text}`;
|
|
128
|
+
const messages = [...history, { role: "user", content: `${ctx.suffix}\n\n${userTurn}` }];
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
- `text` is the pack. Inside a conversation the server pins it: the same bytes on every turn, so your model provider's prompt cache keeps hitting.
|
|
132
|
+
- `suffix` holds what changes turn by turn: the delta and the live turns from other channels that the pack has not absorbed yet. It belongs at the end of the prompt, after the conversation.
|
|
133
|
+
- `delta: true` asks for what changed since this agent last read the subject. The server sends each change once, so the SDK hands each delta out once too, even one fetched by a background refresh; `conversation()` keeps them for you.
|
|
134
|
+
- `source` says where the result came from (`network`, `cache`, `stale`, `fallback` or `none`), and `error` says what went wrong when something did.
|
|
135
|
+
- Pass `object: "invoice:erp:0823"` instead of `subject` when the task is about a business object, and `about` for the account a person acts for.
|
|
136
|
+
|
|
137
|
+
### Conversations
|
|
138
|
+
|
|
139
|
+
`conversation()` wraps one customer thread: it reads the pack the server pins, keeps the deltas, captures turns and ends the conversation.
|
|
140
|
+
|
|
141
|
+
```ts
|
|
142
|
+
const convo = niadra.conversation({ subject: marina, channel: "whatsapp", conversation_id: "wa-8812" });
|
|
143
|
+
|
|
144
|
+
convo.customer(inbound.text, { idempotency_key: inbound.id });
|
|
145
|
+
const ctx = await convo.context();
|
|
146
|
+
convo.markInjected(ctx); // when the pack went into the prompt
|
|
147
|
+
const reply = await callModel(ctx.text, history, ctx.suffix);
|
|
148
|
+
convo.agent(reply); // carries the context stamp
|
|
149
|
+
|
|
150
|
+
await convo.verify({ method: "otp_whatsapp", level: "V2" }); // later reads use the new level
|
|
151
|
+
await convo.handoff({ target: "human", reason: "asked for a person" });
|
|
152
|
+
await convo.end();
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
After the first pack, each read also asks for the delta, and the conversation keeps every delta it receives, in order, in `suffix`, ahead of the live turns. When the server pins a new pack, after `verify()` for instance, the kept deltas are dropped: the new pack already has them. A read with `query` is a one-off and leaves them alone.
|
|
156
|
+
|
|
157
|
+
Call `markInjected()` each time you put the pack in a prompt. The agent's turns and actions that follow carry it as `context_stamp`, with the pack's etag, which is how Niadra tells a context that arrived after the agent spoke from one the agent had and did not use. `timings` keeps the first injection and the first agent turn, for your own checks.
|
|
158
|
+
|
|
159
|
+
### Wrapping an OpenAI-compatible client
|
|
160
|
+
|
|
161
|
+
```ts
|
|
162
|
+
import OpenAI from "openai";
|
|
163
|
+
import { wrap } from "@niadra/sdk";
|
|
164
|
+
|
|
165
|
+
const openai = wrap(new OpenAI(), convo);
|
|
166
|
+
const completion = await openai.chat.completions.create({ model: "gpt-4.1", messages });
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
Every `chat.completions.create` and `chat.completions.parse` call through the wrapper, streaming or not, gets the pack after your leading system messages and the suffix at the end. The injection is stamped, and the model's answer (its first choice) is recorded as the agent's turn: at once, or when a stream ends or you stop reading it. `.withResponse()` keeps working and records too; `.asResponse()` returns the raw HTTP response, so nothing is recorded then. Pass a function instead of a conversation to pick one per call; when it returns `null`, the call passes through untouched. Nothing the wrapper does can fail your call: a context it cannot fetch is left out, and a failure to record the answer is logged, without content.
|
|
170
|
+
|
|
171
|
+
### Tasks
|
|
172
|
+
|
|
173
|
+
Internal agents (billing, collections, triage) work in tasks rather than conversations. A task centers its pack on its object, keeps deltas and stamps like a conversation, scopes the cache, groups events and ends with `task.ended`.
|
|
174
|
+
|
|
175
|
+
```ts
|
|
176
|
+
const task = niadra.task({ channel: "billing-agent", object: "invoice:erp:0823", view: "task:billing" });
|
|
177
|
+
const ctx = await task.context();
|
|
178
|
+
task.markInjected(ctx);
|
|
179
|
+
task.action({ operation: "credit", result: "R$ 40 credited", closes: { object: { type: "invoice", namespace: "erp", id: "0823" }, operation: "credit" } });
|
|
180
|
+
await task.end();
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
### Writing
|
|
184
|
+
|
|
185
|
+
| Method | Records | Delivery |
|
|
186
|
+
| --- | --- | --- |
|
|
187
|
+
| `track(event)` | A message, a system event (`kind: "system_event"`) or an action (`kind: "action"`) | Queued, batched |
|
|
188
|
+
| `action(event)` | What an agent did in a system of record; `closes` resolves the open item it fulfils | Queued, batched |
|
|
189
|
+
| `identify({ handles })` | That several handles belong to the same person or organization | Sent at once |
|
|
190
|
+
| `verify({ handle, method, level })` | That the customer proved who they are, for one conversation or task | Sent at once |
|
|
191
|
+
| `handoff({ conversation_id, target })` | A transfer to a human or another agent | Sent at once |
|
|
192
|
+
| `feedback({ subject, action, ... })` | A correction of what Niadra derived: `retract_fact`, `correct_fact`, `resolve_open_item`, `conversation_outcome` | Sent at once |
|
|
193
|
+
|
|
194
|
+
Every item carries an idempotency key: the provider's message id when you pass one, a UUIDv7 otherwise. Retrying the same event is harmless.
|
|
195
|
+
|
|
196
|
+
`identify()`, `verify()`, `handoff()` and `feedback()` resolve to `{ ok, idempotency_key, error }` once the server has answered. A correction is recorded as an event, so it is audited like any other. A `context()` call made after `identify()` or `verify()` resolves already reflects it.
|
|
197
|
+
|
|
198
|
+
### History navigation
|
|
199
|
+
|
|
200
|
+
When the pack is not enough, search the customer's history. Each call resolves to `{ data, error }`, with exactly one of the two set:
|
|
201
|
+
|
|
202
|
+
```ts
|
|
203
|
+
const { data, error } = await niadra.search({ subject: marina, query: "technician visit", filters: { channels: ["voice"] } });
|
|
204
|
+
const page = await niadra.timeline({ subject: marina, limit: 20 });
|
|
205
|
+
|
|
206
|
+
const first = data?.items[0];
|
|
207
|
+
if (first) {
|
|
208
|
+
const opened = await niadra.open(first.id, { conversation_id: "wa-8812" });
|
|
209
|
+
}
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
`search()` also reports recurrence: how many times the same kind of issue came back, and how it was last resolved.
|
|
213
|
+
|
|
214
|
+
### Business objects
|
|
215
|
+
|
|
216
|
+
```ts
|
|
217
|
+
const { data: invoice } = await niadra.objectState("invoice:erp:0823"); // state, as_of, open items
|
|
218
|
+
const { data: page } = await niadra.objectTimeline("invoice:erp:0823", { limit: 20 });
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
The state comes only from what the systems of record reported; an agent's action counts once a system confirms it. The timeline lists system events and agent actions, newest first, never what anyone said. Object ids are record ids, not personal data, so they go in the URL; an id with a slash cannot be addressed that way.
|
|
222
|
+
|
|
223
|
+
### Media
|
|
224
|
+
|
|
225
|
+
```ts
|
|
226
|
+
const { data: upload } = await niadra.uploadMedia({ data: recording, content_type: "audio/wav", subject: marina });
|
|
227
|
+
if (upload) {
|
|
228
|
+
convo.track({ speaker: "customer", content: { type: "audio", media_ref: upload.media_ref, media_sha256: upload.media_sha256, transcript } });
|
|
229
|
+
}
|
|
230
|
+
```
|
|
231
|
+
|
|
232
|
+
Media never travels inside an event. `uploadMedia()` takes a `Uint8Array`, `ArrayBuffer` or `Blob`, reserves an upload, sends the bytes straight to storage over a signed URL (HTTPS only, with exactly the headers the signature covers and nothing else, so never your key or default headers; storage checks the body against the declared size and digest), and resolves with the reference and digest for the event. With `subject`, the file is stored under that person, so erasing them erases it even if no event ever references it. Hashing uses Web Crypto, which Node 18 only exposes behind a flag.
|
|
233
|
+
|
|
234
|
+
### Tools for any model
|
|
235
|
+
|
|
236
|
+
`tools(subject)` returns the navigation kit as function-calling definitions, with the customer bound in the SDK rather than in the tool arguments. The model chooses what to look for, never whom it is about, so a prompt injection has no argument to switch customers with.
|
|
237
|
+
|
|
238
|
+
```ts
|
|
239
|
+
const kit = convo.tools(); // or niadra.tools(marina, { conversation_id: "wa-8812" })
|
|
240
|
+
|
|
241
|
+
const response = await openai.chat.completions.create({ model, messages, tools: kit.definitions });
|
|
242
|
+
for (const call of response.choices[0].message.tool_calls ?? []) {
|
|
243
|
+
if (kit.has(call.function.name)) {
|
|
244
|
+
messages.push({ role: "tool", tool_call_id: call.id, content: await kit.call(call.function.name, call.function.arguments) });
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
The definitions use the `{ type: "function", function: { name, description, parameters } }` shape. For APIs that expect `{ name, description, input_schema }`, map `function.parameters` to `input_schema`.
|
|
250
|
+
|
|
251
|
+
### Subject tokens for MCP
|
|
252
|
+
|
|
253
|
+
`subjectToken()` mints a signed token, valid for 15 minutes, that binds one customer, conversation and verification level. Call it from your backend and pass the token to the MCP connection; tools served over MCP then read that customer only.
|
|
254
|
+
|
|
255
|
+
```ts
|
|
256
|
+
const { data } = await niadra.subjectToken({ subject: marina, conversation_id: "wa-8812", verification: "V1" });
|
|
257
|
+
```
|
|
258
|
+
|
|
259
|
+
## Failure behavior
|
|
260
|
+
|
|
261
|
+
Memory should make an agent better, never make it fail. By default:
|
|
262
|
+
|
|
263
|
+
| Situation | What happens |
|
|
264
|
+
| --- | --- |
|
|
265
|
+
| No API key | The client is a no-op. Every method resolves with an empty result and nothing is sent. One warning is logged. |
|
|
266
|
+
| Invalid arguments | Logged and dropped. `context()` resolves with empty `text`; `track()` returns `null`. |
|
|
267
|
+
| Timeout, network error, 5xx | Reads resolve with an empty result, or with the last good pack of the conversation (`source: "fallback"`). |
|
|
268
|
+
| A `degraded` answer while a good pack is cached | The good pack is kept and served (`source: "fallback"`). |
|
|
269
|
+
| 401 or 403 | Not treated as an outage: the cached packs are dropped (all of them on 401, the one requested on 403) and `context()` returns empty. Revoking a key also stops what the process had cached. |
|
|
270
|
+
| 421 (the space moved to another cell) | Retried at once, up to three attempts. |
|
|
271
|
+
| 429 on a batch | Retried after `Retry-After`. |
|
|
272
|
+
| Batch failure | Retried with exponential backoff and jitter, three attempts. 4xx answers other than 408, 421 and 429 are never retried. A batch that still fails is dropped and logged. |
|
|
273
|
+
| Queue full (10,000 items) | New events are dropped and logged. |
|
|
274
|
+
| Server rejects one item of a batch (207) | Only that item fails; the rest are stored. |
|
|
275
|
+
|
|
276
|
+
Every read has its own time budget, independent of your platform's:
|
|
277
|
+
|
|
278
|
+
| Call | Default |
|
|
279
|
+
| --- | --- |
|
|
280
|
+
| `context()` | 300 ms, 150 ms with `view: "voice"` |
|
|
281
|
+
| `search()`, `timeline()`, `open()`, `objectState()`, `objectTimeline()` | 600 ms, 300 ms through voice conversations and voice-bound tools |
|
|
282
|
+
| `subjectToken()` | 2 s |
|
|
283
|
+
| Each attempt of a batch, `feedback()` or an upload reservation | 5 s |
|
|
284
|
+
| Each attempt of an `uploadMedia()` transfer | 60 s |
|
|
285
|
+
|
|
286
|
+
Override them with `timeouts`, or per call with `{ timeout }`. Pass `{ signal }` to cancel a call.
|
|
287
|
+
|
|
288
|
+
### The context cache
|
|
289
|
+
|
|
290
|
+
Inside a conversation or task, packs are cached in memory:
|
|
291
|
+
|
|
292
|
+
- younger than 10 s: returned without a request;
|
|
293
|
+
- up to 10 minutes older: returned at once while one background request refreshes it;
|
|
294
|
+
- when a request fails: the last good pack, if it is less than 30 minutes old;
|
|
295
|
+
- at most 1,000 packs, the least recently used evicted first.
|
|
296
|
+
|
|
297
|
+
Refreshes send the cached ETag, so an unchanged pack costs a `not_modified` answer instead of the
|
|
298
|
+
full text, and only one background refresh per pack runs at a time. A 401 or 403 is not an
|
|
299
|
+
outage: the cached packs go (all of them on 401, the one requested on 403), so cutting a vendor's
|
|
300
|
+
access also cuts what it had cached. A plain read and a `delta` read of one conversation share one
|
|
301
|
+
entry, and each delta is handed out once.
|
|
302
|
+
|
|
303
|
+
Configure it with `cache: { ttlMs, staleWhileRevalidateMs, maxStaleMs, maxEntries }`, or turn it off with `cache: false`.
|
|
304
|
+
|
|
305
|
+
### Strict mode
|
|
306
|
+
|
|
307
|
+
`new Niadra({ strict: true })` throws instead of logging: configuration errors from the constructor, validation errors from `track()`, request errors from reads, and lost batches from `flush()`. Use it in tests and during development.
|
|
308
|
+
|
|
309
|
+
## Runtimes and shutdown
|
|
310
|
+
|
|
311
|
+
- **Long-running Node services:** queued events are flushed when the event loop runs out of work (`beforeExit`). That event does not fire on signals or `process.exit()`, so call `await niadra.shutdown()` in your SIGTERM handler.
|
|
312
|
+
- **Serverless functions:** `await niadra.flush()` before returning.
|
|
313
|
+
- **Edge runtimes:** pass the flush to the platform, for example `ctx.waitUntil(niadra.flush())`.
|
|
314
|
+
|
|
315
|
+
Create one client per process and share it: it owns the queue and the cache.
|
|
316
|
+
|
|
317
|
+
## Configuration
|
|
318
|
+
|
|
319
|
+
```ts
|
|
320
|
+
new Niadra({
|
|
321
|
+
apiKey: "nia_sk_live_...", // default: NIADRA_API_KEY
|
|
322
|
+
baseURL: "http://localhost:4010", // default: NIADRA_BASE_URL, then derived from the key
|
|
323
|
+
timeouts: { context: 300, contextVoice: 150, navigation: 600, navigationVoice: 300, write: 5000, token: 2000, upload: 60_000 },
|
|
324
|
+
cache: { ttlMs: 10_000, staleWhileRevalidateMs: 600_000, maxStaleMs: 1_800_000, maxEntries: 1000 },
|
|
325
|
+
queue: { flushAt: 15, flushIntervalMs: 1000, maxBatchSize: 100, maxQueueSize: 10_000, maxAttempts: 3 },
|
|
326
|
+
strict: false,
|
|
327
|
+
flushOnExit: true,
|
|
328
|
+
logger: console, // anything with debug, warn and error
|
|
329
|
+
fetch: globalThis.fetch,
|
|
330
|
+
defaultHeaders: {},
|
|
331
|
+
});
|
|
332
|
+
```
|
|
333
|
+
|
|
334
|
+
Log lines carry status codes, error codes and request ids. They never carry handles, message text or the API key.
|
|
335
|
+
|
|
336
|
+
## Errors
|
|
337
|
+
|
|
338
|
+
All errors extend `NiadraError`. API errors are `NiadraAPIError` with `status`, `code` (from the problem document), `requestId` and `problem`; `NiadraAuthenticationError` (401), `NiadraPermissionError` (403) and `NiadraRateLimitError` (429, with `retryAfterMs`) narrow it. The others are `NiadraTimeoutError`, `NiadraConnectionError`, `NiadraAbortError`, `NiadraValidationError` and `NiadraConfigError`.
|
|
339
|
+
|
|
340
|
+
Include `requestId` when you contact support.
|
|
341
|
+
|
|
342
|
+
## Development
|
|
343
|
+
|
|
344
|
+
```sh
|
|
345
|
+
pnpm install
|
|
346
|
+
pnpm check # typecheck, lint, tests
|
|
347
|
+
pnpm build # ESM and CommonJS into dist/
|
|
348
|
+
```
|
|
349
|
+
|
|
350
|
+
## Em português
|
|
351
|
+
|
|
352
|
+
A Niadra é a memória de clientes compartilhada por todos os agentes de IA de uma empresa: o agente
|
|
353
|
+
do WhatsApp, o de voz, o de cobrança e o time humano leem a mesma memória antes de agir e registram
|
|
354
|
+
o que disseram e fizeram. Este pacote conecta um agente em TypeScript ou JavaScript a essa memória:
|
|
355
|
+
`context()` antes de chamar o modelo, `track()` depois, e `action()` quando o agente faz algo num
|
|
356
|
+
sistema. Documentação em [niadra.com/docs](https://niadra.com/docs) e contato em
|
|
357
|
+
[niadra.com/enterprise](https://niadra.com/enterprise).
|
|
358
|
+
|
|
359
|
+
## License
|
|
360
|
+
|
|
361
|
+
Apache 2.0. See [LICENSE](./LICENSE).
|