@jini-ai/core 0.3.1 → 0.4.1

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.
Files changed (97) hide show
  1. package/CHANGELOG.md +136 -0
  2. package/LICENSE +201 -0
  3. package/README.md +154 -14
  4. package/dist/agent-tools.d.ts +29 -0
  5. package/dist/agent-tools.js +2 -0
  6. package/dist/api-token-auth.d.ts +12 -5
  7. package/dist/api-token-auth.js +7 -7
  8. package/dist/bindings.d.ts +16 -5
  9. package/dist/bindings.js +7 -6
  10. package/dist/{internal.d.ts → composition.d.ts} +9 -9
  11. package/dist/{internal.js → composition.js} +9 -9
  12. package/dist/contribution-registry.d.ts +16 -0
  13. package/dist/contribution-registry.js +12 -0
  14. package/dist/daemon.d.ts +12 -7
  15. package/dist/daemon.js +21 -9
  16. package/dist/gated-mutations/actor-identity.d.ts +20 -0
  17. package/dist/gated-mutations/actor-identity.js +31 -0
  18. package/dist/gated-mutations/gateway.d.ts +115 -0
  19. package/dist/gated-mutations/gateway.js +123 -0
  20. package/dist/gated-mutations/ports.d.ts +27 -0
  21. package/dist/gated-mutations/ports.js +2 -0
  22. package/dist/gated-mutations/token.d.ts +95 -0
  23. package/dist/gated-mutations/token.js +87 -0
  24. package/dist/gated-mutations.d.ts +5 -0
  25. package/dist/gated-mutations.js +5 -0
  26. package/dist/index.d.ts +8 -2
  27. package/dist/index.js +5 -0
  28. package/dist/model-facing-tool-errors.d.ts +37 -0
  29. package/dist/model-facing-tool-errors.js +71 -0
  30. package/dist/naming.d.ts +31 -0
  31. package/dist/naming.js +33 -0
  32. package/dist/origin-validation.d.ts +64 -19
  33. package/dist/origin-validation.js +43 -33
  34. package/dist/pack-lifecycle.d.ts +19 -12
  35. package/dist/pack-lifecycle.js +14 -14
  36. package/dist/pack.d.ts +41 -13
  37. package/dist/pack.js +2 -2
  38. package/dist/primitives/http.d.ts +57 -0
  39. package/dist/primitives/http.js +2 -0
  40. package/dist/primitives/ids.d.ts +8 -0
  41. package/dist/primitives/ids.js +5 -0
  42. package/dist/primitives/index.d.ts +8 -0
  43. package/dist/primitives/index.js +8 -0
  44. package/dist/primitives/json.d.ts +10 -0
  45. package/dist/primitives/json.js +2 -0
  46. package/dist/primitives/logger.d.ts +26 -0
  47. package/dist/primitives/logger.js +17 -0
  48. package/dist/primitives/paths.d.ts +16 -0
  49. package/dist/primitives/paths.js +38 -0
  50. package/dist/primitives/result.d.ts +9 -0
  51. package/dist/primitives/result.js +2 -0
  52. package/dist/primitives/time.d.ts +17 -0
  53. package/dist/primitives/time.js +13 -0
  54. package/dist/redact.d.ts +43 -8
  55. package/dist/redact.js +121 -50
  56. package/dist/registration-kit.d.ts +357 -0
  57. package/dist/registration-kit.js +439 -0
  58. package/dist/text/index.d.ts +3 -0
  59. package/dist/text/index.js +2 -0
  60. package/dist/text/sanitize-untrusted-text.d.ts +22 -0
  61. package/dist/text/sanitize-untrusted-text.js +108 -0
  62. package/dist/token.d.ts +29 -2
  63. package/dist/token.js +22 -2
  64. package/dist/tool-registry.d.ts +32 -16
  65. package/dist/tool-registry.js +11 -11
  66. package/dist/tool-tokens.js +1 -1
  67. package/package.json +56 -11
  68. package/dist/api-token-auth.d.ts.map +0 -1
  69. package/dist/api-token-auth.js.map +0 -1
  70. package/dist/bindings.d.ts.map +0 -1
  71. package/dist/bindings.js.map +0 -1
  72. package/dist/compose.typecheck.d.ts +0 -2
  73. package/dist/compose.typecheck.d.ts.map +0 -1
  74. package/dist/compose.typecheck.js +0 -29
  75. package/dist/compose.typecheck.js.map +0 -1
  76. package/dist/daemon.d.ts.map +0 -1
  77. package/dist/daemon.js.map +0 -1
  78. package/dist/index.d.ts.map +0 -1
  79. package/dist/index.js.map +0 -1
  80. package/dist/internal.d.ts.map +0 -1
  81. package/dist/internal.js.map +0 -1
  82. package/dist/origin-validation.d.ts.map +0 -1
  83. package/dist/origin-validation.js.map +0 -1
  84. package/dist/pack-lifecycle.d.ts.map +0 -1
  85. package/dist/pack-lifecycle.js.map +0 -1
  86. package/dist/pack.d.ts.map +0 -1
  87. package/dist/pack.js.map +0 -1
  88. package/dist/principal.d.ts.map +0 -1
  89. package/dist/principal.js.map +0 -1
  90. package/dist/redact.d.ts.map +0 -1
  91. package/dist/redact.js.map +0 -1
  92. package/dist/token.d.ts.map +0 -1
  93. package/dist/token.js.map +0 -1
  94. package/dist/tool-registry.d.ts.map +0 -1
  95. package/dist/tool-registry.js.map +0 -1
  96. package/dist/tool-tokens.d.ts.map +0 -1
  97. package/dist/tool-tokens.js.map +0 -1
