@tenuo/core 0.3.1-beta.0 → 0.3.3-beta.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 CHANGED
@@ -1,3 +1,4 @@
1
+
1
2
  Apache License
2
3
  Version 2.0, January 2004
3
4
  http://www.apache.org/licenses/
@@ -32,9 +33,10 @@
32
33
  not limited to compiled object code, generated documentation,
33
34
  and conversions to other media types.
34
35
 
35
- "Work" shall mean the work of authorship made available under
36
- the License, as indicated by a copyright notice that is included in
37
- or attached to the work (an example is provided in the Appendix below).
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
38
40
 
39
41
  "Derivative Works" shall mean any work, whether in Source or Object
40
42
  form, that is based on (or derived from) the Work and for which the
@@ -44,24 +46,23 @@
44
46
  separable from, or merely link (or bind by name) to the interfaces of,
45
47
  the Work and Derivative Works thereof.
46
48
 
47
- "Contribution" shall mean, as defined by the copyright owner, any
48
- work of authorship, including the original version of the Work and
49
- any modifications or additions to that Work or Derivative Works of
50
- the Work, submitted to the Licensor for inclusion in the Work by the
51
- copyright owner or by an individual or Legal Entity authorized to
52
- submit on behalf of the copyright owner. For the purposes of this
53
- definition, "submitted" means any form of electronic, verbal, or
54
- written communication sent to the Licensor or its representatives,
55
- including but not limited to communication on electronic mailing lists,
56
- source code control systems, and issue tracking systems that are managed
57
- by, or on behalf of, the Licensor for the purpose of discussing and
58
- improving the Work, but excluding communication that is conspicuously
59
- marked or designated in writing by the copyright owner as "Not a
60
- Contribution."
61
-
62
- "Contributor" shall mean Licensor and any Legal Entity on behalf of
63
- whom a Contribution has been received by the Licensor and included
64
- within the Work.
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
65
66
 
66
67
  2. Grant of Copyright License. Subject to the terms and conditions of
67
68
  this License, each Contributor hereby grants to You a perpetual,
@@ -77,22 +78,22 @@
77
78
  use, offer to sell, sell, import, and otherwise transfer the Work,
78
79
  where such license applies only to those patent claims licensable
79
80
  by such Contributor that are necessarily infringed by their
80
- Contribution(s) alone or by the combined work of their Contribution(s)
81
+ Contribution(s) alone or by combination of their Contribution(s)
81
82
  with the Work to which such Contribution(s) was submitted. If You
82
- institute patent litigation against any entity (including a cross-claim
83
- or counterclaim in a lawsuit) alleging that the Work or any
84
- Contribution embodied within the Work constitutes direct or contributory
85
- patent infringement, then any patent licenses granted to You under
86
- this License for that Work shall terminate as of the date such
87
- litigation is filed.
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
88
89
 
89
90
  4. Redistribution. You may reproduce and distribute copies of the
90
91
  Work or Derivative Works thereof in any medium, with or without
91
92
  modifications, and in Source or Object form, provided that You
92
93
  meet the following conditions:
93
94
 
94
- (a) You must give any other recipients of the Work or Derivative
95
- Works a copy of this License; and
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
96
97
 
97
98
  (b) You must cause any modified files to carry prominent notices
98
99
  stating that You changed the files; and
@@ -104,25 +105,28 @@
104
105
  the Derivative Works; and
105
106
 
106
107
  (d) If the Work includes a "NOTICE" text file as part of its
107
- distribution, You must include a readable copy of the
108
- attribution notices contained within such NOTICE file, in
109
- at least one of the following places: within a NOTICE text
110
- file distributed as part of the Derivative Works; within
111
- the Source form or documentation, if provided along with the
112
- Derivative Works; or, within a display generated by the
113
- Derivative Works, if and wherever such third-party notices
114
- normally appear. The contents of the NOTICE file are for
115
- informational purposes only and do not modify the License.
116
- You may add Your own attribution notices within Derivative
117
- Works that You distribute, alongside or as an addendum to
118
- the NOTICE text from the Work, provided that such additional
119
- attribution notices cannot be construed as modifying the License.
120
-
121
- You may add Your own license statement for Your modifications and
122
- may provide additional grant of rights to use, copy, modify, merge,
123
- publish, distribute, sublicense, and/or sell copies of the
124
- Derivative Works, and to permit persons to whom the Derivative Works
125
- are furnished to do so, subject to Your terms.
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
126
130
 
127
131
  5. Submission of Contributions. Unless You explicitly state otherwise,
128
132
  any Contribution intentionally submitted for inclusion in the Work
@@ -144,7 +148,7 @@
144
148
  implied, including, without limitation, any warranties or conditions
145
149
  of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
146
150
  PARTICULAR PURPOSE. You are solely responsible for determining the
147
- appropriateness of using or reproducing the Work and assume any
151
+ appropriateness of using or redistributing the Work and assume any
148
152
  risks associated with Your exercise of permissions under this License.
149
153
 
150
154
  8. Limitation of Liability. In no event and under no legal theory,
@@ -152,27 +156,38 @@
152
156
  unless required by applicable law (such as deliberate and grossly
153
157
  negligent acts) or agreed to in writing, shall any Contributor be
154
158
  liable to You for damages, including any direct, indirect, special,
155
- incidental, or exemplary damages of any character arising as a
159
+ incidental, or consequential damages of any character arising as a
156
160
  result of this License or out of the use or inability to use the
157
161
  Work (including but not limited to damages for loss of goodwill,
158
- work stoppage, computer failure or malfunction, or all other
159
- commercial damages or losses), even if such Contributor has been
160
- advised of the possibility of such damages.
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
161
165
 
162
166
  9. Accepting Warranty or Additional Liability. While redistributing
163
- the Work or Derivative Works thereof, You may offer, and charge a
164
- fee for, acceptance of support, warranty, indemnity, or other
165
- liability obligations and/or rights consistent with this License.
166
- However, in accepting such obligations, You may offer such obligations
167
- only on Your own behalf and on Your sole responsibility, not on
168
- behalf of any other Contributor, and only if You agree to indemnify,
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
169
173
  defend, and hold each Contributor harmless for any liability
170
174
  incurred by, or claims asserted against, such Contributor by reason
171
175
  of your accepting any such warranty or additional liability.
172
176
 
173
177
  END OF TERMS AND CONDITIONS
174
178
 
175
- Copyright 2025-2026 Tenuo Contributors
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
176
191
 
177
192
  Licensed under the Apache License, Version 2.0 (the "License");
178
193
  you may not use this file except in compliance with the License.
package/README.md CHANGED
@@ -16,7 +16,7 @@ npm i @tenuo/core@beta
16
16
  ```
17
17
 
18
18
  ```ts
19
- import { createTenuo, under } from "@tenuo/core";
19
+ import { AuthorizationDeniedError, createTenuo, under } from "@tenuo/core";
20
20
 
21
21
  const tenuo = createTenuo({ root: createTenuo.devRoot() });
