@takk/racs 1.0.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.
Files changed (46) hide show
  1. package/CHANGELOG.md +70 -0
  2. package/LICENSE +190 -0
  3. package/NOTICE +40 -0
  4. package/README.md +381 -0
  5. package/SECURITY.md +57 -0
  6. package/dist/cli/index.js +3016 -0
  7. package/dist/cli/index.js.map +1 -0
  8. package/dist/edge/index.cjs +2000 -0
  9. package/dist/edge/index.cjs.map +1 -0
  10. package/dist/edge/index.d.cts +598 -0
  11. package/dist/edge/index.d.ts +598 -0
  12. package/dist/edge/index.js +1987 -0
  13. package/dist/edge/index.js.map +1 -0
  14. package/dist/index.cjs +2071 -0
  15. package/dist/index.cjs.map +1 -0
  16. package/dist/index.d.cts +39 -0
  17. package/dist/index.d.ts +39 -0
  18. package/dist/index.js +2057 -0
  19. package/dist/index.js.map +1 -0
  20. package/dist/integrations/index.cjs +123 -0
  21. package/dist/integrations/index.cjs.map +1 -0
  22. package/dist/integrations/index.d.cts +285 -0
  23. package/dist/integrations/index.d.ts +285 -0
  24. package/dist/integrations/index.js +117 -0
  25. package/dist/integrations/index.js.map +1 -0
  26. package/dist/otel/index.cjs +93 -0
  27. package/dist/otel/index.cjs.map +1 -0
  28. package/dist/otel/index.d.cts +105 -0
  29. package/dist/otel/index.d.ts +105 -0
  30. package/dist/otel/index.js +91 -0
  31. package/dist/otel/index.js.map +1 -0
  32. package/dist/types-DQ7-9sk3.d.cts +758 -0
  33. package/dist/types-DQ7-9sk3.d.ts +758 -0
  34. package/dist/vercel/index.cjs +209 -0
  35. package/dist/vercel/index.cjs.map +1 -0
  36. package/dist/vercel/index.d.cts +210 -0
  37. package/dist/vercel/index.d.ts +210 -0
  38. package/dist/vercel/index.js +206 -0
  39. package/dist/vercel/index.js.map +1 -0
  40. package/dist/web/index.cjs +2000 -0
  41. package/dist/web/index.cjs.map +1 -0
  42. package/dist/web/index.d.cts +2 -0
  43. package/dist/web/index.d.ts +2 -0
  44. package/dist/web/index.js +1987 -0
  45. package/dist/web/index.js.map +1 -0
  46. package/package.json +189 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,70 @@