package/CHANGELOG.md ADDED
@@ -0,0 +1,136 @@
1
+ # @jini-ai/core
2
+
3
+ ## 0.4.1 — 2026-10-05
4
+
5
+ - New `readToolLimit({ input, max, fallback }, { key })`: an absent limit is `fallback`, one above `max` is capped at `max`, and a non-integer or one below 1 throws `ToolInputError` ("'limit' must be an integer between 1 and <max>").
6
+ - New `optionalOneOf({ input, key, values })`: a value outside `values` throws `ToolInputError` ("'<key>' must be one of: ..."). Both are additive.
7
+
8
+ ## 0.4.0 — 2026-10-02
9
+
10
+ ### BREAKING
11
+
12
+ - Canonical primitive ports, JSON/time/HTTP types and tool contracts now live in core; use ./composition instead of ./internal and ./text for untrusted-text handling.
13
+ - Distribution includes runtime output, release documentation and required assets only. Process records and per-job neutrality checks are no longer part of the package surface.
14
+
15
+ ## Unreleased
16
+
17
+ - Add browser-safe `pathContains` to `./primitives` for absolute lexical paths, with host-selected case sensitivity and complete directory-segment boundaries.
18
+
19
+ ### Shared registration wiring
20
+
21
+ - Move the domain-independent catalog/input/schema/risk/confirmation registration kit into the root entry, with its behavior contracts. Domain-specific authorization and denial errors remain outside the kernel.
22
+ - Use the existing named argument surface directly; primitive, Result and tool catalog types remain canonical in core.
23
+
24
+
25
+ ### Shared kernel
26
+
27
+ - Add `./primitives` with canonical time, ID, JSON, HTTP, logger and result contracts,
28
+ system/crypto/console default adapters, and UTC time helpers. No runtime dependencies.
29
+ - Add root agent-tool catalog types, preserving delete as a distinct risk classification.
30
+ - Add `./text` with the unchanged bounded terminal sanitizer and its behavior tests.
31
+ - Expand telemetry redaction to the union of core, CLI and provider rules, with literal
32
+ exact-secret masking and named extra patterns. Export the eleven diagnostics credential
33
+ regexes unchanged. Broader opaque/short bearer/header/query rules can mask more input;
34
+ union vectors and existing category tests document the behavior.
35
+ - Add UTF-8 `timingSafeTokenMatch` with a required injected native comparison port so the
36
+ kernel stays universal. Both original native comparators have identical results.
37
+
38
+ ### BREAKING — shared kernel
39
+
40
+ - Rename `./internal` to `./composition` without an alias. Authorized tool invocation and
41
+ pack binding derivation keep their implementation and security boundary.
42
+ - Gated mutations now require `Clock.nowMs()` and `IdGenerator.newId()` from primitives,
43
+ replacing the local `ClockPort.nowIso({})` and `IdGeneratorPort.newId({})`. Format clock
44
+ samples with `nowIso({ clock })`; approval order, TTL and wire timestamps are unchanged.
45
+ - Origin diagnostics use `Pick<Logger, 'warn'>` rather than a duplicate logger interface.
46
+ The alias name `OriginValidationLoggerPort` remains available with the shared shape.
47
+
48
+
49
+ - Add transport-neutral gated mutations with required token generation/TTL and async
50
+ authorization, identity and token-store ports; preserve verified-plan handoff and
51
+ single-use redemption, with atomic explicit expiry and duplicate-issuance rejection.
52
+ - Add domain-owned model-facing error allowlists, an instance-owned contribution
53
+ registry, and bounded naming with required collision, suffix and message policies.
54
+ - Add generalized approval, disclosure, registry and naming contract tests plus a
55
+ package-wide source-neutrality guard. Verification is deferred by owner directive;
56
+ the four subpath manifest exports are listed in `extraction-w4a.md` for coordination.
57
+
58
+ ### Extraction integration
59
+
60
+ - Publish `./gated-mutations`, `./model-facing-tool-errors`, `./contribution-registry`
61
+ and `./naming`, with universal runtime metadata and matching root barrel exports.
62
+ These entries implement the earlier manifest follow-ups in `extraction-w4a.md`;
63
+ no runtime dependency or version change is required.
64
+ - BREAKING: Existing core APIs now accept a required-args object and a separate
65
+ optional-args object. Tokens, bindings, registry lookups, pack callbacks/lifecycle,
66
+ redaction, auth/origin helpers, ToolInputError and internal authorization changed
67
+ shape with no compatibility adapters. Environment snapshots are explicit, origin
68
+ logging uses a supplied port, and optional handler emitSurface moved to the second
69
+ argument. Update consumers before adopting this release. Version unchanged.
70
+ - BREAKING: New extraction APIs follow the same convention: contribution
71
+ `list({})`/`clear({})`, `new InMemoryTokenStore({})`/`count({})`, approval
72
+ `computePlan({})`, `nowIso({})`, `newId({})` and `generateToken({})`, and marker-error
73
+ constructors `new ErrorClass({ message }, { cause? })`. `ForbiddenError` additionally
74
+ requires `reasonCode`; naming exhaustion callbacks receive `{ base, maxAttempts }`.
75
+ `AuthorizeFn` moves optional `entityType`/`entityId` selectors to its second object.
76
+ - Add package-entry identity, manifest/runtime, approval-port, error-cause and
77
+ convention contract tests. Extend the source-neutrality guard to the manifest.
78
+ All verification remains not run (owner directive).
79
+
80
+ ## 0.1.2
81
+
82
+ ### Patch Changes
83
+
84
+ - Add top-level `main`/`types` fields alongside the existing `exports` map. A consumer on
85
+ TypeScript's classic `moduleResolution: "node"` (node10) — which ignores `package.json#exports`
86
+ entirely — could not resolve this package's types at all (`TS2307: Cannot find module`) even
87
+ after the previous exports-map fix restored `require()` at runtime; type resolution and runtime
88
+ resolution are separate algorithms. Verified against a real external consumer (whose
89
+ tsconfig uses this legacy resolution mode): adding these two fields, with its tsconfig completely
90
+ unchanged, made the error disappear. Also fixes absolute-path `require()` (distinct from a bare
91
+ specifier, which already worked) for the same reason — `main` was previously absent.
92
+
93
+ Purely additive: every modern resolver (Node's own runtime `exports` resolution, TypeScript's
94
+ `bundler`/`node16`/`nodenext`) prefers `exports` over `main`/`types` when both are present, so
95
+ this changes nothing for a consumer already on a modern resolver.
96
+
97
+ ## 0.1.1
98
+
99
+ ### Patch Changes
100
+
101
+ - Add a `"default"` export condition to every published package's `exports` map — every one of
102
+ them lacked it, which meant `require()` failed with `ERR_PACKAGE_PATH_NOT_EXPORTED` for any
103
+ CommonJS consumer (found via a real external integration attempt; Node needs `require(esm)`
104
+ support, i.e. Node >=22.12, for this to resolve).
105
+
106
+ `@jini-ai/agent-runtime`:
107
+
108
+ - **New**: `RuntimeBuildOptions.permissionMode` (`'bypass' | 'restricted'`) lets a caller opt a
109
+ run OUT of the auto-approve-every-permission-prompt flag every def with one
110
+ (`bypassPermissions` / `--yolo` / `--dangerously-skip-permissions`) previously pushed
111
+ unconditionally, with no way to turn it off. Omitting it keeps today's default (bypass)
112
+ behavior unchanged.
113
+ - **New**: `ClaudeStreamEvent`, `CopilotStreamEvent`, and `QoderEvent` are now real exported
114
+ discriminated unions instead of `Record<string, unknown>` — a real external consumer guessed a
115
+ nonexistent field name (`event.text` instead of the actual `event.delta`) against the old
116
+ untyped sink and silently lost every streamed token with no compile or runtime error.
117
+ - Fixed a doc/implementation mismatch in `claude-stream.ts`: the module doc claimed `tool_result`
118
+ events carry `{ tool_use_id, content, is_error }`; the actual emitted shape is
119
+ `{ toolUseId, content, isError }`.
120
+
121
+ `@jini-ai/daemon`: `AgentExecutorRunInput.permissionMode` forwards the new
122
+ `RuntimeBuildOptions.permissionMode` through to `buildArgs`, so a host can actually reach the new
123
+ opt-out from the daemon's real run-input surface, not just from `@jini-ai/agent-runtime` in
124
+ isolation.
125
+
126
+ `@jini-ai/agentic`: `setAtPointer` no longer throws on a malformed (e.g. missing leading `/`)
127
+ `updateDataModel` path — degrades to a no-op like its sibling `getAtPointer`, matching this
128
+ package's own "a bad binding must not crash the renderer" contract. That path is agent-authored
129
+ wire data with no error boundary above it in any host, so the uncaught throw could unmount an
130
+ entire chat UI from ~40 bytes of malformed input.
131
+
132
+ `@jini-ai/chat-react`: a local (client-resolved) A2UI button action is no longer a silent no-op —
133
+ `A2uiSurfaceCard` now surfaces the resolved value. New `ExtEventErrorBoundary` confines a
134
+ `kind: 'ext'` event group's renderer to its own card instead of letting a render/effect-phase
135
+ throw from agent-controlled content unmount the whole chat root (there was no error boundary
136
+ anywhere in this package or its hosts before this).
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for 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 Support. While redistributing the Work or
166
+ Derivative Works thereof, You may choose to offer, and charge a
167
+ fee for, acceptance of support, warranty, indemnity, or other
168
+ liability obligations and/or rights consistent with this License.
169
+ However, in accepting such obligations, You may act only on Your
170
+ own behalf and on Your sole responsibility, not on behalf of any
171
+ other Contributor, and only if You agree to indemnify, defend,
172
+ and hold each Contributor harmless for any liability incurred by,
173
+ or claims asserted against, such Contributor by reason of your
174
+ accepting any such warranty or support.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Open Design contributors
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -19,17 +19,17 @@ No peer dependencies — this package is pure TypeScript with no runtime depende
19
19
 