22
22
  const readFile = tenuo.tool(
@@ -26,15 +26,22 @@ const readFile = tenuo.tool(
26
26
  const session = tenuo.session({ tools: [readFile] });
27
27
 
28
28
  await tenuo.withSession(session, async () => {
29
- await readFile.execute({ path: "/data/q3.pdf" }); // allowed
30
- await readFile.execute({ path: "/etc/passwd" }); // denied — execute does not run
29
+ console.log(await readFile.execute({ path: "/data/q3.pdf" })); // allowed
30
+ try {
31
+ await readFile.execute({ path: "/etc/passwd" }); // denied — execute does not run
32
+ } catch (error) {
33
+ if (!(error instanceof AuthorizationDeniedError)) throw error;
34
+ console.log("denied:", error.code);
35
+ }
31
36
  });
32
37
  ```
33
38
 
34
39
  Host schemas (Zod or otherwise) answer **valid**. Tool `allow` is the host ceiling.
35
40
  The session is what this agent may do. Rust AND's both. `allow` is zero-trust:
36
41
  every call argument must be named in the policy. `allow: {}` adds no extra
37
- ceiling. `devRoot()` requires `NODE_ENV=development` or `test`,
42
+ ceiling, and `session({ tools })` refuses such a tool unless the session's own
43
+ `allow` names it (`allow: { read_file: {} }`), because an empty capability in
44
+ a warrant accepts any arguments. Unknown policy and option keys throw. `devRoot()` requires `NODE_ENV=development` or `test`,
38
45
  `devRoot({ allowInProduction: true })`, or `TENUO_ALLOW_DEV=1`. Unset
39
46
  `NODE_ENV` is not treated as development.
40
47
 
@@ -49,6 +56,8 @@ const runtime = createTenuo.runtime({
49
56
  trustedRoots: [createTenuo.publicKeyFromEnv("TENUO_ROOT_PUBLIC_KEY")],
50
57
  receipts: "collect",
51
58
  });
59
+ // TENUO_WARRANT holds session.toWireString() from the issuer: the whole chain
60
+ // as one string. sessionFromWire() also accepts the toWire() array.
52
61
  const session = runtime.sessionFromWire(process.env.TENUO_WARRANT!);
53
62
  await readFile.execute({ path: "/data/q3.pdf" }, { session });
54
63
  const receipts = session.drainReceipts(); // persist, then upload
@@ -59,7 +68,7 @@ read environment variables or invent an origin. Relative `/v1` endpoints need
59
68
  `token.resolveEndpoint({ localBase })`. Callers append `/v1/…` to the bare
60
69
  origin.
61
70
 
62
- See [Receipt delivery](../../README.md#receipt-delivery) for peek / drain / ack
71
+ See [Receipt delivery](https://github.com/tenuo-ai/tenuo/tree/main/tenuo-ts#receipt-delivery) for peek / drain / ack
63
72
  guarantees. This package does not perform HTTP, discovery, or upload.
64
73
 
65
74
  Delegation to another agent rebinds a narrower child to that agent's key. The
@@ -96,11 +105,13 @@ MCP wire helpers live on `tenuo.mcp` (`attach` / `verify` / `handler`). They do
96
105
  not depend on an MCP framework. For the official v2 server, use `@tenuo/mcp`.
97
106
  For `@modelcontextprotocol/sdk` v1, copy the recipe in `examples/mcp/host.ts`.
98
107
  `verify` / `handler` can take an optional `nonceStore` (`memoryNonceStore()`,
99
- or an async Redis `checkAndRecord`) to reject an exact replayed PoP; that is
100
- opt-in. PoP v1 is otherwise replayable in-window, including approval-gated
101
- calls. Pass `nonceStore` on those tools if an approval must be one-use.
108
+ or an async Redis `checkAndRecord`) to reject an exact replayed PoP and to
109
+ consume the approvals an allowed call carried; that is opt-in. PoP v1 is
110
+ otherwise replayable in-window, including approval-gated calls. For
111
+ in-process tools, pass the same `nonceStore` to `tenuo.tool()` to make
112
+ approvals one-use there.
102
113
  `memoryNonceStore({ ttlSeconds })` defaults to 180 seconds; an explicit TTL must
103
114
  be positive, finite, and small enough to represent in milliseconds.
104
115
 
105
- See the [workspace README](../../README.md) for the full API, refuse list, and
116
+ See the [workspace README](https://github.com/tenuo-ai/tenuo/tree/main/tenuo-ts) for the full API, refuse list, and
106
117
  how to rebuild WASM from this monorepo.
package/dist/api.d.ts CHANGED
@@ -121,15 +121,38 @@ export type ToolPolicy<TArgs = undefined> = {
121
121
  /**
122
122
  * Host ceiling. AND'd with the session in Rust.
123
123
  * Non-empty maps are zero-trust: every call argument must be named here.
124
- * `{}` means no extra ceiling (session/warrant only).
124
+ * `{}` means no extra ceiling (session/warrant only). Required: a missing
125
+ * `allow` or an unknown policy key throws. `session({ tools })` refuses a
126
+ * tool whose `allow` is `{}` unless the session's own `allow` names that
127
+ * capability explicitly, because an empty capability in a warrant accepts
128
+ * any arguments.
125
129
  */
126
130
  readonly allow: [NonNullable<TArgs>] extends [object] ? [KeysOfUnion<NonNullable<TArgs>>] extends [never] ? AllowPolicy : string extends KeysOfUnion<NonNullable<TArgs>> ? AllowPolicy : number extends KeysOfUnion<NonNullable<TArgs>> ? AllowPolicy : symbol extends KeysOfUnion<NonNullable<TArgs>> ? AllowPolicy : {
127
131
  readonly [Field in KeysOfUnion<NonNullable<TArgs>>]?: ConstraintExpr;
128
132
  } : AllowPolicy;
129
133
  readonly capability?: string;
134
+ /**
135
+ * Makes approvals one-use for this tool. When a call that carried
136
+ * `approvals` is allowed, each approval envelope that matches the call is
137
+ * recorded here before the tool body runs; an envelope the store has
138
+ * already seen denies with `TENUO_INSUFFICIENT_APPROVALS`. Same
139
+ * `NonceStore` shape as the MCP verify path; `memoryNonceStore()` works
140
+ * for one process. The store must remember a key for as long as an
141
+ * approval can live (one hour by default), so give `memoryNonceStore()` a
142
+ * matching `ttlSeconds`. A store that throws, rejects, or returns a
143
+ * non-boolean fails closed with "Replay store unavailable".
144
+ */
145
+ readonly nonceStore?: NonceStore;
146
+ /** Isolated. Called when `nonceStore.checkAndRecord` throws or rejects. */
147
+ readonly onNonceStoreError?: (error: unknown) => void | Promise<void>;
130
148
  };
131
149
  /** Compile-time brand only — never assigned at runtime. Do not `in`/`has` this key. */
132
150
  declare const protectedBrand: unique symbol;
151
+ /**
152
+ * Tenuo's per-call options. Other keys pass through to the wrapped tool's own
153
+ * `execute`, except keys that look like a misspelled Tenuo option
154
+ * (`sesion`, `approval`, `onReciept`), which throw instead of being ignored.
155
+ */
133
156
  export type ExecuteOptions = {
134
157
  readonly session?: Session;
135
158
  /** Already-signed approval envelopes (hex, standard base64, or CBOR bytes). */
@@ -308,7 +331,10 @@ export type NarrowOptions = {
308
331
  * cannot authorize here. Hand `toWire()` to that agent.
309
332
  */
310
333
  readonly holder?: PublicKeyHandle;
311
- /** Child lifetime. Clamped to what the parent has left. */
334
+ /**
335
+ * Child lifetime. A value longer than the parent has left is clamped to the
336
+ * parent's expiry, not rejected: the child never outlives the parent.
337
+ */
312
338
  readonly ttlSeconds?: number;
313
339
  /** The child's holder cannot delegate further. */
314
340
  readonly terminal?: boolean;
@@ -319,7 +345,7 @@ export type NarrowOptions = {
319
345
  readonly agentId?: string;
320
346
  /** Approvers can only be added. */
321
347
  readonly addApprovers?: readonly PublicKeyHandle[];
322
- /** The threshold can only go up. */
348
+ /** The threshold can only go up. A value below the parent's throws. */
323
349
  readonly minApprovals?: number;
324
350
  };
325
351
  /** Options for `tenuo.issue()`: an execution session minted from an issuer session. */
@@ -508,6 +534,13 @@ export interface Session {
508
534
  readonly [Symbol.toStringTag]: "TenuoSession";
509
535
  /** Warrant tokens, root first. Does not include the holder secret. */
510
536
  toWire(): readonly string[];
537
+ /**
538
+ * The whole chain as one string: a CBOR warrant stack in URL-safe base64,
539
+ * the same encoding as `PresentedCall.warrant`. Use it where only a single
540
+ * string fits (an environment variable, a header). `sessionFromWire()`
541
+ * imports it. Does not include the holder secret.
542
+ */
543
+ toWireString(): string;
511
544
  /** SHA-256 of `(warrant_id, tool, canonical args)`. App-level idempotency, not PoP. */
512
545
  dedupKey(tool: string, args: Readonly<Record<string, unknown>>): string;
513
546
  /** Holder public key, depth, ceiling, lifetime, tools. Never the secret. */
@@ -567,7 +600,12 @@ export interface Tenuo {
567
600
  attestApprovalRequest(session: Session, tool: string, args: Readonly<Record<string, unknown>>): ApprovalContextAttestation;
568
601
  /** Authorize locally, then produce warrant + proof-of-possession for another boundary to verify. */
569
602
  present(session: Session, tool: string, args: Readonly<Record<string, unknown>>, options?: McpAttachOptions): PresentedCall;
570
- /** Verify a presented call at any boundary. Resolves with the authorized arguments; the tool must not run otherwise. */
603
+ /**
604
+ * Verify a presented call at any boundary. Resolves with the authorized
605
+ * arguments; the tool must not run otherwise. `args` is the object already
606
+ * given to this function. A repeated key in the original JSON is not
607
+ * visible. Parse that text with `parseStrictJson` while it is still available.
608
+ */
571
609
  verify(presented: PresentedCall, tool: string, args: Readonly<Record<string, unknown>>, options?: McpVerifyOptions): Promise<Readonly<Record<string, unknown>>>;
572
610
  /** Sign a revocation list with this context's issuer key. Load it with `revoke()` where this issuer is trusted. */
573
611
  revocationList(input: RevocationListInput): string;
@@ -653,8 +691,10 @@ export interface TenuoMcp {
653
691
  /** Local authorize, then put warrant + PoP on `_meta.tenuo`. */
654
692
  attach(session: Session, name: string, args: Readonly<Record<string, unknown>>, options?: McpAttachOptions): McpCallParams;
655
693
  /**
656
- * Server path. Verifies a presented warrant + PoP. Tool handler must not
657
- * run unless this returns.
694
+ * Server path. Verifies a presented warrant + PoP against the object it was
695
+ * given. A repeated key in the original JSON is not visible: the host has
696
+ * already parsed `args`. Parse that text with `parseStrictJson` while it is
697
+ * still available. The tool handler must not run unless this returns.
658
698
  */
659
699
  verify(name: string, args: Readonly<Record<string, unknown>>, meta: unknown, options?: McpVerifyOptions): Promise<Readonly<Record<string, unknown>>>;
660
700
  /** Wrap a handler: verify from `extra._meta` / `extra.meta`, then execute. */
package/dist/api.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"api.js","sourceRoot":"","sources":["../src/api.ts"],"names":[],"mappings":"AAAA;;;;;GAKG","sourcesContent":["/**\n * Frozen public contract for `@tenuo/core`.\n *\n * Names and shapes here are the review surface — do not grow this file with\n * protocol vocabulary (`Warrant`, `mint`, `guard`) as the lead API.\n */\n\n/** Canonical kebab-case codes from Rust `ErrorCode::name()` / `Denial::code()`. */\nexport type ProtocolDenialCode =\n | \"signature-invalid\"\n | \"untrusted-root\"\n | \"chain-broken\"\n | \"depth-exceeded\"\n | \"warrant-expired\"\n | \"tool-not-authorized\"\n | \"constraint-violation\"\n | \"pop-signature-invalid\"\n | \"approval-required\"\n | \"insufficient-approvals\"\n | \"warrant-revoked\";\n\n/** Legacy SCREAMING_SNAKE aliases accepted by existing TypeScript callers. */\nexport type LegacyTenuoErrorCode =\n | \"TENUO_NOT_READY\"\n | \"TENUO_CONFIGURATION\"\n | \"TENUO_CONSTRAINT_VIOLATION\"\n | \"TENUO_TOOL_NOT_AUTHORIZED\"\n | \"TENUO_WARRANT_EXPIRED\"\n | \"TENUO_UNTRUSTED_ROOT\"\n | \"TENUO_INVALID_POP\"\n | \"TENUO_SIGNATURE_INVALID\"\n | \"TENUO_CHAIN_INVALID\"\n | \"TENUO_DEPTH_EXCEEDED\"\n | \"TENUO_REVOKED\"\n | \"TENUO_APPROVAL_REQUIRED\"\n | \"TENUO_INSUFFICIENT_APPROVALS\"\n | \"TENUO_CANONICALIZATION\"\n | \"TENUO_NOT_IMPLEMENTED\";\n\nexport type TenuoErrorCode = ProtocolDenialCode | LegacyTenuoErrorCode;\n\n// ---------------------------------------------------------------------------\n// Constraints. Every kind is evaluated in the Rust core; TypeScript only\n// builds the marker object. The set matches the core `Constraint` enum.\n// ---------------------------------------------------------------------------\n\n/** Path-traversal-safe prefix. Core evaluates this; TypeScript does not. */\nexport type UnderConstraint = {\n readonly kind: \"under\";\n readonly root: string;\n /** Default true. */\n readonly caseSensitive?: boolean;\n /** Whether the root itself is allowed. Default true. */\n readonly allowEqual?: boolean;\n};\n\nexport type EmailConstraint = {\n readonly kind: \"email\";\n readonly domain: string;\n};\n\nexport type MaxConstraint = {\n readonly kind: \"max\";\n readonly value: number;\n};\n\nexport type MinConstraint = {\n readonly kind: \"min\";\n readonly value: number;\n};\n\nexport type RangeConstraint = {\n readonly kind: \"range\";\n readonly min?: number;\n readonly max?: number;\n readonly minExclusive?: boolean;\n readonly maxExclusive?: boolean;\n};\n\nexport type OneOfConstraint = {\n readonly kind: \"oneOf\";\n readonly values: readonly string[];\n};\n\nexport type NotOneOfConstraint = {\n readonly kind: \"notOneOf\";\n readonly values: readonly string[];\n};\n\nexport type PatternConstraint = {\n readonly kind: \"pattern\";\n readonly pattern: string;\n};\n\nexport type RegexConstraint = {\n readonly kind: \"regex\";\n readonly source: string;\n};\n\nexport type ExactConstraint = {\n readonly kind: \"exact\";\n readonly value: string | number | boolean;\n};\n\nexport type WildcardConstraint = {\n readonly kind: \"wildcard\";\n};\n\nexport type CidrConstraint = {\n readonly kind: \"cidr\";\n readonly network: string;\n};\n\nexport type UrlPatternConstraint = {\n readonly kind: \"urlPattern\";\n readonly pattern: string;\n};\n\nexport type UrlSafeConstraint = {\n readonly kind: \"urlSafe\";\n readonly schemes?: readonly string[];\n readonly allowDomains?: readonly string[];\n readonly denyDomains?: readonly string[];\n};\n\nexport type ShlexConstraint = {\n readonly kind: \"shlex\";\n readonly allow: readonly string[];\n};\n\nexport type ContainsConstraint = {\n readonly kind: \"contains\";\n readonly values: readonly (string | number | boolean)[];\n};\n\nexport type SubsetConstraint = {\n readonly kind: \"subset\";\n readonly values: readonly (string | number | boolean)[];\n};\n\nexport type AnyOfConstraint = {\n readonly kind: \"anyOf\";\n readonly constraints: readonly ConstraintExpr[];\n};\n\nexport type AllConstraint = {\n readonly kind: \"all\";\n readonly constraints: readonly ConstraintExpr[];\n};\n\nexport type NotConstraint = {\n readonly kind: \"not\";\n readonly constraint: ConstraintExpr;\n};\n\nexport type CelConstraint = {\n readonly kind: \"cel\";\n readonly expression: string;\n};\n\nexport type ConstraintExpr =\n | UnderConstraint\n | EmailConstraint\n | MaxConstraint\n | MinConstraint\n | RangeConstraint\n | OneOfConstraint\n | NotOneOfConstraint\n | PatternConstraint\n | RegexConstraint\n | ExactConstraint\n | WildcardConstraint\n | CidrConstraint\n | UrlPatternConstraint\n | UrlSafeConstraint\n | ShlexConstraint\n | ContainsConstraint\n | SubsetConstraint\n | AnyOfConstraint\n | AllConstraint\n | NotConstraint\n | CelConstraint;\n\n/** Per-argument allow policy. Not a Zod schema. */\nexport type AllowPolicy = {\n readonly [field: string]: ConstraintExpr;\n};\n\n/**\n * Framework tool shape we wrap. No dependency on `ai` / Mastra.\n * `parameters` is host-schema (usually Zod) and is never treated as authority.\n */\nexport type ToolLike<\n TArgs extends Record<string, unknown> = Record<string, unknown>,\n TResult = unknown,\n> = {\n readonly description?: string;\n readonly parameters?: unknown;\n execute: (args: TArgs, options?: unknown) => TResult | Promise<TResult>;\n};\n\ntype KeysOfUnion<T> = T extends unknown ? keyof T : never;\n\nexport type ToolPolicy<TArgs = undefined> = {\n /**\n * Host ceiling. AND'd with the session in Rust.\n * Non-empty maps are zero-trust: every call argument must be named here.\n * `{}` means no extra ceiling (session/warrant only).\n */\n readonly allow: [NonNullable<TArgs>] extends [object]\n ? [KeysOfUnion<NonNullable<TArgs>>] extends [never]\n ? AllowPolicy\n : string extends KeysOfUnion<NonNullable<TArgs>>\n ? AllowPolicy\n : number extends KeysOfUnion<NonNullable<TArgs>>\n ? AllowPolicy\n : symbol extends KeysOfUnion<NonNullable<TArgs>>\n ? AllowPolicy\n : { readonly [Field in KeysOfUnion<NonNullable<TArgs>>]?: ConstraintExpr }\n : AllowPolicy;\n readonly capability?: string;\n};\n\n/** Compile-time brand only — never assigned at runtime. Do not `in`/`has` this key. */\ndeclare const protectedBrand: unique symbol;\n\nexport type ExecuteOptions = {\n readonly session?: Session;\n /** Already-signed approval envelopes (hex, standard base64, or CBOR bytes). */\n readonly approvals?: readonly (string | Uint8Array)[];\n /**\n * Signed evidence of the decision. Not a security hook.\n * Exceptions (sync or rejected Promise) are isolated and never deny or\n * fail the tool.\n */\n readonly onReceipt?: (receipt: string) => void | Promise<void>;\n /**\n * Correlation handle written to the receipt. Use whatever id the host\n * already has — a JSON-RPC id, a trace or span id — so a receipt can be\n * matched against your own logs. Not an identity: nothing enforces\n * uniqueness, and distinguishing repeated calls is the receipt chain's job.\n */\n readonly requestId?: string;\n};\n\ntype ExtraExecuteOptions<T extends { execute: (args: never) => unknown }> =\n T[\"execute\"] extends (args: never, options?: infer O) => unknown\n ? unknown extends O\n ? object\n : Omit<NonNullable<O>, keyof ExecuteOptions>\n : object;\n\n/** Wrapped tool. `execute` still authorizes; optional `{ session }` overrides ALS. */\nexport type ProtectedTool<T extends { execute: (args: never) => unknown }> = Omit<T, \"execute\"> & {\n execute: (\n args: Parameters<T[\"execute\"]>[0],\n options?: ExecuteOptions & ExtraExecuteOptions<T>,\n ) => Promise<Awaited<ReturnType<T[\"execute\"]>>>;\n readonly [protectedBrand]: true;\n};\n\n// ---------------------------------------------------------------------------\n// Approvals\n// ---------------------------------------------------------------------------\n\n/** Per-argument trigger for an approval gate. */\nexport type ArgApprovalGate =\n /** Every value of this argument fires the gate. */\n | \"all\"\n /** Only values satisfying the constraint fire the gate. */\n | { readonly when: ConstraintExpr }\n /** Every value except those satisfying the constraint fires the gate. Narrowable across delegation. */\n | { readonly exempt: ConstraintExpr };\n\n/** Gate on one tool: a message for the approver and optional per-argument triggers. */\nexport type ToolApprovalGate = {\n readonly message?: string;\n /** Absent: the whole tool is gated. */\n readonly args?: { readonly [field: string]: ArgApprovalGate };\n};\n\n/** Approval requirement. Host collects SignedApproval envelopes; Rust decides. */\nexport type RequireApproval = {\n readonly approvers: readonly PublicKeyHandle[];\n readonly min: number;\n /** Whole-tool gates. Defaults to every tool in the session when `gates` is absent too. */\n readonly tools?: readonly string[];\n /** Per-tool gates with messages and per-argument triggers. */\n readonly gates?: { readonly [tool: string]: ToolApprovalGate };\n};\n\n/** What an approval service needs to present a call to a human. Not a signed artifact. */\nexport type ApprovalRequest = {\n readonly requestId: string;\n readonly warrantId: string;\n readonly tool: string;\n readonly args: Readonly<Record<string, unknown>>;\n /** Hex SHA-256 committing to warrant id, tool, canonical args, and holder. */\n readonly requestHash: string;\n readonly holderPublicKey: string;\n readonly requiredApprovers: readonly string[];\n readonly minApprovals: number;\n /** Unix seconds. An approval cannot outlive the warrant. */\n readonly warrantExpiresAt: number;\n readonly createdAt: number;\n readonly message: string;\n};\n\n/** Holder-signed statement that it is the one asking. Carried in a control-plane request. */\nexport type ApprovalContextAttestation = {\n readonly version: number;\n readonly canonicalization: string;\n readonly warrantId: string;\n readonly tool: string;\n readonly requestHash: string;\n readonly holderKeyHex: string;\n readonly argsCanonicalCborB64: string;\n readonly signerKeyHex: string;\n readonly signatureB64: string;\n};\n\n/** Wire body for a control-plane approval API. Field names are the wire names. */\nexport type ControlPlaneApprovalRequestV1 = {\n readonly schema_version: 1;\n readonly request_id_hex: string;\n readonly warrant_id: string;\n readonly tool: string;\n readonly arguments: Readonly<Record<string, unknown>>;\n readonly request_hash_hex: string;\n readonly holder_public_key_hex: string;\n readonly required_approver_keys_hex: readonly string[];\n readonly min_approvals: number;\n readonly warrant_expires_at_unix: number;\n readonly created_at_unix: number;\n readonly attestation?: Readonly<Record<string, unknown>>;\n readonly temporal?: Readonly<Record<string, string>>;\n readonly message?: string;\n};\n\nexport type ControlPlaneApprovalResponseV1 = {\n readonly status: string;\n readonly signed_approvals_b64?: readonly string[];\n readonly error?: string;\n readonly server_request_id?: string;\n};\n\nexport type SignApprovalOptions = {\n /** Who approved, in the approver system's own terms. Required. */\n readonly externalId: string;\n /** Approval lifetime. Default one hour, always clamped to the warrant's expiry when given. */\n readonly ttlSeconds?: number;\n readonly warrantExpiresAt?: number;\n};\n\n/** Decoded approval envelope. Not authorization. */\nexport type ApprovalInfo = {\n readonly approverPublicKey: string;\n readonly requestHash: string;\n readonly externalId: string;\n readonly approvedAt: number;\n readonly expiresAt: number;\n readonly expired: boolean;\n readonly signatureValid: boolean;\n readonly error?: string;\n};\n\n// ---------------------------------------------------------------------------\n// Sessions\n// ---------------------------------------------------------------------------\n\nexport type SessionAllow = {\n readonly [capability: string]: AllowPolicy;\n};\n\n/** Named level or a number 0-255. Delegation can only lower it. */\nexport type Clearance =\n | number\n | \"untrusted\"\n | \"external\"\n | \"partner\"\n | \"internal\"\n | \"privileged\"\n | \"system\";\n\nexport type SessionInput = {\n /** Capability map. Optional when `tools` is set. Issuer sessions may omit it. */\n readonly allow?: SessionAllow;\n /** Wrapped tools from `tenuo.tool()`. Their `allow` is minted into the session. */\n readonly tools?: readonly object[];\n readonly ttlSeconds?: number;\n readonly requireApproval?: RequireApproval;\n /**\n * Issue to another agent's key instead of a fresh local holder. The\n * returned session cannot authorize here (it has no holder secret); send\n * `toWire()` to that agent, which imports it with `sessionFromWire()`.\n */\n readonly holder?: PublicKeyHandle;\n /**\n * How many times this authority may be delegated below the root.\n * `0` makes the session terminal. Omit for the protocol maximum.\n * Delegation can lower this ceiling and never raise it.\n */\n readonly maxDepth?: number;\n /**\n * `\"execution\"` (default) can call tools. `\"issuer\"` cannot call tools; its\n * holder can mint execution sessions with `tenuo.issue()` for the tools in\n * `issuableTools`, within `constraintBounds`, without the root key.\n */\n readonly kind?: \"execution\" | \"issuer\";\n readonly clearance?: Clearance;\n /** Free-form task correlation id. Inherited unchanged through delegation. */\n readonly sessionId?: string;\n /** Free-form agent label. Delegation may change it. */\n readonly agentId?: string;\n /** Issuer sessions only. */\n readonly issuableTools?: readonly string[];\n /** Issuer sessions only: ceiling on the constraints of anything issued, by field. */\n readonly constraintBounds?: AllowPolicy;\n /** Issuer sessions only: how deep issued sessions may themselves delegate. */\n readonly maxIssueDepth?: number;\n};\n\n/** Options for `tenuo.narrow()`. All optional; the default keeps the holder. */\nexport type NarrowOptions = {\n /**\n * Bind the child to another agent's key. This is delegation: the current\n * holder signs, the child belongs to `holder`, and the returned session\n * cannot authorize here. Hand `toWire()` to that agent.\n */\n readonly holder?: PublicKeyHandle;\n /** Child lifetime. Clamped to what the parent has left. */\n readonly ttlSeconds?: number;\n /** The child's holder cannot delegate further. */\n readonly terminal?: boolean;\n /** Lower the delegation ceiling. Cannot exceed the parent's. */\n readonly maxDepth?: number;\n /** Lower the clearance. Cannot exceed the parent's. */\n readonly clearance?: Clearance;\n readonly agentId?: string;\n /** Approvers can only be added. */\n readonly addApprovers?: readonly PublicKeyHandle[];\n /** The threshold can only go up. */\n readonly minApprovals?: number;\n};\n\n/** Options for `tenuo.issue()`: an execution session minted from an issuer session. */\nexport type IssueInput = {\n readonly allow: SessionAllow;\n /** The distinct agent that will use it. Issuer/holder separation is enforced. */\n readonly holder: PublicKeyHandle;\n readonly ttlSeconds?: number;\n readonly maxDepth?: number;\n readonly clearance?: Clearance;\n readonly sessionId?: string;\n readonly agentId?: string;\n /** Approval policy for the issued execution session. Defaults to gating every issued tool. */\n readonly requireApproval?: RequireApproval;\n};\n\n/** Public view of a session's leaf. Never includes the holder secret. */\nexport type SessionInfo = {\n readonly kind: \"execution\" | \"issuer\";\n /** Hex public key the leaf is bound to. */\n readonly holderPublicKey: string;\n /** Hex public key that signed the root of the chain. */\n readonly rootPublicKey: string;\n /** 0 for a root session, +1 per delegation. */\n readonly depth: number;\n /** Delegation ceiling in force for this leaf. */\n readonly maxDepth: number;\n /** True when `depth >= maxDepth`: cannot be narrowed further. */\n readonly terminal: boolean;\n /** Unix seconds. */\n readonly expiresAt: number;\n readonly tools: readonly string[];\n /** Warrant ids, root first. */\n readonly warrantIds: readonly string[];\n /**\n * True when this process holds the leaf's holder secret. False for a\n * session issued or delegated to another agent: `toWire()` works,\n * `execute` and `narrow` do not.\n */\n readonly canAuthorize: boolean;\n readonly clearance?: number;\n readonly sessionId?: string;\n readonly agentId?: string;\n readonly issuableTools?: readonly string[];\n readonly maxIssueDepth?: number;\n readonly requiredApprovers?: readonly string[];\n readonly minApprovals?: number;\n readonly approvalGatedTools: readonly string[];\n};\n\n/** One constrained argument in an `explain()` result. */\nexport type ExplainedField = {\n readonly field: string;\n /** Core constraint type name, e.g. `\"Subpath\"`, `\"Range\"`. */\n readonly kind: string;\n /** The constraint as core serializes it. */\n readonly constraint: unknown;\n /** Absent when the argument was not supplied. */\n readonly value?: unknown;\n readonly satisfied: boolean;\n /** Stable machine-readable diagnostic, when the core can identify one. */\n readonly reasonCode?: string;\n readonly reason?: string;\n};\n\n/** What a session would decide for `tool(args)`, field by field. No proof-of-possession involved. */\nexport type Explanation = {\n readonly tool: string;\n readonly kind: \"execution\" | \"issuer\";\n readonly outcome: \"allow\" | \"deny\";\n readonly code?: TenuoErrorCode;\n readonly field?: string;\n readonly message?: string;\n readonly toolGranted: boolean;\n readonly fields: readonly ExplainedField[];\n /** Arguments the session does not name. Zero-trust policies reject these. */\n readonly unknownFields: readonly string[];\n /** Constrained arguments the call did not supply. */\n readonly missingFields: readonly string[];\n readonly expired: boolean;\n readonly expiresAt: number;\n readonly chainValid: boolean;\n readonly chainError?: TenuoErrorCode;\n};\n\nexport type DevRoot = {\n readonly kind: \"dev-root\";\n /**\n * Required when `NODE_ENV` is unset or is not `development` / `test`.\n * Unset `NODE_ENV` is not treated as development.\n */\n readonly allowInProduction?: boolean;\n};\n\n/** A stable issuer secret: this process is a control plane. */\nexport type IssuerKey = {\n readonly kind: \"issuer-key\";\n readonly secret: Uint8Array;\n};\n\nexport type PublicKeyHandle = {\n readonly kind: \"public-key\";\n readonly source: \"env\" | \"hex\" | \"bytes\";\n readonly hex: string;\n};\n\nexport type WarrantPart = {\n readonly payload_hex: string;\n readonly signature_hex: string;\n};\n\nexport type SessionFromWireInput = {\n readonly warrant: string | readonly string[] | readonly WarrantPart[];\n readonly holderKey: Uint8Array;\n};\n\n/** Field-level (`{ path: under(\"/data\") }`) or per-capability (`{ read_file: { path: ... } }`). */\nexport type NarrowInput = AllowPolicy | SessionAllow;\n\nexport type CreateTenuoOptions = {\n readonly trustedRoots?: readonly PublicKeyHandle[];\n /**\n * `devRoot()` for development; an `issuerKey*` for a control plane that\n * mints with a stable key; a public key for a verifier. An issuer key\n * trusts itself plus `trustedRoots`.\n */\n readonly root?: DevRoot | IssuerKey | PublicKeyHandle;\n /** Published SignedRevocationList (hex or standard base64). Verified against a trusted root. */\n readonly revocationList?: string | Uint8Array;\n /** 32-byte holder seed used to sign verifier receipts. Runtime supplies this. */\n readonly receiptSigner?: Uint8Array;\n};\n\nexport type ApprovalRequestSummary = {\n readonly tool: string;\n readonly required: number;\n readonly received: number;\n};\n\nexport type Decision =\n | { readonly outcome: \"allow\"; readonly args: Readonly<Record<string, unknown>> }\n | { readonly outcome: \"deny\"; readonly code: TenuoErrorCode; readonly field?: string }\n | { readonly outcome: \"approval_required\"; readonly request: ApprovalRequestSummary };\n\n// ---------------------------------------------------------------------------\n// Revocation and receipts\n// ---------------------------------------------------------------------------\n\nexport type RevocationListInput = {\n readonly revoke: readonly string[];\n /** Monotonic; verifiers refuse an older version. Default 1. */\n readonly version?: number;\n};\n\nexport type RevocationListInfo = {\n readonly version: number;\n readonly issuedAt: number;\n readonly issuerPublicKey: string;\n readonly revokedIds: readonly string[];\n readonly signatureValid: boolean;\n};\n\n/** Signature authenticity of a receipt. Not authorization. */\nexport type ReceiptInfo = {\n readonly authentic: true;\n /** Hex key the receipt is signed under — resolve against your own authorizer set. */\n readonly signerKey: string;\n readonly outcome: \"allow\" | \"deny\";\n readonly action: string;\n readonly decisionCode?: string;\n readonly requestId: string;\n readonly srlVersion?: number;\n readonly srlHash?: string;\n readonly requestHash?: string;\n readonly policyDefinitionHash?: string;\n readonly prevReceiptHash?: string;\n readonly trustedRootsHash?: string;\n};\n\n/** Root-anchored receipt check: the embedded chain against trusted roots at decision time. */\nexport type ReceiptChainInfo = {\n readonly signerKey: string;\n readonly outcome: \"allow\" | \"deny\";\n readonly decisionCode?: string;\n readonly timestamp: number;\n readonly chainValid: boolean;\n readonly chainError?: string;\n readonly corroboratesDenial?: boolean;\n readonly rootIssuer?: string;\n readonly leafHolder?: string;\n};\n\n// ---------------------------------------------------------------------------\n// Presenting authority across any boundary\n// ---------------------------------------------------------------------------\n\n/** Warrant chain plus proof-of-possession for one call. Transport-agnostic. */\nexport type PresentedCall = {\n readonly warrant: string;\n readonly signature: string;\n readonly approvals?: readonly string[];\n};\n\nexport interface Session {\n readonly [Symbol.toStringTag]: \"TenuoSession\";\n /** Warrant tokens, root first. Does not include the holder secret. */\n toWire(): readonly string[];\n /** SHA-256 of `(warrant_id, tool, canonical args)`. App-level idempotency, not PoP. */\n dedupKey(tool: string, args: Readonly<Record<string, unknown>>): string;\n /** Holder public key, depth, ceiling, lifetime, tools. Never the secret. */\n inspect(): SessionInfo;\n /**\n * Receipt helpers below are required for `createTenuo.runtime({ receipts:\n * \"collect\" })`. Implementers that are not runtime sessions can return\n * empty snapshots and `0` from acknowledge.\n */\n /**\n * Receipts collected for this session and not yet drained. Empty when the\n * session was not created by a Runtime with `receipts: \"collect\"`.\n */\n peekReceipts(): readonly string[];\n /**\n * Snapshot of collected receipts. Same as `peekReceipts`; nothing is removed\n * until `acknowledgeReceipts`.\n */\n drainReceipts(): readonly string[];\n /** Remove the first `count` pending receipts. */\n acknowledgeReceipts(count: number): number;\n}\n\nexport interface Tenuo {\n /**\n * Wrap any `{ execute }` tool (Vercel AI SDK, Mastra, plain object).\n * `parameters` / Zod stay on the inner tool and are never treated as authority.\n */\n tool<T extends { execute: (args: never) => unknown }>(\n inner: T,\n policy: ToolPolicy<Parameters<T[\"execute\"]>[0]>,\n ): ProtectedTool<T>;\n session(input: SessionInput): Session;\n /** Import a warrant minted elsewhere (Rust / Python / another process). */\n sessionFromWire(input: SessionFromWireInput): Session;\n withSession<R>(session: Session, fn: () => R): R;\n /**\n * Child session with less authority. Without options the same holder keeps\n * it; with `options.holder` it is delegated to another agent's key. Core\n * rejects any child that is not within its parent before a token exists.\n */\n narrow(session: Session, allow: NarrowInput, options?: NarrowOptions): Session;\n /**\n * Mint an execution session from an issuer session, signed by the issuer\n * session's holder. Core checks tools against `issuableTools`, constraints\n * against `constraintBounds`, clearance, and issue depth. No root key.\n */\n issue(issuer: Session, input: IssueInput): Session;\n /**\n * Public key of the local issuer (dev root or issuer key). Other processes\n * put it in `trustedRoots` to accept warrants this context mints.\n */\n issuerPublicKey(): PublicKeyHandle;\n /** What the session would decide for `tool(args)`, field by field. Never runs the tool. */\n explain(session: Session, tool: string, args: Readonly<Record<string, unknown>>): Explanation;\n /** Everything an approval service needs to present `tool(args)` to a human. */\n approvalRequest(session: Session, tool: string, args: Readonly<Record<string, unknown>>): ApprovalRequest;\n /** Holder-signed proof that this session is the one asking for `tool(args)`. */\n attestApprovalRequest(\n session: Session,\n tool: string,\n args: Readonly<Record<string, unknown>>,\n ): ApprovalContextAttestation;\n /** Authorize locally, then produce warrant + proof-of-possession for another boundary to verify. */\n present(\n session: Session,\n tool: string,\n args: Readonly<Record<string, unknown>>,\n options?: McpAttachOptions,\n ): PresentedCall;\n /** Verify a presented call at any boundary. Resolves with the authorized arguments; the tool must not run otherwise. */\n verify(\n presented: PresentedCall,\n tool: string,\n args: Readonly<Record<string, unknown>>,\n options?: McpVerifyOptions,\n ): Promise<Readonly<Record<string, unknown>>>;\n /** Sign a revocation list with this context's issuer key. Load it with `revoke()` where this issuer is trusted. */\n revocationList(input: RevocationListInput): string;\n /** Load a published SignedRevocationList. Rust verifies the issuer against trusted roots. */\n revoke(list: string | Uint8Array): void;\n /** MCP `_meta.tenuo` attach / verify. No MCP SDK dependency. */\n readonly mcp: TenuoMcp;\n ready(): void;\n}\n\n/** Wire envelope Python and TypeScript both read from `params._meta`. */\nexport type TenuoMcpMeta = {\n readonly tenuo: PresentedCall;\n};\n\nexport type McpAttachOptions = {\n readonly approvals?: readonly (string | Uint8Array)[];\n readonly onReceipt?: (receipt: string) => void | Promise<void>;\n /**\n * Correlation handle written to the receipt. Use whatever id the host\n * already has — a JSON-RPC id, a trace or span id — so a receipt can be\n * matched against your own logs. Not an identity: nothing enforces\n * uniqueness, and distinguishing repeated calls is the receipt chain's job.\n */\n readonly requestId?: string;\n};\n\n/** Host ceiling and optional receipt hook on `mcp.handler()`. */\nexport type McpHandlerPolicy = {\n readonly allow?: AllowPolicy;\n readonly onReceipt?: (receipt: string) => void | Promise<void>;\n readonly nonceStore?: NonceStore;\n /**\n * Isolated. Called when `nonceStore.checkAndRecord` throws or rejects.\n * The client only ever sees \"Replay store unavailable\".\n */\n readonly onNonceStoreError?: (error: unknown) => void | Promise<void>;\n};\n\nexport type McpVerifyOptions = {\n readonly allow?: AllowPolicy;\n readonly onReceipt?: (receipt: string) => void | Promise<void>;\n /**\n * Opt-in exact-PoP replay check. `checkAndRecord` may return a Promise\n * (Redis). A rejected Promise fails closed. In-memory stores do not work\n * across processes. PoP v1 is otherwise replayable in-window, including\n * envelopes that already carry approvals.\n */\n readonly nonceStore?: NonceStore;\n /**\n * Isolated. Called when `nonceStore.checkAndRecord` throws or rejects.\n * The client only ever sees \"Replay store unavailable\".\n */\n readonly onNonceStoreError?: (error: unknown) => void | Promise<void>;\n /**\n * Correlation handle written to the receipt. Use whatever id the host\n * already has — a JSON-RPC id, a trace or span id — so a receipt can be\n * matched against your own logs. Not an identity: nothing enforces\n * uniqueness, and distinguishing repeated calls is the receipt chain's job.\n */\n readonly requestId?: string;\n};\n\n/**\n * Returns true if the PoP is fresh and recorded; false if this exact token\n * was already consumed. Async stores (Redis) return `Promise<boolean>`.\n * `verify()` / handlers await the result. Never return a Promise from a\n * store that is only consulted synchronously — that used to fail open.\n */\nexport type NonceStore = {\n checkAndRecord(popSignature: string): boolean | Promise<boolean>;\n};\n\nexport type McpCallParams = {\n readonly name: string;\n readonly arguments: Readonly<Record<string, unknown>>;\n readonly _meta: TenuoMcpMeta;\n};\n\nexport type McpJsonRpcError = {\n readonly code: -32602 | -32001 | -32002;\n readonly message: string;\n readonly data?: { readonly tenuo?: { readonly code: TenuoErrorCode } };\n};\n\nexport interface TenuoMcp {\n /** Local authorize, then put warrant + PoP on `_meta.tenuo`. */\n attach(\n session: Session,\n name: string,\n args: Readonly<Record<string, unknown>>,\n options?: McpAttachOptions,\n ): McpCallParams;\n /**\n * Server path. Verifies a presented warrant + PoP. Tool handler must not\n * run unless this returns.\n */\n verify(\n name: string,\n args: Readonly<Record<string, unknown>>,\n meta: unknown,\n options?: McpVerifyOptions,\n ): Promise<Readonly<Record<string, unknown>>>;\n /** Wrap a handler: verify from `extra._meta` / `extra.meta`, then execute. */\n handler<TArgs extends Record<string, unknown>, TResult>(\n name: string,\n execute: (args: TArgs) => TResult | Promise<TResult>,\n ): (\n args: TArgs,\n extra?: { readonly _meta?: unknown; readonly meta?: unknown },\n ) => Promise<TResult>;\n handler<TArgs extends Record<string, unknown>, TResult>(\n name: string,\n policy: McpHandlerPolicy,\n execute: (args: TArgs) => TResult | Promise<TResult>,\n ): (\n args: TArgs,\n extra?: { readonly _meta?: unknown; readonly meta?: unknown },\n ) => Promise<TResult>;\n jsonRpcError(error: unknown): McpJsonRpcError;\n}\n"]}
1
+ {"version":3,"file":"api.js","sourceRoot":"","sources":["../src/api.ts"],"names":[],"mappings":"AAAA;;;;;GAKG","sourcesContent":["/**\n * Frozen public contract for `@tenuo/core`.\n *\n * Names and shapes here are the review surface — do not grow this file with\n * protocol vocabulary (`Warrant`, `mint`, `guard`) as the lead API.\n */\n\n/** Canonical kebab-case codes from Rust `ErrorCode::name()` / `Denial::code()`. */\nexport type ProtocolDenialCode =\n | \"signature-invalid\"\n | \"untrusted-root\"\n | \"chain-broken\"\n | \"depth-exceeded\"\n | \"warrant-expired\"\n | \"tool-not-authorized\"\n | \"constraint-violation\"\n | \"pop-signature-invalid\"\n | \"approval-required\"\n | \"insufficient-approvals\"\n | \"warrant-revoked\";\n\n/** Legacy SCREAMING_SNAKE aliases accepted by existing TypeScript callers. */\nexport type LegacyTenuoErrorCode =\n | \"TENUO_NOT_READY\"\n | \"TENUO_CONFIGURATION\"\n | \"TENUO_CONSTRAINT_VIOLATION\"\n | \"TENUO_TOOL_NOT_AUTHORIZED\"\n | \"TENUO_WARRANT_EXPIRED\"\n | \"TENUO_UNTRUSTED_ROOT\"\n | \"TENUO_INVALID_POP\"\n | \"TENUO_SIGNATURE_INVALID\"\n | \"TENUO_CHAIN_INVALID\"\n | \"TENUO_DEPTH_EXCEEDED\"\n | \"TENUO_REVOKED\"\n | \"TENUO_APPROVAL_REQUIRED\"\n | \"TENUO_INSUFFICIENT_APPROVALS\"\n | \"TENUO_CANONICALIZATION\"\n | \"TENUO_NOT_IMPLEMENTED\";\n\nexport type TenuoErrorCode = ProtocolDenialCode | LegacyTenuoErrorCode;\n\n// ---------------------------------------------------------------------------\n// Constraints. Every kind is evaluated in the Rust core; TypeScript only\n// builds the marker object. The set matches the core `Constraint` enum.\n// ---------------------------------------------------------------------------\n\n/** Path-traversal-safe prefix. Core evaluates this; TypeScript does not. */\nexport type UnderConstraint = {\n readonly kind: \"under\";\n readonly root: string;\n /** Default true. */\n readonly caseSensitive?: boolean;\n /** Whether the root itself is allowed. Default true. */\n readonly allowEqual?: boolean;\n};\n\nexport type EmailConstraint = {\n readonly kind: \"email\";\n readonly domain: string;\n};\n\nexport type MaxConstraint = {\n readonly kind: \"max\";\n readonly value: number;\n};\n\nexport type MinConstraint = {\n readonly kind: \"min\";\n readonly value: number;\n};\n\nexport type RangeConstraint = {\n readonly kind: \"range\";\n readonly min?: number;\n readonly max?: number;\n readonly minExclusive?: boolean;\n readonly maxExclusive?: boolean;\n};\n\nexport type OneOfConstraint = {\n readonly kind: \"oneOf\";\n readonly values: readonly string[];\n};\n\nexport type NotOneOfConstraint = {\n readonly kind: \"notOneOf\";\n readonly values: readonly string[];\n};\n\nexport type PatternConstraint = {\n readonly kind: \"pattern\";\n readonly pattern: string;\n};\n\nexport type RegexConstraint = {\n readonly kind: \"regex\";\n readonly source: string;\n};\n\nexport type ExactConstraint = {\n readonly kind: \"exact\";\n readonly value: string | number | boolean;\n};\n\nexport type WildcardConstraint = {\n readonly kind: \"wildcard\";\n};\n\nexport type CidrConstraint = {\n readonly kind: \"cidr\";\n readonly network: string;\n};\n\nexport type UrlPatternConstraint = {\n readonly kind: \"urlPattern\";\n readonly pattern: string;\n};\n\nexport type UrlSafeConstraint = {\n readonly kind: \"urlSafe\";\n readonly schemes?: readonly string[];\n readonly allowDomains?: readonly string[];\n readonly denyDomains?: readonly string[];\n};\n\nexport type ShlexConstraint = {\n readonly kind: \"shlex\";\n readonly allow: readonly string[];\n};\n\nexport type ContainsConstraint = {\n readonly kind: \"contains\";\n readonly values: readonly (string | number | boolean)[];\n};\n\nexport type SubsetConstraint = {\n readonly kind: \"subset\";\n readonly values: readonly (string | number | boolean)[];\n};\n\nexport type AnyOfConstraint = {\n readonly kind: \"anyOf\";\n readonly constraints: readonly ConstraintExpr[];\n};\n\nexport type AllConstraint = {\n readonly kind: \"all\";\n readonly constraints: readonly ConstraintExpr[];\n};\n\nexport type NotConstraint = {\n readonly kind: \"not\";\n readonly constraint: ConstraintExpr;\n};\n\nexport type CelConstraint = {\n readonly kind: \"cel\";\n readonly expression: string;\n};\n\nexport type ConstraintExpr =\n | UnderConstraint\n | EmailConstraint\n | MaxConstraint\n | MinConstraint\n | RangeConstraint\n | OneOfConstraint\n | NotOneOfConstraint\n | PatternConstraint\n | RegexConstraint\n | ExactConstraint\n | WildcardConstraint\n | CidrConstraint\n | UrlPatternConstraint\n | UrlSafeConstraint\n | ShlexConstraint\n | ContainsConstraint\n | SubsetConstraint\n | AnyOfConstraint\n | AllConstraint\n | NotConstraint\n | CelConstraint;\n\n/** Per-argument allow policy. Not a Zod schema. */\nexport type AllowPolicy = {\n readonly [field: string]: ConstraintExpr;\n};\n\n/**\n * Framework tool shape we wrap. No dependency on `ai` / Mastra.\n * `parameters` is host-schema (usually Zod) and is never treated as authority.\n */\nexport type ToolLike<\n TArgs extends Record<string, unknown> = Record<string, unknown>,\n TResult = unknown,\n> = {\n readonly description?: string;\n readonly parameters?: unknown;\n execute: (args: TArgs, options?: unknown) => TResult | Promise<TResult>;\n};\n\ntype KeysOfUnion<T> = T extends unknown ? keyof T : never;\n\nexport type ToolPolicy<TArgs = undefined> = {\n /**\n * Host ceiling. AND'd with the session in Rust.\n * Non-empty maps are zero-trust: every call argument must be named here.\n * `{}` means no extra ceiling (session/warrant only). Required: a missing\n * `allow` or an unknown policy key throws. `session({ tools })` refuses a\n * tool whose `allow` is `{}` unless the session's own `allow` names that\n * capability explicitly, because an empty capability in a warrant accepts\n * any arguments.\n */\n readonly allow: [NonNullable<TArgs>] extends [object]\n ? [KeysOfUnion<NonNullable<TArgs>>] extends [never]\n ? AllowPolicy\n : string extends KeysOfUnion<NonNullable<TArgs>>\n ? AllowPolicy\n : number extends KeysOfUnion<NonNullable<TArgs>>\n ? AllowPolicy\n : symbol extends KeysOfUnion<NonNullable<TArgs>>\n ? AllowPolicy\n : { readonly [Field in KeysOfUnion<NonNullable<TArgs>>]?: ConstraintExpr }\n : AllowPolicy;\n readonly capability?: string;\n /**\n * Makes approvals one-use for this tool. When a call that carried\n * `approvals` is allowed, each approval envelope that matches the call is\n * recorded here before the tool body runs; an envelope the store has\n * already seen denies with `TENUO_INSUFFICIENT_APPROVALS`. Same\n * `NonceStore` shape as the MCP verify path; `memoryNonceStore()` works\n * for one process. The store must remember a key for as long as an\n * approval can live (one hour by default), so give `memoryNonceStore()` a\n * matching `ttlSeconds`. A store that throws, rejects, or returns a\n * non-boolean fails closed with \"Replay store unavailable\".\n */\n readonly nonceStore?: NonceStore;\n /** Isolated. Called when `nonceStore.checkAndRecord` throws or rejects. */\n readonly onNonceStoreError?: (error: unknown) => void | Promise<void>;\n};\n\n/** Compile-time brand only — never assigned at runtime. Do not `in`/`has` this key. */\ndeclare const protectedBrand: unique symbol;\n\n/**\n * Tenuo's per-call options. Other keys pass through to the wrapped tool's own\n * `execute`, except keys that look like a misspelled Tenuo option\n * (`sesion`, `approval`, `onReciept`), which throw instead of being ignored.\n */\nexport type ExecuteOptions = {\n readonly session?: Session;\n /** Already-signed approval envelopes (hex, standard base64, or CBOR bytes). */\n readonly approvals?: readonly (string | Uint8Array)[];\n /**\n * Signed evidence of the decision. Not a security hook.\n * Exceptions (sync or rejected Promise) are isolated and never deny or\n * fail the tool.\n */\n readonly onReceipt?: (receipt: string) => void | Promise<void>;\n /**\n * Correlation handle written to the receipt. Use whatever id the host\n * already has — a JSON-RPC id, a trace or span id — so a receipt can be\n * matched against your own logs. Not an identity: nothing enforces\n * uniqueness, and distinguishing repeated calls is the receipt chain's job.\n */\n readonly requestId?: string;\n};\n\ntype ExtraExecuteOptions<T extends { execute: (args: never) => unknown }> =\n T[\"execute\"] extends (args: never, options?: infer O) => unknown\n ? unknown extends O\n ? object\n : Omit<NonNullable<O>, keyof ExecuteOptions>\n : object;\n\n/** Wrapped tool. `execute` still authorizes; optional `{ session }` overrides ALS. */\nexport type ProtectedTool<T extends { execute: (args: never) => unknown }> = Omit<T, \"execute\"> & {\n execute: (\n args: Parameters<T[\"execute\"]>[0],\n options?: ExecuteOptions & ExtraExecuteOptions<T>,\n ) => Promise<Awaited<ReturnType<T[\"execute\"]>>>;\n readonly [protectedBrand]: true;\n};\n\n// ---------------------------------------------------------------------------\n// Approvals\n// ---------------------------------------------------------------------------\n\n/** Per-argument trigger for an approval gate. */\nexport type ArgApprovalGate =\n /** Every value of this argument fires the gate. */\n | \"all\"\n /** Only values satisfying the constraint fire the gate. */\n | { readonly when: ConstraintExpr }\n /** Every value except those satisfying the constraint fires the gate. Narrowable across delegation. */\n | { readonly exempt: ConstraintExpr };\n\n/** Gate on one tool: a message for the approver and optional per-argument triggers. */\nexport type ToolApprovalGate = {\n readonly message?: string;\n /** Absent: the whole tool is gated. */\n readonly args?: { readonly [field: string]: ArgApprovalGate };\n};\n\n/** Approval requirement. Host collects SignedApproval envelopes; Rust decides. */\nexport type RequireApproval = {\n readonly approvers: readonly PublicKeyHandle[];\n readonly min: number;\n /** Whole-tool gates. Defaults to every tool in the session when `gates` is absent too. */\n readonly tools?: readonly string[];\n /** Per-tool gates with messages and per-argument triggers. */\n readonly gates?: { readonly [tool: string]: ToolApprovalGate };\n};\n\n/** What an approval service needs to present a call to a human. Not a signed artifact. */\nexport type ApprovalRequest = {\n readonly requestId: string;\n readonly warrantId: string;\n readonly tool: string;\n readonly args: Readonly<Record<string, unknown>>;\n /** Hex SHA-256 committing to warrant id, tool, canonical args, and holder. */\n readonly requestHash: string;\n readonly holderPublicKey: string;\n readonly requiredApprovers: readonly string[];\n readonly minApprovals: number;\n /** Unix seconds. An approval cannot outlive the warrant. */\n readonly warrantExpiresAt: number;\n readonly createdAt: number;\n readonly message: string;\n};\n\n/** Holder-signed statement that it is the one asking. Carried in a control-plane request. */\nexport type ApprovalContextAttestation = {\n readonly version: number;\n readonly canonicalization: string;\n readonly warrantId: string;\n readonly tool: string;\n readonly requestHash: string;\n readonly holderKeyHex: string;\n readonly argsCanonicalCborB64: string;\n readonly signerKeyHex: string;\n readonly signatureB64: string;\n};\n\n/** Wire body for a control-plane approval API. Field names are the wire names. */\nexport type ControlPlaneApprovalRequestV1 = {\n readonly schema_version: 1;\n readonly request_id_hex: string;\n readonly warrant_id: string;\n readonly tool: string;\n readonly arguments: Readonly<Record<string, unknown>>;\n readonly request_hash_hex: string;\n readonly holder_public_key_hex: string;\n readonly required_approver_keys_hex: readonly string[];\n readonly min_approvals: number;\n readonly warrant_expires_at_unix: number;\n readonly created_at_unix: number;\n readonly attestation?: Readonly<Record<string, unknown>>;\n readonly temporal?: Readonly<Record<string, string>>;\n readonly message?: string;\n};\n\nexport type ControlPlaneApprovalResponseV1 = {\n readonly status: string;\n readonly signed_approvals_b64?: readonly string[];\n readonly error?: string;\n readonly server_request_id?: string;\n};\n\nexport type SignApprovalOptions = {\n /** Who approved, in the approver system's own terms. Required. */\n readonly externalId: string;\n /** Approval lifetime. Default one hour, always clamped to the warrant's expiry when given. */\n readonly ttlSeconds?: number;\n readonly warrantExpiresAt?: number;\n};\n\n/** Decoded approval envelope. Not authorization. */\nexport type ApprovalInfo = {\n readonly approverPublicKey: string;\n readonly requestHash: string;\n readonly externalId: string;\n readonly approvedAt: number;\n readonly expiresAt: number;\n readonly expired: boolean;\n readonly signatureValid: boolean;\n readonly error?: string;\n};\n\n// ---------------------------------------------------------------------------\n// Sessions\n// ---------------------------------------------------------------------------\n\nexport type SessionAllow = {\n readonly [capability: string]: AllowPolicy;\n};\n\n/** Named level or a number 0-255. Delegation can only lower it. */\nexport type Clearance =\n | number\n | \"untrusted\"\n | \"external\"\n | \"partner\"\n | \"internal\"\n | \"privileged\"\n | \"system\";\n\nexport type SessionInput = {\n /** Capability map. Optional when `tools` is set. Issuer sessions may omit it. */\n readonly allow?: SessionAllow;\n /** Wrapped tools from `tenuo.tool()`. Their `allow` is minted into the session. */\n readonly tools?: readonly object[];\n readonly ttlSeconds?: number;\n readonly requireApproval?: RequireApproval;\n /**\n * Issue to another agent's key instead of a fresh local holder. The\n * returned session cannot authorize here (it has no holder secret); send\n * `toWire()` to that agent, which imports it with `sessionFromWire()`.\n */\n readonly holder?: PublicKeyHandle;\n /**\n * How many times this authority may be delegated below the root.\n * `0` makes the session terminal. Omit for the protocol maximum.\n * Delegation can lower this ceiling and never raise it.\n */\n readonly maxDepth?: number;\n /**\n * `\"execution\"` (default) can call tools. `\"issuer\"` cannot call tools; its\n * holder can mint execution sessions with `tenuo.issue()` for the tools in\n * `issuableTools`, within `constraintBounds`, without the root key.\n */\n readonly kind?: \"execution\" | \"issuer\";\n readonly clearance?: Clearance;\n /** Free-form task correlation id. Inherited unchanged through delegation. */\n readonly sessionId?: string;\n /** Free-form agent label. Delegation may change it. */\n readonly agentId?: string;\n /** Issuer sessions only. */\n readonly issuableTools?: readonly string[];\n /** Issuer sessions only: ceiling on the constraints of anything issued, by field. */\n readonly constraintBounds?: AllowPolicy;\n /** Issuer sessions only: how deep issued sessions may themselves delegate. */\n readonly maxIssueDepth?: number;\n};\n\n/** Options for `tenuo.narrow()`. All optional; the default keeps the holder. */\nexport type NarrowOptions = {\n /**\n * Bind the child to another agent's key. This is delegation: the current\n * holder signs, the child belongs to `holder`, and the returned session\n * cannot authorize here. Hand `toWire()` to that agent.\n */\n readonly holder?: PublicKeyHandle;\n /**\n * Child lifetime. A value longer than the parent has left is clamped to the\n * parent's expiry, not rejected: the child never outlives the parent.\n */\n readonly ttlSeconds?: number;\n /** The child's holder cannot delegate further. */\n readonly terminal?: boolean;\n /** Lower the delegation ceiling. Cannot exceed the parent's. */\n readonly maxDepth?: number;\n /** Lower the clearance. Cannot exceed the parent's. */\n readonly clearance?: Clearance;\n readonly agentId?: string;\n /** Approvers can only be added. */\n readonly addApprovers?: readonly PublicKeyHandle[];\n /** The threshold can only go up. A value below the parent's throws. */\n readonly minApprovals?: number;\n};\n\n/** Options for `tenuo.issue()`: an execution session minted from an issuer session. */\nexport type IssueInput = {\n readonly allow: SessionAllow;\n /** The distinct agent that will use it. Issuer/holder separation is enforced. */\n readonly holder: PublicKeyHandle;\n readonly ttlSeconds?: number;\n readonly maxDepth?: number;\n readonly clearance?: Clearance;\n readonly sessionId?: string;\n readonly agentId?: string;\n /** Approval policy for the issued execution session. Defaults to gating every issued tool. */\n readonly requireApproval?: RequireApproval;\n};\n\n/** Public view of a session's leaf. Never includes the holder secret. */\nexport type SessionInfo = {\n readonly kind: \"execution\" | \"issuer\";\n /** Hex public key the leaf is bound to. */\n readonly holderPublicKey: string;\n /** Hex public key that signed the root of the chain. */\n readonly rootPublicKey: string;\n /** 0 for a root session, +1 per delegation. */\n readonly depth: number;\n /** Delegation ceiling in force for this leaf. */\n readonly maxDepth: number;\n /** True when `depth >= maxDepth`: cannot be narrowed further. */\n readonly terminal: boolean;\n /** Unix seconds. */\n readonly expiresAt: number;\n readonly tools: readonly string[];\n /** Warrant ids, root first. */\n readonly warrantIds: readonly string[];\n /**\n * True when this process holds the leaf's holder secret. False for a\n * session issued or delegated to another agent: `toWire()` works,\n * `execute` and `narrow` do not.\n */\n readonly canAuthorize: boolean;\n readonly clearance?: number;\n readonly sessionId?: string;\n readonly agentId?: string;\n readonly issuableTools?: readonly string[];\n readonly maxIssueDepth?: number;\n readonly requiredApprovers?: readonly string[];\n readonly minApprovals?: number;\n readonly approvalGatedTools: readonly string[];\n};\n\n/** One constrained argument in an `explain()` result. */\nexport type ExplainedField = {\n readonly field: string;\n /** Core constraint type name, e.g. `\"Subpath\"`, `\"Range\"`. */\n readonly kind: string;\n /** The constraint as core serializes it. */\n readonly constraint: unknown;\n /** Absent when the argument was not supplied. */\n readonly value?: unknown;\n readonly satisfied: boolean;\n /** Stable machine-readable diagnostic, when the core can identify one. */\n readonly reasonCode?: string;\n readonly reason?: string;\n};\n\n/** What a session would decide for `tool(args)`, field by field. No proof-of-possession involved. */\nexport type Explanation = {\n readonly tool: string;\n readonly kind: \"execution\" | \"issuer\";\n readonly outcome: \"allow\" | \"deny\";\n readonly code?: TenuoErrorCode;\n readonly field?: string;\n readonly message?: string;\n readonly toolGranted: boolean;\n readonly fields: readonly ExplainedField[];\n /** Arguments the session does not name. Zero-trust policies reject these. */\n readonly unknownFields: readonly string[];\n /** Constrained arguments the call did not supply. */\n readonly missingFields: readonly string[];\n readonly expired: boolean;\n readonly expiresAt: number;\n readonly chainValid: boolean;\n readonly chainError?: TenuoErrorCode;\n};\n\nexport type DevRoot = {\n readonly kind: \"dev-root\";\n /**\n * Required when `NODE_ENV` is unset or is not `development` / `test`.\n * Unset `NODE_ENV` is not treated as development.\n */\n readonly allowInProduction?: boolean;\n};\n\n/** A stable issuer secret: this process is a control plane. */\nexport type IssuerKey = {\n readonly kind: \"issuer-key\";\n readonly secret: Uint8Array;\n};\n\nexport type PublicKeyHandle = {\n readonly kind: \"public-key\";\n readonly source: \"env\" | \"hex\" | \"bytes\";\n readonly hex: string;\n};\n\nexport type WarrantPart = {\n readonly payload_hex: string;\n readonly signature_hex: string;\n};\n\nexport type SessionFromWireInput = {\n readonly warrant: string | readonly string[] | readonly WarrantPart[];\n readonly holderKey: Uint8Array;\n};\n\n/** Field-level (`{ path: under(\"/data\") }`) or per-capability (`{ read_file: { path: ... } }`). */\nexport type NarrowInput = AllowPolicy | SessionAllow;\n\nexport type CreateTenuoOptions = {\n readonly trustedRoots?: readonly PublicKeyHandle[];\n /**\n * `devRoot()` for development; an `issuerKey*` for a control plane that\n * mints with a stable key; a public key for a verifier. An issuer key\n * trusts itself plus `trustedRoots`.\n */\n readonly root?: DevRoot | IssuerKey | PublicKeyHandle;\n /** Published SignedRevocationList (hex or standard base64). Verified against a trusted root. */\n readonly revocationList?: string | Uint8Array;\n /** 32-byte holder seed used to sign verifier receipts. Runtime supplies this. */\n readonly receiptSigner?: Uint8Array;\n};\n\nexport type ApprovalRequestSummary = {\n readonly tool: string;\n readonly required: number;\n readonly received: number;\n};\n\nexport type Decision =\n | { readonly outcome: \"allow\"; readonly args: Readonly<Record<string, unknown>> }\n | { readonly outcome: \"deny\"; readonly code: TenuoErrorCode; readonly field?: string }\n | { readonly outcome: \"approval_required\"; readonly request: ApprovalRequestSummary };\n\n// ---------------------------------------------------------------------------\n// Revocation and receipts\n// ---------------------------------------------------------------------------\n\nexport type RevocationListInput = {\n readonly revoke: readonly string[];\n /** Monotonic; verifiers refuse an older version. Default 1. */\n readonly version?: number;\n};\n\nexport type RevocationListInfo = {\n readonly version: number;\n readonly issuedAt: number;\n readonly issuerPublicKey: string;\n readonly revokedIds: readonly string[];\n readonly signatureValid: boolean;\n};\n\n/** Signature authenticity of a receipt. Not authorization. */\nexport type ReceiptInfo = {\n readonly authentic: true;\n /** Hex key the receipt is signed under — resolve against your own authorizer set. */\n readonly signerKey: string;\n readonly outcome: \"allow\" | \"deny\";\n readonly action: string;\n readonly decisionCode?: string;\n readonly requestId: string;\n readonly srlVersion?: number;\n readonly srlHash?: string;\n readonly requestHash?: string;\n readonly policyDefinitionHash?: string;\n readonly prevReceiptHash?: string;\n readonly trustedRootsHash?: string;\n};\n\n/** Root-anchored receipt check: the embedded chain against trusted roots at decision time. */\nexport type ReceiptChainInfo = {\n readonly signerKey: string;\n readonly outcome: \"allow\" | \"deny\";\n readonly decisionCode?: string;\n readonly timestamp: number;\n readonly chainValid: boolean;\n readonly chainError?: string;\n readonly corroboratesDenial?: boolean;\n readonly rootIssuer?: string;\n readonly leafHolder?: string;\n};\n\n// ---------------------------------------------------------------------------\n// Presenting authority across any boundary\n// ---------------------------------------------------------------------------\n\n/** Warrant chain plus proof-of-possession for one call. Transport-agnostic. */\nexport type PresentedCall = {\n readonly warrant: string;\n readonly signature: string;\n readonly approvals?: readonly string[];\n};\n\nexport interface Session {\n readonly [Symbol.toStringTag]: \"TenuoSession\";\n /** Warrant tokens, root first. Does not include the holder secret. */\n toWire(): readonly string[];\n /**\n * The whole chain as one string: a CBOR warrant stack in URL-safe base64,\n * the same encoding as `PresentedCall.warrant`. Use it where only a single\n * string fits (an environment variable, a header). `sessionFromWire()`\n * imports it. Does not include the holder secret.\n */\n toWireString(): string;\n /** SHA-256 of `(warrant_id, tool, canonical args)`. App-level idempotency, not PoP. */\n dedupKey(tool: string, args: Readonly<Record<string, unknown>>): string;\n /** Holder public key, depth, ceiling, lifetime, tools. Never the secret. */\n inspect(): SessionInfo;\n /**\n * Receipt helpers below are required for `createTenuo.runtime({ receipts:\n * \"collect\" })`. Implementers that are not runtime sessions can return\n * empty snapshots and `0` from acknowledge.\n */\n /**\n * Receipts collected for this session and not yet drained. Empty when the\n * session was not created by a Runtime with `receipts: \"collect\"`.\n */\n peekReceipts(): readonly string[];\n /**\n * Snapshot of collected receipts. Same as `peekReceipts`; nothing is removed\n * until `acknowledgeReceipts`.\n */\n drainReceipts(): readonly string[];\n /** Remove the first `count` pending receipts. */\n acknowledgeReceipts(count: number): number;\n}\n\nexport interface Tenuo {\n /**\n * Wrap any `{ execute }` tool (Vercel AI SDK, Mastra, plain object).\n * `parameters` / Zod stay on the inner tool and are never treated as authority.\n */\n tool<T extends { execute: (args: never) => unknown }>(\n inner: T,\n policy: ToolPolicy<Parameters<T[\"execute\"]>[0]>,\n ): ProtectedTool<T>;\n session(input: SessionInput): Session;\n /** Import a warrant minted elsewhere (Rust / Python / another process). */\n sessionFromWire(input: SessionFromWireInput): Session;\n withSession<R>(session: Session, fn: () => R): R;\n /**\n * Child session with less authority. Without options the same holder keeps\n * it; with `options.holder` it is delegated to another agent's key. Core\n * rejects any child that is not within its parent before a token exists.\n */\n narrow(session: Session, allow: NarrowInput, options?: NarrowOptions): Session;\n /**\n * Mint an execution session from an issuer session, signed by the issuer\n * session's holder. Core checks tools against `issuableTools`, constraints\n * against `constraintBounds`, clearance, and issue depth. No root key.\n */\n issue(issuer: Session, input: IssueInput): Session;\n /**\n * Public key of the local issuer (dev root or issuer key). Other processes\n * put it in `trustedRoots` to accept warrants this context mints.\n */\n issuerPublicKey(): PublicKeyHandle;\n /** What the session would decide for `tool(args)`, field by field. Never runs the tool. */\n explain(session: Session, tool: string, args: Readonly<Record<string, unknown>>): Explanation;\n /** Everything an approval service needs to present `tool(args)` to a human. */\n approvalRequest(session: Session, tool: string, args: Readonly<Record<string, unknown>>): ApprovalRequest;\n /** Holder-signed proof that this session is the one asking for `tool(args)`. */\n attestApprovalRequest(\n session: Session,\n tool: string,\n args: Readonly<Record<string, unknown>>,\n ): ApprovalContextAttestation;\n /** Authorize locally, then produce warrant + proof-of-possession for another boundary to verify. */\n present(\n session: Session,\n tool: string,\n args: Readonly<Record<string, unknown>>,\n options?: McpAttachOptions,\n ): PresentedCall;\n /**\n * Verify a presented call at any boundary. Resolves with the authorized\n * arguments; the tool must not run otherwise. `args` is the object already\n * given to this function. A repeated key in the original JSON is not\n * visible. Parse that text with `parseStrictJson` while it is still available.\n */\n verify(\n presented: PresentedCall,\n tool: string,\n args: Readonly<Record<string, unknown>>,\n options?: McpVerifyOptions,\n ): Promise<Readonly<Record<string, unknown>>>;\n /** Sign a revocation list with this context's issuer key. Load it with `revoke()` where this issuer is trusted. */\n revocationList(input: RevocationListInput): string;\n /** Load a published SignedRevocationList. Rust verifies the issuer against trusted roots. */\n revoke(list: string | Uint8Array): void;\n /** MCP `_meta.tenuo` attach / verify. No MCP SDK dependency. */\n readonly mcp: TenuoMcp;\n ready(): void;\n}\n\n/** Wire envelope Python and TypeScript both read from `params._meta`. */\nexport type TenuoMcpMeta = {\n readonly tenuo: PresentedCall;\n};\n\nexport type McpAttachOptions = {\n readonly approvals?: readonly (string | Uint8Array)[];\n readonly onReceipt?: (receipt: string) => void | Promise<void>;\n /**\n * Correlation handle written to the receipt. Use whatever id the host\n * already has — a JSON-RPC id, a trace or span id — so a receipt can be\n * matched against your own logs. Not an identity: nothing enforces\n * uniqueness, and distinguishing repeated calls is the receipt chain's job.\n */\n readonly requestId?: string;\n};\n\n/** Host ceiling and optional receipt hook on `mcp.handler()`. */\nexport type McpHandlerPolicy = {\n readonly allow?: AllowPolicy;\n readonly onReceipt?: (receipt: string) => void | Promise<void>;\n readonly nonceStore?: NonceStore;\n /**\n * Isolated. Called when `nonceStore.checkAndRecord` throws or rejects.\n * The client only ever sees \"Replay store unavailable\".\n */\n readonly onNonceStoreError?: (error: unknown) => void | Promise<void>;\n};\n\nexport type McpVerifyOptions = {\n readonly allow?: AllowPolicy;\n readonly onReceipt?: (receipt: string) => void | Promise<void>;\n /**\n * Opt-in exact-PoP replay check. `checkAndRecord` may return a Promise\n * (Redis). A rejected Promise fails closed. In-memory stores do not work\n * across processes. PoP v1 is otherwise replayable in-window, including\n * envelopes that already carry approvals.\n */\n readonly nonceStore?: NonceStore;\n /**\n * Isolated. Called when `nonceStore.checkAndRecord` throws or rejects.\n * The client only ever sees \"Replay store unavailable\".\n */\n readonly onNonceStoreError?: (error: unknown) => void | Promise<void>;\n /**\n * Correlation handle written to the receipt. Use whatever id the host\n * already has — a JSON-RPC id, a trace or span id — so a receipt can be\n * matched against your own logs. Not an identity: nothing enforces\n * uniqueness, and distinguishing repeated calls is the receipt chain's job.\n */\n readonly requestId?: string;\n};\n\n/**\n * Returns true if the PoP is fresh and recorded; false if this exact token\n * was already consumed. Async stores (Redis) return `Promise<boolean>`.\n * `verify()` / handlers await the result. Never return a Promise from a\n * store that is only consulted synchronously — that used to fail open.\n */\nexport type NonceStore = {\n checkAndRecord(popSignature: string): boolean | Promise<boolean>;\n};\n\nexport type McpCallParams = {\n readonly name: string;\n readonly arguments: Readonly<Record<string, unknown>>;\n readonly _meta: TenuoMcpMeta;\n};\n\nexport type McpJsonRpcError = {\n readonly code: -32602 | -32001 | -32002;\n readonly message: string;\n readonly data?: { readonly tenuo?: { readonly code: TenuoErrorCode } };\n};\n\nexport interface TenuoMcp {\n /** Local authorize, then put warrant + PoP on `_meta.tenuo`. */\n attach(\n session: Session,\n name: string,\n args: Readonly<Record<string, unknown>>,\n options?: McpAttachOptions,\n ): McpCallParams;\n /**\n * Server path. Verifies a presented warrant + PoP against the object it was\n * given. A repeated key in the original JSON is not visible: the host has\n * already parsed `args`. Parse that text with `parseStrictJson` while it is\n * still available. The tool handler must not run unless this returns.\n */\n verify(\n name: string,\n args: Readonly<Record<string, unknown>>,\n meta: unknown,\n options?: McpVerifyOptions,\n ): Promise<Readonly<Record<string, unknown>>>;\n /** Wrap a handler: verify from `extra._meta` / `extra.meta`, then execute. */\n handler<TArgs extends Record<string, unknown>, TResult>(\n name: string,\n execute: (args: TArgs) => TResult | Promise<TResult>,\n ): (\n args: TArgs,\n extra?: { readonly _meta?: unknown; readonly meta?: unknown },\n ) => Promise<TResult>;\n handler<TArgs extends Record<string, unknown>, TResult>(\n name: string,\n policy: McpHandlerPolicy,\n execute: (args: TArgs) => TResult | Promise<TResult>,\n ): (\n args: TArgs,\n extra?: { readonly _meta?: unknown; readonly meta?: unknown },\n ) => Promise<TResult>;\n jsonRpcError(error: unknown): McpJsonRpcError;\n}\n"]}
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "package": "@tenuo/core",
3
- "version": "0.3.1-beta.0",
4
- "sourceCommit": "beacaf0b92abb238f1df39ee97479a988f63a339",
3
+ "version": "0.3.3-beta.0",
4
+ "sourceCommit": "6d0b668f3d4d4da137967624eee5e307462ded54",
5
5
  "sourceClean": false,
6
- "wasmSha256": "02b056ba107079a1e9ee648d03cf28b6e1d04baf62f0ac3688347c307c25c7b0",
6
+ "wasmSha256": "7fb51e3beda0f2f0cb91863456d22ecc9b139fdfa869e65dead03b315adc3c22",
7
7
  "wasmMatchesCommit": false
8
8
  }