1
+ # Changelog
2
+
3
+ All notable changes to `@takk/racs` are documented in this file.
4
+
5
+ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). Every entry carries a UTC timestamp.
6
+
7
+ ## [1.0.0] - 2026-06-12T04:35:39Z
8
+
9
+ Initial stable release. RACS (Remote Agent Context Store): provider-faithful prefix-cache planning, linting, scheduling, drift detection, persistence, and savings analytics for Massive Intelligence (IM) agent workloads, without ever calling a provider API. Zero runtime dependencies. 187 tests across 13 suites on Node 22 and Node 24.
10
+
11
+ ### Added
12
+
13
+ #### Engine core (`@takk/racs`)
14
+
15
+ - `createRACS(options)` factory returning the full engine surface: `plan`, `lint`, `record`, `stats`, `schedule`, `markRefreshed`, `drifts`, `invalidate`, `profileOf`, `on`, `flush`, `close`.
16
+ - Product invariant enforced throughout: no provider network calls, no credentials, no global randomness; deterministic plan ids from a seeded counter (`seed`, default 7) and an injectable clock.
17
+ - `PrefixAnalyzer` with nine lint codes: `volatile-early`, `below-minimum`, `unstable-tools`, `timestamp-in-stable`, `identifier-in-stable`, `breakpoint-after-volatile`, `write-premium-trap`, `segment-order`, `missing-stability`. Content heuristics use bounded regex classes (ISO-8601, unix epoch, relative-time-near-digits, UUID v4, hex runs, filtered base64 runs) and never embed matched substrings in findings.
18
+ - `Planner` mapping analyzed prompts onto four adapter families: explicit `breakpoint` markers with role-weighted span selection and TTL tier choice, `routing-key` directives with optional 24h retention, `resource` lifecycle directives (`create`/`reuse`/`refresh`/`delete`) with storage-trap protection, and reasoned `none` for passive providers.
19
+ - Forced deepest-marker coverage on breakpoint plans: the deepest stable boundary always takes a marker because the last marker determines left-anchored coverage, remaining slots fill in role-weight order, and coverage plus economics are accounted cumulatively to that forced deepest marker, so the reasoning states exactly how many prompt tokens the markers cover and the premium is priced on the covered tokens, never on a flattering subset.
20
+ - Break-even economics on every breakpoint and resource plan: write-premium tokens, minimum reuses to profit, profitability against the declared reuse pattern, with a human-readable derivation. The reuse model is refresh-on-use: cache reads refresh the provider TTL window at no extra cost, so steady reuse inside the window keeps a single write alive indefinitely, reuse past the widest window is priced with explicit keep-warm touch costs, and a plan that cannot repay its write is declined with a reasoned `none` plus the `write-premium-trap` finding, so an emitted breakpoint plan is never knowingly unprofitable.
21
+ - Deterministic prefix keys: FNV-1a 64 over UTF-16 code units, fused with provider, model, and agent lineage through a separator-safe `combineKeys`. Hash-only privacy mode: segments keyed by caller-supplied `contentHash`, content never required.
22
+ - Prefix drift detection (`Fingerprints`): per-lineage stable-and-semi fingerprints, changed-segment naming, invalidated-token quantification, a 200-entry drift ring, `prefix.drifted` telemetry.
23
+ - TTL keep-warm scheduling (`TtlKeeper`): refresh touches at 90 percent of the TTL window, shortest-TTL-wins on multi-directive plans, `schedule`/`markRefreshed` round trip, `refresh.due` telemetry.
24
+ - Usage ledger (`Ledger`): normalized hit ratio (`reads / (reads + writes + uncached)`) under the all-in accounting convention, `CacheUsage.inputTokens` is the all-in billed input including cached reads and cache writes of both TTL tiers, and the uncached remainder subtracts all three, so one workload reports one identical hit ratio whether usage arrives ledger-direct, through OTel span ingestion, through the Vercel AI SDK middleware, or through simulate accounting (cross-entry-point equality, probed to 1e-9). USD savings and net figures from a user-supplied `PricingTable` (prices are never hardcoded), per-prefix breakdown, bounded LRU with `limit.reached` telemetry.
25
+ - `invalidate({ prefixKey?, provider? })`: clears fingerprints, keep-warm schedules, and resource registry entries; emits a `resource.action` delete per dropped resource for the host to mirror; built for credential rotation; ledger and drift history deliberately untouched.
26
+ - 16 provider profiles over the 4 families: `anthropic`, `bedrock`, `hermes`, `microsoft-foundry` (breakpoint; `cache_control` or `cachePoint`, 4 breakpoints, 5m and 1h TTLs, 1.25x and 2x write premiums, 0.1x reads, and the 1024-token Anthropic minimum on every breakpoint profile, hermes included, so a below-minimum prefix plans to a reasoned `none` instead of a write the provider would silently ignore); `openai`, `xai`, `mistral`, `moonshot`, `openrouter` (routing-key; `prompt_cache_key` style stickiness, optional 24h retention); `google` (resource; `cachedContent` lifecycle with per-token-hour storage economics); `groq`, `deepseek`, `ollama`, `lmstudio`, `huggingface`, `custom` (passive; analytics only). Every number overridable per engine through `options.profiles`.
27
+ - Telemetry: `plan.created`, `prefix.drifted`, `usage.recorded`, `refresh.due`, `resource.action`, `limit.reached`; synchronous fan-out, listener exceptions contained.
28
+ - `RacsError` with stable machine-readable codes: `ERR_INVALID_INPUT`, `ERR_STATE_LOAD`, `ERR_STATE_VERSION`.
29
+
30
+ #### State backends
31
+
32
+ - `memoryState()` (default posture), `fileState({ path })` (Node-only, atomic JSON snapshot), and `kvState(kv, key?)` wrapping any Redis, Upstash, or Cloudflare KV client in one line through the structural `KvLike` interface.
33
+ - Snapshots carry hashes and aggregates only, never prompt content; version-validated (`version: 1`) and restored section by section, a corrupt section degrades to empty instead of crashing the engine.
34
+
35
+ #### `@takk/racs/otel`
36
+
37
+ - `usageFromSpan(span, fallback?)`: structural ingestion of finished OpenTelemetry GenAI spans into normalized `CacheUsage`, tolerating the Anthropic-flavored, OpenLLMetry, and draft semantic-convention attribute spellings, plus OTLP JSON int64 strings. Reads token counters and identity only, never prompt or completion attributes.
38
+
39
+ #### `@takk/racs/vercel`
40
+
41
+ - `racsMiddleware(racs, options)`: Vercel AI SDK middleware (structurally `LanguageModelV3Middleware`) that plans per call, applies directives via `providerOptions`, and records usage from both `wrapGenerate` and `wrapStream` (stream teed, parts untouched, finish-part usage recorded on flush).
42
+ - `defaultSegmenter` mapping the conventional call anatomy onto segments, fully replaceable through `options.segmenter`.
43
+
44
+ #### `@takk/racs/integrations`
45
+
46
+ - `noeticosBridge`: freezes parameter tuning on prefix drift, releases after 3 stable plans; plus `noeticosAdapter` folding the published module surface into the structural shape.
47
+ - `behavioralaiBridge`: turns the cache into a behaviorally observed agent, one synthetic turn per recorded usage, keys and counts only.
48
+ - `modelchainBridge`: per-routed-model cache planning.
49
+ - `keymeshBridge`: provider-scoped invalidation on credential rotation and opened circuits.
50
+ - All bridges are structural; siblings remain optional peer dependencies and are never imported at runtime.
51
+
52
+ #### `@takk/racs/web` and `@takk/racs/edge`
53
+
54
+ - Full engine surface without the Node-only file backend; no `node:` imports in either graph; runs in browsers, Cloudflare Workers, and other edge runtimes.
55
+
56
+ #### CLI `racs`
57
+
58
+ - `help` (first line `racs 1.0.0`, a tested CI contract), `version`, `analyze` (PlanInput lint-and-plan gate, exit 1 on error findings), `simulate` (deterministic structured-versus-naive demonstration, byte-identical output per flag set), `inspect` (snapshot rendering with optional `--watch`), and `serve`.
59
+ - `racs serve`: hardened local HTTP bridge with `/healthz`, `/plan`, `/lint`, `/usage`, `/stats`, `/schedule`, `/refreshed`, `/invalidate`; loopback by default, constant-time bearer auth, and Host-header validation on tokenless instances: any request whose Host header is not a loopback name (`localhost`, `127.0.0.1`, `::1`, port stripped, IPv6 brackets tolerated) is answered 403 `forbidden host`, closing the DNS-rebinding vector, `/healthz` included; with `--token` the bearer is the gate and the Host header is not consulted. Plus 415/413 body gates, CORS only when token and origin are both configured, graceful signal shutdown with state flush.
60
+
61
+ #### Documentation
62
+
63
+ - "Caching MCP tool descriptions" section in the README: the serialized `tools/list` response of an MCP server becomes one stable `'tools'` segment, the role with the highest breakpoint placement weight, with deterministic-serialization guidance backed by the `unstable-tools` lint. Runnable companion example [examples/mcp-tools-segment.ts](./examples/mcp-tools-segment.ts), structural on purpose, no MCP SDK import.
64
+
65
+ #### Quality contract
66
+
67
+ - Planning benchmark P1-P10 pinning breakpoint fidelity, the volatile-early trap, minimum boundaries, TTL economics, routing-key stability, the resource lifecycle, ledger exactness, drift precision, cross-engine determinism, and simulate parity.
68
+ - SemVer extensibility clauses (SPEC section 11): `ProviderId`, `LintCode`, `TelemetryEvent`, `SegmentRole`, `RacsError.code`, `CacheDirective` kinds, `CacheTtl` tiers, the retention literal union, and the resource lifecycle action union are declared minor-extensible; consumers treat them as open unions and carry a default arm on exhaustive switches.
69
+ - 187 tests across 13 suites; coverage 92.46 percent statements, 82.09 branches, 93.33 functions, 92.49 lines.
70
+ - Brotli budgets enforced in CI: core 10.72 kB ESM / 10.86 kB CJS, `/otel` 604 B, `/vercel` 1.15 kB, `/integrations` 666 B, `/web` 10.23 kB, `/edge` 10.23 kB. Published tarball: 46 files.
package/LICENSE ADDED
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for describing the origin of the Work and
141
+ reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may accept and charge a
167
+ fee for the 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 own
170
+ behalf and on Your sole responsibility, not on behalf of any other
171
+ Contributor, and only if You agree to indemnify, defend, and hold
172
+ each Contributor harmless for any liability incurred by, or claims
173
+ asserted against, such Contributor by reason of your accepting any
174
+ such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2026 David C Cavalcante
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,40 @@
1
+ @takk/racs
2
+ Copyright 2026 David C Cavalcante / Takk Innovate Studio
3
+
4
+ This product includes software developed by David C Cavalcante
5
+ (https://takk.ag - davcavalcante@proton.me / say@takk.ag).
6
+
7
+ RACS (Remote Agent Context Store) is a universal, zero-runtime-dependency
8
+ library and CLI for provider-faithful prefix-cache management: stability
9
+ linting, multi-provider directive planning, deterministic prefix keys,
10
+ TTL keep-warm scheduling, drift detection, persistence, and hit-ratio and
11
+ savings analytics. It never calls a provider API.
12
+
13
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not
14
+ use the software in this repository except in compliance with the License.
15
+ A copy of the License is in the LICENSE file at the root of this repository,
16
+ and is also available at:
17
+
18
+ http://www.apache.org/licenses/LICENSE-2.0
19
+
20
+ ----------------------------------------------------------------------------
21
+ THIRD-PARTY COMPONENTS
22
+ ----------------------------------------------------------------------------
23
+
24
+ RACS has ZERO runtime dependencies. The published package contains no
25
+ third-party code. The @takk sibling packages (@takk/noeticos,
26
+ @takk/behavioralai, @takk/modelchain, @takk/keymesh) are OPTIONAL peer
27
+ dependencies bridged through local structural interfaces; none of them is
28
+ imported at runtime, and each is distributed under its own license by the
29
+ same author.
30
+
31
+ Development-only tooling (NOT shipped in the published package):
32
+
33
+ - tsup - MIT
34
+ - vitest - MIT
35
+ - typescript - Apache-2.0
36
+ - @biomejs/biome - MIT OR Apache-2.0
37
+ - publint - MIT
38
+ - @arethetypeswrong/cli - MIT
39
+ - size-limit - MIT
40
+ - tsx - MIT