20
20
  ## What you get
21
21
 
22
- - **DI tokens** — `token<T>(id)` / `manyToken<T>(id)`, nominal and versioned, plus `bindings()`
22
+ - **DI tokens** — `token<T>({ id }, { version? })` / `manyToken<T>({ id }, { version? })`, nominal and versioned, plus `bindings({})`
23
23
  building a typed `Bindings<BoundIds>` set (`.bind`, `.bindMany`) that tracks which ids are bound
24
24
  in its own type parameter.
25
- - **Pack composition** — `definePack({ name, deps, services, tools?, http?, cli?, dispose? })`,
26
- the `Pack`/`PackContainer` types, and `createDaemon({ packs, bindings, transports? })`, which
25
+ - **Pack composition** — `definePack({ name, deps, services }, { tools?, http?, cli?, dispose? })`,
26
+ the `Pack`/`PackContainer` types, and `createDaemon({ packs, bindings }, { transports? })`, which
27
27
  composes packs against bound tokens and resolves each pack's `services` against a container
28
28
  scoped to only that pack's declared `deps`.
29
29
  - **Pack lifecycle helpers** — `registerPackTools` (walks composed packs' `tools()` into a shared
30
30
  `ToolRegistry`) and `disposePacks` (best-effort reverse-order teardown; one pack's `dispose`
31
31
  failure never blocks another's, recorded as `PackDisposalFailure`).
32
- - **Tool registry** — `createToolRegistry()` and the `ToolRegistry`/`ToolDescriptor`/`ToolPolicy`/
32
+ - **Tool registry** — `createToolRegistry({})` and the `ToolRegistry`/`ToolDescriptor`/`ToolPolicy`/
33
33
  `ToolHandler`/`ToolRegistration`/`ToolAuthorizationContext`/`AuthorizationDecision` types. The
34
34
  registry's public surface (`register`/`has`/`list`) exposes descriptors only — handlers and
35
35
  policies are never publicly retrievable, so holding a `ToolRegistry` reference lets you enumerate
@@ -47,45 +47,59 @@ No peer dependencies — this package is pure TypeScript with no runtime depende
47
47
  import { bindings, definePack, createDaemon, token, createToolRegistry, registerPackTools } from '@jini-ai/core';
48
48
 
49
49
  interface Logger {
50
- log(msg: string): void;
50
+ log(required: { message: string }): void;
51
51
  }
52
52
 
53
- const LoggerToken = token<Logger>('app.logger');
53
+ const LoggerToken = token<Logger>({ id: 'app.logger' });
54
54
 
55
55
  const loggerPack = definePack({
56
56
  name: 'logger',
57
57
  deps: [],
58
- services: () => ({ logger: { log: (m: string) => console.log(m) } }),
58
+ services: () => ({ logger: { log: ({ message }: { message: string }) => console.log(message) } }),
59
59
  });
60
60
 
61
61
  const consumerPack = definePack({
62
62
  name: 'consumer',
63
63
  deps: [LoggerToken],
64
- services: (c) => ({ logger: c.get(LoggerToken) }),
64
+ services: (c) => ({ logger: c.get({ token: LoggerToken }) }),
65
65
  });
66
66
 
67
- const bound = bindings().bind(LoggerToken, { log: (m: string) => console.log(m) });
67
+ const bound = bindings({}).bind({ token: LoggerToken, impl: { log: ({ message }: { message: string }) => console.log(message) } });
68
68
 
69
69
  const daemon = createDaemon({
70
70
  packs: [loggerPack, consumerPack] as const,
71
71
  bindings: bound,
72
72
  });
73
73
 
74
- const registry = createToolRegistry();
75
- registerPackTools([loggerPack, consumerPack], daemon.services, registry);
74
+ const registry = createToolRegistry({});
75
+ registerPackTools({ registry, packs: [loggerPack, consumerPack], daemon });
76
76
  ```
77
77
 
78
+ Every callable takes a required object and, when needed, a separate optional object. Factories
79
+ with no required values take `{}`. Registry lookups use `registry.has({ toolId })` and
80
+ `registry.list({})`; registration already takes the required `{ descriptor, handler, policy }`.
81
+ Pack tools/disposal callbacks receive `{ services }`; HTTP and CLI callbacks receive
82
+ `{ app, services }` and `{ reg, services }`. A pack's services factory still receives its scoped
83
+ `PackContainer` port object directly.
84
+
85
+ Auth and origin helpers require `{ config, env }`, with `env` supplied by the host. For example,
86
+ `apiTokenFromEnv({ config, env: environmentSnapshot })`. `isLocalSameOrigin` additionally requires
87
+ `req` and `port`. Malformed-origin diagnostics go through the optional `{ logger }` port, whose
88
+ `warn({ message })` method the host supplies. No process environment or console logger is read.
89
+ Redaction takes `{ input }` and optional `{ exactSecrets, extraPatterns }`, and `ToolInputError` takes `{ message }` plus optional `{ cause }`.
90
+ Tool handlers receive required execution context first and optional `{ emitSurface }` second.
91
+
78
92
  ## Entry points
79
93
 
80
94
  | subpath | what's behind it |
81
95
  |---|---|
82
96
  | `.` | The public surface above: tokens, packs, daemon composition, tool registry (descriptors only), principal, redact, auth primitives. |
83
- | `./internal` | **Not part of the public contract.** Exposes `authorizeToolInvocation` (resolves a registry's tool and runs its authorization gate — a security-sensitive value export, but one that only ever hands back a handler alongside an `'allow'` decision) plus type-only `AnyPack`/`RequiredTokenIds`/`MissingTokenIds` re-derivation helpers. Its sole intended consumers are `@jini-ai/daemon`'s `ToolExecutor` and `@jini-ai/server`'s `createLocalNodeDaemon`. Node's resolver will happily let any consumer import it — the boundary is enforced by `scripts/check-engine-boundaries.ts`, not by the exports map — so external adopters should treat it as off-limits regardless. |
97
+ | `./composition` | **Not part of the public contract.** Exposes `authorizeToolInvocation` (resolves a registry's tool and runs its authorization gate — a security-sensitive value export, but one that only ever hands back a handler alongside an `'allow'` decision) plus type-only `AnyPack`/`RequiredTokenIds`/`MissingTokenIds` re-derivation helpers. Its sole intended consumers are `@jini-ai/daemon`'s `ToolExecutor` and `@jini-ai/server`'s `createLocalNodeDaemon`. Node's resolver will happily let any consumer import it — the boundary is enforced by `scripts/check-engine-boundaries.ts`, not by the exports map — so external adopters should treat it as off-limits regardless. |
84
98
 
85
99
  ## What's swappable
86
100
 
87
101
  Everything a pack declares as a `deps` token is a swap point by construction: bind any
88
- implementation that satisfies the token's type via `bindings().bind(...)`, and `createDaemon`
102
+ implementation that satisfies the token's type via `bindings({}).bind(...)`, and `createDaemon`
89
103
  resolves it into that pack's `PackContainer` with no other change. `ToolPolicy.authorize` is
90
104
  likewise a seam you supply per tool registration. The kernel logic itself (composition ordering,
91
105
  the missing-binding compile-time gate, the tool registry's append-only enforcement) is fixed and
@@ -98,4 +112,130 @@ ESM only — ships `"type": "module"` with no CommonJS `require` build.
98
112
 
99
113
  ## Provenance
100
114
 
101
- See [source-map.md](./source-map.md) for per-file provenance and scope decisions. Apache-2.0.
115
+ See the archived provenance ledger for per-file provenance and scope decisions. Apache-2.0.
116
+
117
+ ## Additional entry points
118
+
119
+ The four entries below also have named exports from the package root. Each is universal
120
+ and has no runtime dependency. Importing the root and a subpath shares the same
121
+ class and factory identities.
122
+
123
+ | Subpath | API and required ports |
124
+ |---|---|
125
+ | `./gated-mutations` | `plan`, `confirm`, `execute`, `authorizeForHooks`; authorization, clock, ID generation, complete opaque token generation, TTL, token store and mutation hooks. Includes token lifecycle and composite actor-reference helpers. |
126
+ | `./model-facing-tool-errors` | `forbiddenRule`, `reclassifyToolError`, `withModelFacingErrors`, `withModelFacingRegistrationErrors`, `callerSafeErrorMessage`; callers own ordered error allowlists and fallback wording. |
127
+ | `./contribution-registry` | `createContributionRegistry({ keyOf })`; instance-owned replacement by key, with detached array snapshots. |
128
+ | `./naming` | `deriveAvailableName`, `deriveDuplicateName`, `MAX_SUFFIX_ATTEMPTS`; required collision predicate, suffix formatter and exhaustion message policy. |
129
+
130
+ Contribution registries use `register({ contribution })`, `list({})` and `clear({})`.
131
+ Approval clock/ID ports use the shared zero-argument `Clock.nowMs()` and
132
+ `IdGenerator.newId()` getters. Token generation and `hooks.computePlan` still receive
133
+ an empty required object. `AuthorizeFn` takes `{ principalId, permission, workspaceId }` with optional
134
+ `{ entityType, entityId }` in the second object. The memory token adapter uses
135
+ `new InMemoryTokenStore({})` and `count({})`;
136
+ its persistence methods already accept named objects. Marker errors use
137
+ `new TokenExpiredError({ message }, { cause })` (and the same shape for the other
138
+ approval/actor marker errors). `ForbiddenError` also requires a `reasonCode`.
139
+ Error class identity, existing messages and authorization/redemption ordering are
140
+ preserved. The host supplies transaction/locking policy and hashes the full intent.
141
+
142
+ ```ts
143
+ import { createContributionRegistry } from '@jini-ai/core/contribution-registry';
144
+ import { deriveDuplicateName } from '@jini-ai/core/naming';
145
+
146
+ const registry = createContributionRegistry({
147
+ keyOf: ({ contribution }: { contribution: { domain: string } }) => contribution.domain,
148
+ });
149
+ registry.register({ contribution: { domain: 'example' } });
150
+ const snapshot = registry.list({});
151
+ registry.clear({});
152
+
153
+ const existing = new Set(['Example', 'Example 2']);
154
+ const duplicateName = await deriveDuplicateName({
155
+ sourceName: 'Example',
156
+ isTaken: async ({ candidate }) => existing.has(candidate),
157
+ withSuffix: ({ base, suffix }) => `${base} ${suffix}`,
158
+ exhaustionMessage: ({ base, maxAttempts }) => `No name available for ${base} after ${maxAttempts} attempts`,
159
+ }, { maxAttempts: 1000 }); // 'Example 3'
160
+ ```
161
+
162
+ Naming's optional `onExhausted({ base, maxAttempts })` port must throw. Approval token
163
+ stores must insert without overwriting issuance and atomically redeem/expire tokens;
164
+ `InMemoryTokenStore` provides that contract for tests and requires host retention policy
165
+ for long-lived use. There is no application layout, environment name or storage default.
166
+
167
+ The existing kernel APIs have also changed to object arguments. Update token/binding
168
+ calls, pack contributions, handler emitters and explicit environment snapshots before
169
+ using this unreleased version; see [CHANGELOG.md](./CHANGELOG.md) for BREAKING notes.
170
+
171
+ ## Design decisions
172
+
173
+ - [Confirmation checks have a fixed order and atomic redemption](docs/decisions/DR-001-gated-mutation-check-order.md).
174
+
175
+ ## Shared kernel contracts
176
+
177
+ Import `Clock`, `IdGenerator`, `UUID`, `ISODateTime`, `JsonPrimitive`, `JsonValue`,
178
+ `JsonObject`, `JsonArray`, `HttpRequest`, `HttpResponse`, `RequestRedirect`, `HttpClientPort`,
179
+ `Logger` and `Result` from `@jini-ai/core/primitives`. They are canonical structural types;
180
+ UUIDs and timestamps remain unbranded strings. The HTTP contract includes binary response
181
+ bytes, redirect provenance, socket idle budgets and an optional total deadline. Platform
182
+ supplies the guarded HTTP implementation; core defines the port only.
183
+
184
+ Default adapters are `createSystemClock()`, `createRandomUuidGenerator()` and
185
+ `createConsoleLogger({ prefix })`. Clock/ID getters take no arguments. Time helpers are
186
+ `toIsoDateTime({ epochMs })` and `nowIso({ clock })`. The UUID adapter requires a host
187
+ cryptographic UUID implementation and fails if unavailable. The console adapter routes
188
+ info/warn/error with optional `{ meta, error }` to the same console severity.
189
+
190
+ Agent-tool catalogs import `AgentToolSideEffect`, `AgentToolActorClassRule` and
191
+ `AgentToolDefinition` from the core root. Delete is a separate side-effect classification;
192
+ domains may tighten the shared interface, including making `inputSchema` required.
193
+
194
+ `@jini-ai/core/text` exports `sanitizeUntrustedText({ text }, { maxLength? })` and
195
+ `SanitizeTextOptions`. This terminal-boundary policy strips C0/C1 and ANSI control
196
+ sequences, masks labeled/opaque credentials and caps the complete output at 500 characters
197
+ by default. Correlation IDs and the delegated-tool route remain visible. This sanitizer
198
+ keeps its existing policy; the telemetry redactor additionally masks PII.
199
+
200
+ `redactSecrets` and `redactSecretsWithCounts` cover the core, CLI and provider rule union.
201
+ Exact secrets are literal strings (including regex metacharacters), applied longest first;
202
+ null/undefined/empty entries are ignored. Extra patterns are `{ name, regex }` entries, cloned
203
+ and made global so caller `lastIndex` state is unchanged. `SECRET_SHAPE_PATTERNS` exports
204
+ the eleven unchanged diagnostics vendor regexes; diagnostics retains its secret-only policy.
205
+ Core's full redactor is conservative and can mask long ordinary identifiers as opaque tokens.
206
+
207
+ `timingSafeTokenMatch({ presented, expected, timingSafeEqual })` encodes UTF-8, rejects unequal
208
+ byte lengths, and calls the required native byte comparator with `{ left, right }`.
209
+ Node hosts inject `({ left, right }) => crypto.timingSafeEqual(left, right)`; this keeps the
210
+ universal root free of Node imports while preserving native timing guarantees. No JavaScript
211
+ equality fallback is provided. The root does not expose `authorizeToolInvocation`; that gate
212
+ and the pack binding derivation types live at `@jini-ai/core/composition`.
213
+
214
+ Origin classifiers implement the dev-browser LAN allow-list. They allow private addresses
215
+ for local development; use `@jini-ai/platform/net` for SSRF classification. Origin validation
216
+ uses only an injected environment snapshot and optional `Pick<Logger, 'warn'>` diagnostics.
217
+
218
+ ## Agent tool registration
219
+
220
+ The root exports `AgentToolDefinition`, `AgentToolSideEffect`, `AgentToolActorClassRule` and
221
+ the shared registration kit: catalog indexing, named input readers, schema-bearing refusals,
222
+ independent risk gates, registration assembly, risk-map merging and human-confirmed handlers.
223
+ This wiring is domain-independent. A domain may require `inputSchema` through an intersection
224
+ with `AgentToolDefinition`; it must still independently classify the effects its handlers perform.
225
+
226
+ Use `indexCatalogById({ catalog })`, `requireInputRecord({ input })`,
227
+ `requireString({ input, key })`, `optionalString({ input, key })`, and
228
+ `withSchemaOnRejection({ toolId, catalog, isShapeRejection: ({ error }) => predicate(error), fn })`.
229
+ `buildDomainRegistrations(required, { unwiredToolIds })` refuses metadata/schema drift and
230
+ unclassified or accidentally unwired tools. Domain-specific authorization decisions and denial
231
+ classes remain in the domain or host; registration policy is pass-through after those gates.
232
+
233
+ ## Pure path containment
234
+
235
+ `@jini-ai/core/primitives` exports `pathContains({ root, target }, { caseSensitive?, separator? })`.
236
+ Both paths must already be absolute; the host resolves cwd-relative paths and
237
+ symlinks. The helper performs lexical segment normalization without importing
238
+ Node or reading a working directory. Equality counts as contained. Directory
239
+ prefix siblings and traversal escapes are rejected; a legal `..name` segment is
240
+ allowed. Windows hosts pass `{ caseSensitive: false, separator: "\\\\" }`; POSIX hosts
241
+ retain the default slash separator so backslashes in directory names remain literal.
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Shared vocabulary for independently classified agent-tool catalogs.
3
+ *
4
+ * `deletes-durable-state` is a distinct member rather than a flavor of `mutates-durable-state`, and
5
+ * the distinction is load-bearing rather than cosmetic. Wiring gates compare the two
6
+ * classifications for EQUALITY, so the strength of the check is exactly the resolution of the
7
+ * vocabulary: folding a delete into `mutates-durable-state` would let a tool that removes content
8
+ * from every read path carry the same declared risk as one that edits a title, and
9
+ * the wiring gate would have nothing to object to. A separate member means a delete tool
10
+ * whose declaration drifts toward the milder classification fails the build.
11
+ *
12
+ * Narrower domain-owned unions remain assignable to this shared vocabulary. Domains may tighten
13
+ * their own catalogs without loosening the classification required by the wiring gate.
14
+ */
15
+ export type AgentToolSideEffect = "none" | "mutates-durable-state" | "deletes-durable-state" | "mints-token";
16
+ export type AgentToolActorClassRule = "confirmer-must-equal-own-delegatedBy" | "user-only" | "none";
17
+ /** Structural catalog contract. Domains may require inputSchema or tighten their own metadata. */
18
+ export interface AgentToolDefinition {
19
+ name: string;
20
+ description: string;
21
+ sideEffects: AgentToolSideEffect;
22
+ authorization: {
23
+ permission: string;
24
+ orPermission?: string;
25
+ };
26
+ actorClassRule?: AgentToolActorClassRule;
27
+ inputSchema?: Readonly<Record<string, unknown>>;
28
+ }
29
+ //# sourceMappingURL=agent-tools.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=agent-tools.js.map
@@ -4,7 +4,7 @@
4
4
  * Whether a bearer-style API token gate should be enforced, and what the
5
5
  * expected token value is. Generalized from an upstream flat daemon module:
6
6
  * the origin hardcoded its host product's env-var names, now fields on
7
- * {@link ApiTokenAuthEnvConfig} — see `source-map.md` for the exact mapping.
7
+ * {@link ApiTokenAuthEnvConfig} — see `archived provenance ledger` for the exact mapping.
8
8
  */
9
9
  /** Names the env vars this port reads. */
10
10
  export interface ApiTokenAuthEnvConfig {
@@ -18,11 +18,18 @@ export interface ApiTokenAuthEnvConfig {
18
18
  * (case-insensitive, trimmed). Anything else, including `undefined`, is
19
19
  * falsy.
20
20
  */
21
- export declare function isTruthyEnvFlag(value: unknown): boolean;
21
+ export declare function isTruthyEnvFlag({ value }: {
22
+ value: unknown;
23
+ }): boolean;
24
+ /** Explicit environment snapshot; no process-global reads. */
25
+ export interface ApiTokenAuthArgs {
26
+ config: ApiTokenAuthEnvConfig;
27
+ env: Readonly<Record<string, string | undefined>>;
28
+ }
22
29
  /** Whether the API auth gate has been explicitly force-disabled. */
23
- export declare function isApiAuthDisabled(config: ApiTokenAuthEnvConfig, env?: NodeJS.ProcessEnv): boolean;
30
+ export declare function isApiAuthDisabled({ config, env }: ApiTokenAuthArgs): boolean;
24
31
  /** The configured expected token value, trimmed; `''` when unset. */
25
- export declare function apiTokenFromEnv(config: ApiTokenAuthEnvConfig, env?: NodeJS.ProcessEnv): string;
32
+ export declare function apiTokenFromEnv({ config, env }: ApiTokenAuthArgs): string;
26
33
  /** Whether the token gate should actually run: a token is configured and it hasn't been disabled. */
27
- export declare function isApiTokenMiddlewareEnabled(config: ApiTokenAuthEnvConfig, env?: NodeJS.ProcessEnv): boolean;
34
+ export declare function isApiTokenMiddlewareEnabled({ config, env }: ApiTokenAuthArgs): boolean;
28
35
  //# sourceMappingURL=api-token-auth.d.ts.map