@atlasent/sdk 1.5.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/LICENSE +190 -0
- package/README.md +133 -0
- package/dist/behavior.cjs +175 -0
- package/dist/behavior.cjs.map +1 -0
- package/dist/behavior.d.cts +241 -0
- package/dist/behavior.d.ts +241 -0
- package/dist/behavior.js +143 -0
- package/dist/behavior.js.map +1 -0
- package/dist/hono.cjs +580 -0
- package/dist/hono.cjs.map +1 -0
- package/dist/hono.d.cts +109 -0
- package/dist/hono.d.ts +109 -0
- package/dist/hono.js +550 -0
- package/dist/hono.js.map +1 -0
- package/dist/index.cjs +763 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +620 -0
- package/dist/index.d.ts +620 -0
- package/dist/index.js +723 -0
- package/dist/index.js.map +1 -0
- package/dist/protect-BKxcoR_2.d.cts +159 -0
- package/dist/protect-BKxcoR_2.d.ts +159 -0
- package/package.json +101 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
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 describing the origin of the Work and
|
|
141
|
+
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
|
+
Copyright 2026 AtlaSent Systems Inc.
|
|
179
|
+
|
|
180
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
181
|
+
you may not use this file except in compliance with the License.
|
|
182
|
+
You may obtain a copy of the License at
|
|
183
|
+
|
|
184
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
185
|
+
|
|
186
|
+
Unless required by applicable law or agreed to in writing, software
|
|
187
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
188
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
189
|
+
See the License for the specific language governing permissions and
|
|
190
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
# @atlasent/sdk
|
|
2
|
+
|
|
3
|
+
Execution-time authorization for AI agents, in TypeScript. Two methods, zero runtime dependencies, one function call per decision.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
npm i @atlasent/sdk
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
## Quickstart
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
import { AtlaSentClient } from "@atlasent/sdk";
|
|
13
|
+
|
|
14
|
+
const client = new AtlaSentClient({ apiKey: process.env.ATLASENT_API_KEY! });
|
|
15
|
+
|
|
16
|
+
const result = await client.evaluate({
|
|
17
|
+
agent: "clinical-data-agent",
|
|
18
|
+
action: "modify_patient_record",
|
|
19
|
+
context: { user: "dr_smith", environment: "production" },
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
if (result.decision === "ALLOW") {
|
|
23
|
+
// execute the action
|
|
24
|
+
} else {
|
|
25
|
+
console.warn("Blocked:", result.reason);
|
|
26
|
+
}
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
That's it. `evaluate()` calls the AtlaSent policy engine, generates a hash-chained audit entry (21 CFR Part 11 / GxP-ready), and returns a result you branch on. A clean `DENY` is **not** thrown — network / server / auth failures are.
|
|
30
|
+
|
|
31
|
+
## Two methods, that's the whole surface
|
|
32
|
+
|
|
33
|
+
```ts
|
|
34
|
+
client.evaluate({ agent, action, context? })
|
|
35
|
+
// → { decision: "ALLOW" | "DENY", permitId, reason, auditHash, timestamp }
|
|
36
|
+
|
|
37
|
+
client.verifyPermit({ permitId, agent?, action?, context? })
|
|
38
|
+
// → { verified, outcome, permitHash, timestamp }
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
`verifyPermit()` confirms a previously-issued permit end-to-end — use it as a second-factor gate (e.g., in a CI deploy pipeline before side-effects run).
|
|
42
|
+
|
|
43
|
+
## CI deploy-gate pattern
|
|
44
|
+
|
|
45
|
+
```ts
|
|
46
|
+
import { AtlaSentClient } from "@atlasent/sdk";
|
|
47
|
+
|
|
48
|
+
const client = new AtlaSentClient({ apiKey: process.env.ATLASENT_API_KEY! });
|
|
49
|
+
|
|
50
|
+
const evaluation = await client.evaluate({
|
|
51
|
+
agent: "ci-deploy-bot",
|
|
52
|
+
action: "deploy_to_production",
|
|
53
|
+
context: { service: "billing-api", commit: process.env.GIT_SHA },
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
if (evaluation.decision !== "ALLOW") {
|
|
57
|
+
console.error("Deploy blocked:", evaluation.reason);
|
|
58
|
+
process.exit(1);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const verification = await client.verifyPermit({
|
|
62
|
+
permitId: evaluation.permitId,
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
if (!verification.verified) {
|
|
66
|
+
console.error("Permit verification failed — aborting");
|
|
67
|
+
process.exit(1);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// runDeploy();
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
See [`examples/deploy-gate.ts`](./examples/deploy-gate.ts) for a complete CI-shaped script.
|
|
74
|
+
|
|
75
|
+
## Constructor options
|
|
76
|
+
|
|
77
|
+
```ts
|
|
78
|
+
new AtlaSentClient({
|
|
79
|
+
apiKey: "ask_live_...", // required
|
|
80
|
+
baseUrl: "https://api.atlasent.io", // default
|
|
81
|
+
timeoutMs: 10_000, // default — per-request
|
|
82
|
+
fetch: customFetch, // default: globalThis.fetch
|
|
83
|
+
});
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
## Error handling
|
|
87
|
+
|
|
88
|
+
The SDK throws exactly one error type — `AtlaSentError` — with a flat shape that mirrors Stripe / Octokit / Supabase conventions:
|
|
89
|
+
|
|
90
|
+
```ts
|
|
91
|
+
import { AtlaSentError } from "@atlasent/sdk";
|
|
92
|
+
|
|
93
|
+
try {
|
|
94
|
+
await client.evaluate({ agent: "a", action: "b" });
|
|
95
|
+
} catch (err) {
|
|
96
|
+
if (err instanceof AtlaSentError) {
|
|
97
|
+
console.error(err.code, err.status, err.requestId, err.retryAfterMs);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
| `err.code` | When it's thrown |
|
|
103
|
+
|--------------------|---------------------------------------------------------|
|
|
104
|
+
| `invalid_api_key` | HTTP 401 |
|
|
105
|
+
| `forbidden` | HTTP 403 |
|
|
106
|
+
| `rate_limited` | HTTP 429 (check `err.retryAfterMs`) |
|
|
107
|
+
| `bad_request` | HTTP 4xx (other than 401/403/429) |
|
|
108
|
+
| `server_error` | HTTP 5xx |
|
|
109
|
+
| `timeout` | `timeoutMs` exceeded |
|
|
110
|
+
| `network` | DNS / connection failure, fetch threw |
|
|
111
|
+
| `bad_response` | non-JSON body or missing required fields |
|
|
112
|
+
|
|
113
|
+
Every `AtlaSentError` carries `err.requestId` — the UUID the SDK sent as `X-Request-ID`, correlatable in your server logs.
|
|
114
|
+
|
|
115
|
+
## Design choices
|
|
116
|
+
|
|
117
|
+
- **Fail-closed.** A clean `DENY` is returned so your code explicitly handles it; every other failure throws, so no action proceeds silently.
|
|
118
|
+
- **Native `fetch` only.** No axios, no polyfills. Node 20+ has everything we need.
|
|
119
|
+
- **Zero runtime dependencies.** Strongly typed via plain TS interfaces.
|
|
120
|
+
- **Bearer-token auth.** `Authorization: Bearer <apiKey>` so request-body logs never capture the key. (The SDK also includes `api_key` in the body for wire compat with the current policy engine; that will be removed once the server drops body-based auth.)
|
|
121
|
+
|
|
122
|
+
## Requirements
|
|
123
|
+
|
|
124
|
+
- Node.js **20** or newer (native `fetch`, `AbortSignal.timeout`, `crypto.randomUUID`).
|
|
125
|
+
- TypeScript **5.0+** for best type-inference ergonomics (older is fine — types are plain interfaces).
|
|
126
|
+
|
|
127
|
+
## Related
|
|
128
|
+
|
|
129
|
+
- **Python SDK:** same repo, [`../python/`](../python/README.md). Wire-compatible.
|
|
130
|
+
|
|
131
|
+
## License
|
|
132
|
+
|
|
133
|
+
Apache-2.0 — see [LICENSE](./LICENSE).
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/behavior.ts
|
|
21
|
+
var behavior_exports = {};
|
|
22
|
+
__export(behavior_exports, {
|
|
23
|
+
ConsentDeniedError: () => ConsentDeniedError,
|
|
24
|
+
ConsentManager: () => ConsentManager,
|
|
25
|
+
DEFAULT_CONSENT: () => DEFAULT_CONSENT,
|
|
26
|
+
InMemoryBehaviorLedger: () => InMemoryBehaviorLedger,
|
|
27
|
+
MemoryStorage: () => MemoryStorage,
|
|
28
|
+
SENSITIVE_CATEGORIES: () => SENSITIVE_CATEGORIES,
|
|
29
|
+
StateEventCache: () => StateEventCache,
|
|
30
|
+
redactStateSnapshot: () => redactStateSnapshot
|
|
31
|
+
});
|
|
32
|
+
module.exports = __toCommonJS(behavior_exports);
|
|
33
|
+
var SENSITIVE_CATEGORIES = [
|
|
34
|
+
"behavior.health.mental",
|
|
35
|
+
"behavior.health.adherence",
|
|
36
|
+
"behavior.financial",
|
|
37
|
+
"behavior.minor"
|
|
38
|
+
];
|
|
39
|
+
var DEFAULT_CONSENT = Object.freeze({
|
|
40
|
+
share_state_summaries: false,
|
|
41
|
+
private_only_mode: false
|
|
42
|
+
});
|
|
43
|
+
var MemoryStorage = class {
|
|
44
|
+
store = /* @__PURE__ */ new Map();
|
|
45
|
+
get(key) {
|
|
46
|
+
return this.store.get(key) ?? null;
|
|
47
|
+
}
|
|
48
|
+
set(key, value) {
|
|
49
|
+
this.store.set(key, value);
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
var ConsentManager = class {
|
|
53
|
+
key;
|
|
54
|
+
storage;
|
|
55
|
+
defaults;
|
|
56
|
+
constructor(opts) {
|
|
57
|
+
this.key = `atlasent.behavior.consent.${opts.userId}`;
|
|
58
|
+
this.storage = opts.storage ?? new MemoryStorage();
|
|
59
|
+
this.defaults = opts.defaults ?? DEFAULT_CONSENT;
|
|
60
|
+
}
|
|
61
|
+
get() {
|
|
62
|
+
const raw = this.storage.get(this.key);
|
|
63
|
+
if (!raw) return { ...this.defaults };
|
|
64
|
+
try {
|
|
65
|
+
const parsed = JSON.parse(raw);
|
|
66
|
+
return { ...this.defaults, ...parsed };
|
|
67
|
+
} catch {
|
|
68
|
+
return { ...this.defaults };
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
set(patch) {
|
|
72
|
+
const next = { ...this.get(), ...patch };
|
|
73
|
+
this.storage.set(this.key, JSON.stringify(next));
|
|
74
|
+
return next;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* The single decision point: may we emit a `BehaviorEvent` for
|
|
78
|
+
* this `category` to this `receiver`? Returns `false` whenever
|
|
79
|
+
* any of the following is true:
|
|
80
|
+
*
|
|
81
|
+
* - `private_only_mode` is on.
|
|
82
|
+
* - `share_state_summaries` is off.
|
|
83
|
+
* - A `receivers` allowlist exists and the `(receiver, category)`
|
|
84
|
+
* pair is not in it.
|
|
85
|
+
*/
|
|
86
|
+
canEmit(receiver, category) {
|
|
87
|
+
const c = this.get();
|
|
88
|
+
if (c.private_only_mode) return false;
|
|
89
|
+
if (!c.share_state_summaries) return false;
|
|
90
|
+
if (c.receivers) {
|
|
91
|
+
const allowed = c.receivers[receiver] ?? [];
|
|
92
|
+
if (!allowed.includes(category)) return false;
|
|
93
|
+
}
|
|
94
|
+
return true;
|
|
95
|
+
}
|
|
96
|
+
};
|
|
97
|
+
function redactStateSnapshot(s) {
|
|
98
|
+
return {
|
|
99
|
+
emotional_state: s.emotional_state,
|
|
100
|
+
intensity: s.intensity,
|
|
101
|
+
stress_level: s.stress_level,
|
|
102
|
+
pressure_level: s.pressure_level,
|
|
103
|
+
body_state: s.body_state,
|
|
104
|
+
cognitive_load: s.cognitive_load,
|
|
105
|
+
readiness_level: s.readiness_level
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
var ConsentDeniedError = class extends Error {
|
|
109
|
+
constructor(receiver, category) {
|
|
110
|
+
super(
|
|
111
|
+
`Consent denies emit to receiver=${receiver} category=${category}`
|
|
112
|
+
);
|
|
113
|
+
this.receiver = receiver;
|
|
114
|
+
this.category = category;
|
|
115
|
+
this.name = "ConsentDeniedError";
|
|
116
|
+
}
|
|
117
|
+
receiver;
|
|
118
|
+
category;
|
|
119
|
+
code = "consent_denied";
|
|
120
|
+
};
|
|
121
|
+
var InMemoryBehaviorLedger = class {
|
|
122
|
+
constructor(opts) {
|
|
123
|
+
this.opts = opts;
|
|
124
|
+
}
|
|
125
|
+
opts;
|
|
126
|
+
events = [];
|
|
127
|
+
async emit(event) {
|
|
128
|
+
const receiver = this.opts.receiver ?? "in-memory";
|
|
129
|
+
if (!this.opts.consent.canEmit(receiver, event.category)) {
|
|
130
|
+
throw new ConsentDeniedError(receiver, event.category);
|
|
131
|
+
}
|
|
132
|
+
this.events.push(event);
|
|
133
|
+
}
|
|
134
|
+
/** Read all events accepted so far. Test/demo helper. */
|
|
135
|
+
list() {
|
|
136
|
+
return [...this.events];
|
|
137
|
+
}
|
|
138
|
+
/** Clear the in-memory store. Test helper. */
|
|
139
|
+
clear() {
|
|
140
|
+
this.events.length = 0;
|
|
141
|
+
}
|
|
142
|
+
};
|
|
143
|
+
var StateEventCache = class {
|
|
144
|
+
constructor(capacity = 10) {
|
|
145
|
+
this.capacity = capacity;
|
|
146
|
+
if (capacity <= 0) {
|
|
147
|
+
throw new RangeError("capacity must be > 0");
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
capacity;
|
|
151
|
+
buf = [];
|
|
152
|
+
add(summary) {
|
|
153
|
+
this.buf.push(summary);
|
|
154
|
+
if (this.buf.length > this.capacity) this.buf.shift();
|
|
155
|
+
}
|
|
156
|
+
recent(n) {
|
|
157
|
+
const k = n ?? this.buf.length;
|
|
158
|
+
return this.buf.slice(-k);
|
|
159
|
+
}
|
|
160
|
+
clear() {
|
|
161
|
+
this.buf.length = 0;
|
|
162
|
+
}
|
|
163
|
+
};
|
|
164
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
165
|
+
0 && (module.exports = {
|
|
166
|
+
ConsentDeniedError,
|
|
167
|
+
ConsentManager,
|
|
168
|
+
DEFAULT_CONSENT,
|
|
169
|
+
InMemoryBehaviorLedger,
|
|
170
|
+
MemoryStorage,
|
|
171
|
+
SENSITIVE_CATEGORIES,
|
|
172
|
+
StateEventCache,
|
|
173
|
+
redactStateSnapshot
|
|
174
|
+
});
|
|
175
|
+
//# sourceMappingURL=behavior.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/behavior.ts"],"sourcesContent":["/**\n * @atlasent/sdk/behavior — consent + redaction helpers for the v2\n * Behavior Conditioning Layer.\n *\n * See `atlasent-docs/docs/V2_BEHAVIOR_CONDITIONING_LAYER.md` for the\n * architecture this module implements.\n *\n * Quick start:\n *\n * ```ts\n * import {\n * ConsentManager,\n * InMemoryBehaviorLedger,\n * redactStateSnapshot,\n * type StateSnapshot,\n * } from \"@atlasent/sdk/behavior\";\n *\n * const consent = new ConsentManager({ userId: \"u_123\" });\n * const ledger = new InMemoryBehaviorLedger();\n *\n * const snapshot: StateSnapshot = { ... };\n * const summary = redactStateSnapshot(snapshot);\n *\n * if (consent.canEmit(\"ledgers-me\", \"behavior.health.mental\")) {\n * await ledger.emit({\n * user_id: snapshot.user_id,\n * source: \"hicoach\",\n * category: \"behavior.health.mental\",\n * entry_state_summary: summary,\n * exit_state_summary: null,\n * relief_delta: null,\n * confidence_score: 1,\n * timestamp: new Date().toISOString(),\n * });\n * }\n * ```\n *\n * The MVP is pure and on-device — no HTTP calls. A future\n * `RemoteBehaviorLedger` will POST to `/v1/behavior/events` once\n * the atlasent-api endpoint ships.\n */\n\n// ---------------------------------------------------------------------------\n// Sensitive-category vocabulary\n// ---------------------------------------------------------------------------\n\n/**\n * Sensitive-category slugs used by behavior policies. Keep in sync\n * with `gxp-starter/packs/hipaa/` rules and\n * `atlasent-api`'s `target.category` field.\n */\nexport type SensitiveCategory =\n | \"behavior.health.mental\"\n | \"behavior.health.adherence\"\n | \"behavior.financial\"\n | \"behavior.minor\";\n\nexport const SENSITIVE_CATEGORIES: readonly SensitiveCategory[] = [\n \"behavior.health.mental\",\n \"behavior.health.adherence\",\n \"behavior.financial\",\n \"behavior.minor\",\n] as const;\n\n// ---------------------------------------------------------------------------\n// Domain types — mirror the model in `bettyc925/hicoach/lib/hicoach/types.ts`.\n// ---------------------------------------------------------------------------\n\nexport type EmotionalState =\n | \"tense\"\n | \"anxious\"\n | \"overwhelmed\"\n | \"flat\"\n | \"frustrated\"\n | \"uncertain\"\n | \"tired\"\n | \"okay\";\n\nexport type BodyState =\n | \"tight\"\n | \"heavy\"\n | \"restless\"\n | \"numb\"\n | \"buzzing\"\n | \"settled\";\n\nexport type ReadinessLevel = \"low\" | \"medium\" | \"high\";\n\n/**\n * A single moment captured before/after a regulation session.\n *\n * This is the **on-device** shape with all raw fields. It is never\n * emitted to a ledger; only the {@link StateEventSummary} projection\n * crosses an app boundary.\n */\nexport interface StateSnapshot {\n id: string;\n user_id: string;\n emotional_state: EmotionalState;\n /** 0..10 */\n intensity: number;\n /** 0..10 */\n stress_level: number;\n /** 0..10 */\n pressure_level: number;\n body_state: BodyState;\n /** 0..10 */\n cognitive_load: number;\n readiness_level: ReadinessLevel;\n /** 0..1 — how sure the user feels about the rating */\n confidence_score: number;\n /** ISO 8601 */\n created_at: string;\n /** Optional free-form note. NEVER part of the redacted summary. */\n note?: string;\n}\n\n/**\n * Redacted summary projection — the only shape that crosses an app\n * boundary. Contains no raw text, no IDs, no timestamps.\n */\nexport interface StateEventSummary {\n emotional_state: EmotionalState;\n intensity: number;\n stress_level: number;\n pressure_level: number;\n body_state: BodyState;\n cognitive_load: number;\n readiness_level: ReadinessLevel;\n}\n\n/**\n * A behavior event written to the cross-app ledger (LedgersMe).\n * The atlasent-api `/v1/behavior/events` endpoint accepts this shape.\n */\nexport interface BehaviorEvent {\n user_id: string;\n source: \"hicoach\" | \"echobloom\" | \"ledgers-me\" | string;\n category: SensitiveCategory;\n entry_state_summary: StateEventSummary;\n exit_state_summary: StateEventSummary | null;\n relief_delta: number | null;\n /** 0..1 */\n confidence_score: number;\n /** ISO 8601 */\n timestamp: string;\n /** Optional list of safety signals that fired during the event. Never raw text. */\n safety_signals?: string[];\n}\n\n// ---------------------------------------------------------------------------\n// Consent\n// ---------------------------------------------------------------------------\n\n/**\n * Per-user consent settings. Privacy-first defaults: nothing leaves\n * the device unless the user explicitly opts in.\n */\nexport interface ConsentSettings {\n /** Default false. Opt-in to emit summaries to the ledger. */\n share_state_summaries: boolean;\n /**\n * Default false. When true, suppresses ALL outbound emissions\n * regardless of any other setting. Acts as a global circuit\n * breaker.\n */\n private_only_mode: boolean;\n /**\n * Optional per-receiver allowlist. When non-empty, an event is\n * only emitted to a receiver whose name appears here AND for a\n * category whose slug appears in the receiver's allowed set.\n *\n * Example:\n * ```ts\n * { \"ledgers-me\": [\"behavior.health.mental\"] }\n * ```\n */\n receivers?: Record<string, SensitiveCategory[]>;\n}\n\nexport const DEFAULT_CONSENT: ConsentSettings = Object.freeze({\n share_state_summaries: false,\n private_only_mode: false,\n});\n\n/**\n * Storage abstraction so the helper works in browser\n * (`window.localStorage`), Node, and tests.\n */\nexport interface ConsentStorage {\n get(key: string): string | null;\n set(key: string, value: string): void;\n}\n\n/**\n * Default in-memory storage (for Node + tests). In a browser, pass\n * `window.localStorage`.\n */\nexport class MemoryStorage implements ConsentStorage {\n private store = new Map<string, string>();\n get(key: string): string | null {\n return this.store.get(key) ?? null;\n }\n set(key: string, value: string): void {\n this.store.set(key, value);\n }\n}\n\nexport interface ConsentManagerOpts {\n userId: string;\n /** Defaults to {@link MemoryStorage}. Pass `localStorage` in browsers. */\n storage?: ConsentStorage;\n /** Defaults to {@link DEFAULT_CONSENT}. */\n defaults?: ConsentSettings;\n}\n\n/**\n * Read/write consent settings; gate emissions through `canEmit`.\n *\n * Apps NEVER hand-roll consent checks. This is the only correct way\n * to decide whether a `BehaviorEvent` may leave the device.\n */\nexport class ConsentManager {\n private readonly key: string;\n private readonly storage: ConsentStorage;\n private readonly defaults: ConsentSettings;\n\n constructor(opts: ConsentManagerOpts) {\n this.key = `atlasent.behavior.consent.${opts.userId}`;\n this.storage = opts.storage ?? new MemoryStorage();\n this.defaults = opts.defaults ?? DEFAULT_CONSENT;\n }\n\n get(): ConsentSettings {\n const raw = this.storage.get(this.key);\n if (!raw) return { ...this.defaults };\n try {\n const parsed = JSON.parse(raw) as Partial<ConsentSettings>;\n return { ...this.defaults, ...parsed };\n } catch {\n return { ...this.defaults };\n }\n }\n\n set(patch: Partial<ConsentSettings>): ConsentSettings {\n const next = { ...this.get(), ...patch };\n this.storage.set(this.key, JSON.stringify(next));\n return next;\n }\n\n /**\n * The single decision point: may we emit a `BehaviorEvent` for\n * this `category` to this `receiver`? Returns `false` whenever\n * any of the following is true:\n *\n * - `private_only_mode` is on.\n * - `share_state_summaries` is off.\n * - A `receivers` allowlist exists and the `(receiver, category)`\n * pair is not in it.\n */\n canEmit(receiver: string, category: SensitiveCategory): boolean {\n const c = this.get();\n if (c.private_only_mode) return false;\n if (!c.share_state_summaries) return false;\n if (c.receivers) {\n const allowed = c.receivers[receiver] ?? [];\n if (!allowed.includes(category)) return false;\n }\n return true;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Redaction\n// ---------------------------------------------------------------------------\n\n/**\n * Project a {@link StateSnapshot} down to the redacted\n * {@link StateEventSummary} shape. Drops `id`, `user_id`,\n * `created_at`, `confidence_score`, and any `note` field. The\n * remaining fields are bounded numeric ranges or closed enums and\n * carry no free-form text.\n */\nexport function redactStateSnapshot(s: StateSnapshot): StateEventSummary {\n return {\n emotional_state: s.emotional_state,\n intensity: s.intensity,\n stress_level: s.stress_level,\n pressure_level: s.pressure_level,\n body_state: s.body_state,\n cognitive_load: s.cognitive_load,\n readiness_level: s.readiness_level,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Ledger\n// ---------------------------------------------------------------------------\n\nexport interface BehaviorLedger {\n /**\n * Emit a behavior event. Implementations MUST validate `consent`\n * before persisting and throw `ConsentDeniedError` when an event\n * would be persisted in violation of the user's settings.\n */\n emit(event: BehaviorEvent): Promise<void>;\n}\n\nexport class ConsentDeniedError extends Error {\n readonly code = \"consent_denied\" as const;\n constructor(\n public readonly receiver: string,\n public readonly category: SensitiveCategory,\n ) {\n super(\n `Consent denies emit to receiver=${receiver} category=${category}`,\n );\n this.name = \"ConsentDeniedError\";\n }\n}\n\n/**\n * On-device ledger for development and demos. A future\n * `RemoteBehaviorLedger` will POST to atlasent-api's\n * `/v1/behavior/events` once that endpoint ships.\n */\nexport class InMemoryBehaviorLedger implements BehaviorLedger {\n private readonly events: BehaviorEvent[] = [];\n constructor(\n private readonly opts: {\n consent: ConsentManager;\n receiver?: string;\n },\n ) {}\n\n async emit(event: BehaviorEvent): Promise<void> {\n const receiver = this.opts.receiver ?? \"in-memory\";\n if (!this.opts.consent.canEmit(receiver, event.category)) {\n throw new ConsentDeniedError(receiver, event.category);\n }\n this.events.push(event);\n }\n\n /** Read all events accepted so far. Test/demo helper. */\n list(): readonly BehaviorEvent[] {\n return [...this.events];\n }\n\n /** Clear the in-memory store. Test helper. */\n clear(): void {\n this.events.length = 0;\n }\n}\n\n// ---------------------------------------------------------------------------\n// State-event cache (for biasing AI suggestions with recent context)\n// ---------------------------------------------------------------------------\n\n/**\n * Bounded in-memory ring buffer of recent {@link StateEventSummary}\n * values. The LangChain/LlamaIndex middleware (and similar wrappers)\n * read this to attach `context.session_history` to evaluate calls\n * without ever touching raw snapshots.\n */\nexport class StateEventCache {\n private readonly buf: StateEventSummary[] = [];\n constructor(private readonly capacity: number = 10) {\n if (capacity <= 0) {\n throw new RangeError(\"capacity must be > 0\");\n }\n }\n\n add(summary: StateEventSummary): void {\n this.buf.push(summary);\n if (this.buf.length > this.capacity) this.buf.shift();\n }\n\n recent(n?: number): readonly StateEventSummary[] {\n const k = n ?? this.buf.length;\n return this.buf.slice(-k);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