@kindgi/bounds 0.0.0-stage → 0.1.8

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 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 Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Kindgi Inc.
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
@@ -1,3 +1,111 @@
1
- # Temporary Holding Version
1
+ # @kindgi/bounds
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The limits a Kindgi server puts on what a tenant sends it, so that one
4
+ tenant's input can't stall the server for the others:
5
+
6
+ - **patterns:** their length, the engine they run on (V8's, or RE2's,
7
+ which runs in linear time, so no pattern can take exponential time), and
8
+ how many citations a `must-cite` guardrail may ask for;
9
+ - **schemas:** their size and nesting depth before they're compiled, how
10
+ many compiled ones are kept and how much JSON they add up to, and how
11
+ long a tenant's schemas may spend compiling in any 60 seconds;
12
+ - **templates:** liquidjs's parse, render-time and memory limits;
13
+ - **bodies** read from endpoints a tenant names: their size, decompressed,
14
+ and the idle time between chunks (per event for `text/event-stream`);
15
+ - **request bodies** the API reads: their size and JSON nesting depth.
16
+
17
+ The process sets its bounds once, at boot. The Kindgi runtime sets
18
+ `HOSTED_BOUNDS` under its hosted profile; anywhere else it's
19
+ `SELF_HOSTED_BOUNDS`, today's behaviour with generous caps. A second call
20
+ throws.
21
+
22
+ ```ts
23
+ import { HOSTED_BOUNDS, configureTenantInputBounds, tenantInputBounds } from '@kindgi/bounds';
24
+
25
+ configureTenantInputBounds(HOSTED_BOUNDS); // once, at boot
26
+ tenantInputBounds().schemaMaxBytes; // what the helpers read
27
+ ```
28
+
29
+ Tests run with other bounds through `@kindgi/bounds/testing`'s
30
+ `overrideTenantInputBounds`, which returns the function that puts them back.
31
+
32
+ ## Whose work it is
33
+
34
+ A budget kept per tenant (`schemaCompileBudgetMs`) charges the tenant
35
+ whose work is running. The server runs each request and each run inside
36
+ `runAsTenant(tenantId, fn)`; `currentTenant()` reads it. The scope follows
37
+ `fn`'s own awaits and callbacks (an `AsyncLocalStorage` context), never
38
+ another request's. Outside any scope, at boot or in Kindgi's own work,
39
+ nothing is charged.
40
+
41
+ Which compiles count is the scope's `compiles`:
42
+
43
+ - `recompiles`, the default: a schema compiled again after the cache
44
+ dropped it. The first compile of a schema the tenant published doesn't
45
+ count, so a restarted server compiles each tenant's schemas freely.
46
+ Once a tenant has compiled 4,096 different schemas in the process, every
47
+ compile counts.
48
+ - `all`: every compile, the first included. A request that publishes,
49
+ deploys or registers schemas runs this way, since that's where new
50
+ schemas come from.
51
+
52
+ ```ts
53
+ import { runAsTenant } from '@kindgi/bounds';
54
+
55
+ await runAsTenant(tenantId, () => handle(request));
56
+ await runAsTenant(tenantId, () => publish(request), { compiles: 'all' });
57
+ ```
58
+
59
+ ## Patterns
60
+
61
+ `compileTenantPattern(source, flags)` compiles a pattern a tenant wrote, a
62
+ JavaScript regular expression's source and flags, under the process's
63
+ bounds. It answers `{ kind: 'ok', pattern }`, whose `test(input)` and
64
+ `count(input, atMost)` give the answers of the `RegExp` it was written as
65
+ (on RE2, but for the differences below), or `{ kind: 'refused', reason }`,
66
+ saying why.
67
+
68
+ ```ts
69
+ import { compileTenantPattern } from '@kindgi/bounds';
70
+
71
+ const compiled = compileTenantPattern(config.pattern, config.flags);
72
+ if (compiled.kind === 'refused') throw new Error(`config.pattern: ${compiled.reason}`);
73
+ compiled.pattern.test(output);
74
+ compiled.pattern.count(output, 3); // stops at 3
75
+ ```
76
+
77
+ With `SELF_HOSTED_BOUNDS` a pattern runs on V8's engine, as `new RegExp`
78
+ does, up to 8,192 characters with its flags. With `HOSTED_BOUNDS` it runs on
79
+ [RE2](https://github.com/google/re2/wiki/Syntax) (the
80
+ [re2js](https://www.npmjs.com/package/re2js) port), in time linear in its
81
+ input, up to 1,024 characters. On RE2:
82
+
83
+ - **Only what `RegExp` accepts:** a pattern V8 refuses is refused in V8's
84
+ words, even where RE2 would compile it (`(?i)`, `(?P<n>…)`, or with `u`,
85
+ `\pL` and `\x{41}`).
86
+ - **Refused, by name:**
87
+ - what RE2 doesn't have: backreferences (`\1`, `\k<name>`), lookahead and
88
+ lookbehind (`(?=`, `(?!`, `(?<=`, `(?<!`), and `\u` escapes (write the
89
+ character itself);
90
+ - what RE2 would silently read otherwise: `[]` and `[^]` (the start of a
91
+ class to RE2), `[:` in a class (a POSIX class to RE2) and, without the
92
+ `u` flag, `\p`, `\P`, `\A`, `\z`, `\Q`, `\a` and `\x{`, in a class or
93
+ out, which JavaScript reads as the letter itself.
94
+ - **Refused in RE2's words:** anything else RE2 can't compile, such as a
95
+ repeat count over 1,000.
96
+ - **Flags:** `i`, `m`, `s` and `u` map to RE2's own; `y` anchors at the
97
+ start; `g` and `d` change no answer; `v` is refused.
98
+ - **Read differently, for every pattern:**
99
+ - RE2 always matches by code point and folds case as the `u` flag does: `.`
100
+ matches an emoji, and `/ſ/i` matches `s`;
101
+ - `.` stops only at `\n`, not at `\r`, `\u2028` or `\u2029`, and with `m`, `^`
102
+ and `$` match only around `\n`;
103
+ - `\s` is ASCII whitespace (`\t`, `\n`, `\f`, `\r` and space).
104
+ - **Counting:** every match of a pattern like `x.*y|x` can read to the end of
105
+ the input, so counting them all is quadratic. `count(input, atMost)` scans
106
+ at most `atMost` matches, each linear in the input, so it costs up to
107
+ `atMost` × the input. A `must-cite` guardrail asks for its `minCitations`, at
108
+ most `mustCiteMaxCitations`: 100 with `HOSTED_BOUNDS`, no cap with
109
+ `SELF_HOSTED_BOUNDS`.
110
+
111
+ Apache-2.0.
@@ -0,0 +1,111 @@
1
+ /**
2
+ * The limits a Kindgi server puts on what a tenant sends it: one setting
3
+ * for the whole process, set once at boot (`configureTenantInputBounds`)
4
+ * and read where tenant input is compiled or read (`tenantInputBounds`).
5
+ *
6
+ * The runtime sets {@link HOSTED_BOUNDS} under the hosted profile, where
7
+ * one tenant's input must never stall the server for the others. Anywhere
8
+ * else (a self-hosted server, a pack's own process, a test) it's
9
+ * {@link SELF_HOSTED_BOUNDS}: today's behaviour, with generous limits on
10
+ * bodies, schemas and a render's memory.
11
+ *
12
+ * Why one setting rather than an argument: the places that compile tenant
13
+ * input are deep inside the SDK's packages (guardrails, schema, agents,
14
+ * flow, tools). One explicit call at boot is testable, and a second call
15
+ * throwing keeps it from changing while the server runs. Why not the
16
+ * environment: a library that reads `process.env` behaves differently in a
17
+ * test than in the server.
18
+ */
19
+ export interface TenantInputBounds {
20
+ /**
21
+ * The engine a tenant's pattern runs on: V8's, or RE2's, which runs in
22
+ * linear time. On RE2, a tenant's JSON Schema checks its data in linear
23
+ * time too (`@kindgi/schema`): its patterns run on RE2, its formats are
24
+ * ajv-formats' `fast` ones, and `uniqueItems` compares items by a key.
25
+ */
26
+ readonly regex: 'v8' | 're2';
27
+ /** The longest a tenant's pattern may be: its source plus its flags, in characters. */
28
+ readonly patternMaxLength: number;
29
+ /**
30
+ * The most citations a `must-cite` guardrail may require (`minCitations`).
31
+ * It counts matches up to that many, and on RE2 each match can read the
32
+ * rest of the output, so this caps what one evaluation costs.
33
+ */
34
+ readonly mustCiteMaxCitations: number;
35
+ /** The largest schema compiled: its JSON, in bytes, before it's compiled. */
36
+ readonly schemaMaxBytes: number;
37
+ /** The deepest a schema may nest, objects and arrays. */
38
+ readonly schemaMaxDepth: number;
39
+ /** Compiled schemas kept, by their JSON, the least recently used dropped first. */
40
+ readonly schemaCacheEntries: number;
41
+ /**
42
+ * The most schema JSON those compiled schemas may add up to, in bytes: a
43
+ * compiled schema takes 4 to 15 times its JSON in memory for real API
44
+ * schemas, and up to about 20 times for the worst shapes measured.
45
+ */
46
+ readonly schemaCacheMaxBytes: number;
47
+ /**
48
+ * The time a tenant's schemas may spend compiling in any 60 seconds, in
49
+ * milliseconds: the compiles that count (`runAsTenant` says whose work
50
+ * it is, and which count). Past it, the tenant's next compile that
51
+ * counts is refused until the window moves on; schemas already compiled
52
+ * keep working.
53
+ */
54
+ readonly schemaCompileBudgetMs: number;
55
+ /**
56
+ * The time a tenant's templates may spend rendering in any 60 seconds,
57
+ * in milliseconds, for renders done as its work (`runAsTenant`). Past it,
58
+ * the tenant's next render is refused until the window moves on. A
59
+ * render holds the event loop while it runs.
60
+ */
61
+ readonly templateRenderBudgetMs: number;
62
+ /** A template's limits (liquidjs's own). */
63
+ readonly liquid: {
64
+ /** The longest template parsed, in characters. */
65
+ readonly parseLimit: number;
66
+ /** The longest one render may take, in milliseconds. */
67
+ readonly renderLimitMs: number;
68
+ /**
69
+ * The most one render may allocate, in liquidjs's own units (roughly
70
+ * characters of strings and arrays it builds), not bytes: 8,388,608 is
71
+ * not 8 MiB, and isn't meant to be.
72
+ */
73
+ readonly memoryLimit: number;
74
+ };
75
+ /** The largest body read from a tenant-named endpoint, decompressed, in bytes. */
76
+ readonly responseMaxBytes: number;
77
+ /** The longest wait between two chunks of such a body, in milliseconds. */
78
+ readonly responseIdleMs: number;
79
+ /** The largest one event of a `text/event-stream` may be; the stream itself has no total. */
80
+ readonly sseEventMaxBytes: number;
81
+ /** The largest request body the API reads, in bytes (routes that take more set their own). */
82
+ readonly requestMaxBytes: number;
83
+ /**
84
+ * The deepest a request's JSON may nest, in levels of objects and arrays,
85
+ * the body's own being 1. It leaves room for a schema as deep as
86
+ * `schemaMaxDepth` inside the body that carries it.
87
+ */
88
+ readonly requestJsonMaxDepth: number;
89
+ }
90
+ /**
91
+ * Anywhere but the hosted profile: today's behaviour. A pattern on V8's
92
+ * engine, a template's length and render time, and idle time without
93
+ * limits; caps where today has none that a self-hoster could still hurt
94
+ * itself without (bodies, schemas, the compile cache, a render's memory).
95
+ */
96
+ export declare const SELF_HOSTED_BOUNDS: TenantInputBounds;
97
+ /** The hosted profile: patterns on RE2 (linear time), and tight limits. */
98
+ export declare const HOSTED_BOUNDS: TenantInputBounds;
99
+ /**
100
+ * Sets the process's bounds, once, at boot. A second call throws: they
101
+ * never change while the server runs.
102
+ */
103
+ export declare function configureTenantInputBounds(bounds: TenantInputBounds): void;
104
+ /** The process's bounds: what boot set, or {@link SELF_HOSTED_BOUNDS}. */
105
+ export declare function tenantInputBounds(): TenantInputBounds;
106
+ /**
107
+ * For tests (`@kindgi/bounds/testing`): runs with other bounds, and puts
108
+ * back what was set.
109
+ */
110
+ export declare function overrideTenantInputBounds(bounds: TenantInputBounds): () => void;
111
+ //# sourceMappingURL=bounds.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bounds.d.ts","sourceRoot":"","sources":["../src/bounds.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,WAAW,iBAAiB;IAChC;;;;;OAKG;IACH,QAAQ,CAAC,KAAK,EAAE,IAAI,GAAG,KAAK,CAAC;IAC7B,uFAAuF;IACvF,QAAQ,CAAC,gBAAgB,EAAE,MAAM,CAAC;IAClC;;;;OAIG;IACH,QAAQ,CAAC,oBAAoB,EAAE,MAAM,CAAC;IACtC,6EAA6E;IAC7E,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAChC,yDAAyD;IACzD,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAChC,mFAAmF;IACnF,QAAQ,CAAC,kBAAkB,EAAE,MAAM,CAAC;IACpC;;;;OAIG;IACH,QAAQ,CAAC,mBAAmB,EAAE,MAAM,CAAC;IACrC;;;;;;OAMG;IACH,QAAQ,CAAC,qBAAqB,EAAE,MAAM,CAAC;IACvC;;;;;OAKG;IACH,QAAQ,CAAC,sBAAsB,EAAE,MAAM,CAAC;IACxC,4CAA4C;IAC5C,QAAQ,CAAC,MAAM,EAAE;QACf,kDAAkD;QAClD,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;QAC5B,wDAAwD;QACxD,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;QAC/B;;;;WAIG;QACH,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;KAC9B,CAAC;IACF,kFAAkF;IAClF,QAAQ,CAAC,gBAAgB,EAAE,MAAM,CAAC;IAClC,2EAA2E;IAC3E,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAChC,6FAA6F;IAC7F,QAAQ,CAAC,gBAAgB,EAAE,MAAM,CAAC;IAClC,8FAA8F;IAC9F,QAAQ,CAAC,eAAe,EAAE,MAAM,CAAC;IACjC;;;;OAIG;IACH,QAAQ,CAAC,mBAAmB,EAAE,MAAM,CAAC;CACtC;AAcD;;;;;GAKG;AACH,eAAO,MAAM,kBAAkB,EAAE,iBAoB/B,CAAC;AAEH,2EAA2E;AAC3E,eAAO,MAAM,aAAa,EAAE,iBAoB1B,CAAC;AAIH;;;GAGG;AACH,wBAAgB,0BAA0B,CAAC,MAAM,EAAE,iBAAiB,GAAG,IAAI,CAK1E;AAED,0EAA0E;AAC1E,wBAAgB,iBAAiB,IAAI,iBAAiB,CAErD;AAED;;;GAGG;AACH,wBAAgB,yBAAyB,CAAC,MAAM,EAAE,iBAAiB,GAAG,MAAM,IAAI,CAM/E"}
package/dist/bounds.js ADDED
@@ -0,0 +1,95 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Copyright (C) 2026 Kindgi Inc.
3
+ const KiB = 1024;
4
+ const MiB = 1024 * KiB;
5
+ /*
6
+ * The numbers: fitted to limits the code already enforces (a pack
7
+ * service's body and an HTTP tool's response 10 MiB, a webhook body
8
+ * 256 KiB, MCP sign-in 64 KiB), until hosted usage tunes them. The
9
+ * compile cache's bytes and the compile budget are measured: a 256 KiB
10
+ * schema compiles to 4–5 MiB of heap in up to 0.75 s, and a 100 KiB one
11
+ * derived from a public OpenAPI document in 0.1–0.2 s.
12
+ */
13
+ /**
14
+ * Anywhere but the hosted profile: today's behaviour. A pattern on V8's
15
+ * engine, a template's length and render time, and idle time without
16
+ * limits; caps where today has none that a self-hoster could still hurt
17
+ * itself without (bodies, schemas, the compile cache, a render's memory).
18
+ */
19
+ export const SELF_HOSTED_BOUNDS = deepFreeze({
20
+ regex: 'v8',
21
+ patternMaxLength: 8_192,
22
+ mustCiteMaxCitations: Number.POSITIVE_INFINITY,
23
+ schemaMaxBytes: 1 * MiB,
24
+ schemaMaxDepth: 64,
25
+ schemaCacheEntries: 1_000,
26
+ schemaCacheMaxBytes: Number.POSITIVE_INFINITY,
27
+ schemaCompileBudgetMs: Number.POSITIVE_INFINITY,
28
+ templateRenderBudgetMs: Number.POSITIVE_INFINITY,
29
+ liquid: {
30
+ parseLimit: Number.POSITIVE_INFINITY,
31
+ renderLimitMs: Number.POSITIVE_INFINITY,
32
+ memoryLimit: 16_777_216,
33
+ },
34
+ responseMaxBytes: 10 * MiB,
35
+ responseIdleMs: Number.POSITIVE_INFINITY,
36
+ sseEventMaxBytes: 10 * MiB,
37
+ requestMaxBytes: 10 * MiB,
38
+ requestJsonMaxDepth: 128,
39
+ });
40
+ /** The hosted profile: patterns on RE2 (linear time), and tight limits. */
41
+ export const HOSTED_BOUNDS = deepFreeze({
42
+ regex: 're2',
43
+ patternMaxLength: 1_024,
44
+ mustCiteMaxCitations: 100,
45
+ schemaMaxBytes: 256 * KiB,
46
+ schemaMaxDepth: 64,
47
+ schemaCacheEntries: 512,
48
+ schemaCacheMaxBytes: 8 * MiB,
49
+ schemaCompileBudgetMs: 2_000,
50
+ templateRenderBudgetMs: 5_000,
51
+ liquid: {
52
+ parseLimit: 262_144,
53
+ renderLimitMs: 1_000,
54
+ memoryLimit: 8_388_608,
55
+ },
56
+ responseMaxBytes: 10 * MiB,
57
+ responseIdleMs: 60_000,
58
+ sseEventMaxBytes: 10 * MiB,
59
+ requestMaxBytes: 2 * MiB,
60
+ requestJsonMaxDepth: 128,
61
+ });
62
+ let configured;
63
+ /**
64
+ * Sets the process's bounds, once, at boot. A second call throws: they
65
+ * never change while the server runs.
66
+ */
67
+ export function configureTenantInputBounds(bounds) {
68
+ if (configured !== undefined) {
69
+ throw new Error('Tenant input bounds are already set: they are set once, at boot.');
70
+ }
71
+ configured = deepFreeze(structuredClone(bounds));
72
+ }
73
+ /** The process's bounds: what boot set, or {@link SELF_HOSTED_BOUNDS}. */
74
+ export function tenantInputBounds() {
75
+ return configured ?? SELF_HOSTED_BOUNDS;
76
+ }
77
+ /**
78
+ * For tests (`@kindgi/bounds/testing`): runs with other bounds, and puts
79
+ * back what was set.
80
+ */
81
+ export function overrideTenantInputBounds(bounds) {
82
+ const before = configured;
83
+ configured = deepFreeze(structuredClone(bounds));
84
+ return () => {
85
+ configured = before;
86
+ };
87
+ }
88
+ function deepFreeze(value) {
89
+ for (const inner of Object.values(value)) {
90
+ if (inner !== null && typeof inner === 'object')
91
+ deepFreeze(inner);
92
+ }
93
+ return Object.freeze(value);
94
+ }
95
+ //# sourceMappingURL=bounds.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bounds.js","sourceRoot":"","sources":["../src/bounds.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,iCAAiC;AA4FjC,MAAM,GAAG,GAAG,IAAI,CAAC;AACjB,MAAM,GAAG,GAAG,IAAI,GAAG,GAAG,CAAC;AAEvB;;;;;;;GAOG;AAEH;;;;;GAKG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAsB,UAAU,CAAC;IAC9D,KAAK,EAAE,IAAI;IACX,gBAAgB,EAAE,KAAK;IACvB,oBAAoB,EAAE,MAAM,CAAC,iBAAiB;IAC9C,cAAc,EAAE,CAAC,GAAG,GAAG;IACvB,cAAc,EAAE,EAAE;IAClB,kBAAkB,EAAE,KAAK;IACzB,mBAAmB,EAAE,MAAM,CAAC,iBAAiB;IAC7C,qBAAqB,EAAE,MAAM,CAAC,iBAAiB;IAC/C,sBAAsB,EAAE,MAAM,CAAC,iBAAiB;IAChD,MAAM,EAAE;QACN,UAAU,EAAE,MAAM,CAAC,iBAAiB;QACpC,aAAa,EAAE,MAAM,CAAC,iBAAiB;QACvC,WAAW,EAAE,UAAU;KACxB;IACD,gBAAgB,EAAE,EAAE,GAAG,GAAG;IAC1B,cAAc,EAAE,MAAM,CAAC,iBAAiB;IACxC,gBAAgB,EAAE,EAAE,GAAG,GAAG;IAC1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AAM,CAAC;IACtB,CAAC,CAAC;AACJ,CAAC;AAED,SAAS,UAAU,CAAmB,KAAQ;IAC5C,KAAK,MAAM,KAAK,IAAI,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC;QACzC,IAAI,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ;YAAE,UAAU,CAAC,KAAK,CAAC,CAAC;IACrE,CAAC;IACD,OAAO,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAC9B,CAAC"}
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Budgets kept per tenant: the time a tenant's work of one kind (its
3
+ * schema compiles, its template renders) takes in any 60 seconds. That
4
+ * work holds the event loop while it runs, so a tenant past its budget
5
+ * waits instead of the others: its next piece of that work is refused
6
+ * until the window moves on, and may be retried then. The budget doesn't
7
+ * stop a piece it let start, so a tenant's minute can run past the budget
8
+ * by one piece.
9
+ */
10
+ /** The window a budget kept per tenant counts over, in milliseconds. */
11
+ export declare const BUDGET_WINDOW_MS = 60000;
12
+ /** Which budget refused: what the API's refusal names in `details.limit`. */
13
+ export type TenantBudgetLimit = 'schema-compile-time' | 'template-render-time';
14
+ /**
15
+ * A tenant's work refused: it spent its budget of `budgetMs` (`limit`) in
16
+ * the last 60 seconds, and is under it again after `retryAfterMs`. Every
17
+ * budget's refusal is one of these, so what answers for one (the API, an
18
+ * agent's turn, a run's step) answers for them all.
19
+ */
20
+ export declare class TenantBudgetError extends Error {
21
+ readonly limit: TenantBudgetLimit;
22
+ readonly budgetMs: number;
23
+ readonly retryAfterMs: number;
24
+ constructor(message: string, limit: TenantBudgetLimit, budgetMs: number, retryAfterMs: number);
25
+ }
26
+ /** Where a budget reads the time. */
27
+ export interface BudgetClock {
28
+ /** The wall time, in milliseconds: where a piece of work sits in the window. */
29
+ now(): number;
30
+ /** A monotonic time, in milliseconds: how long a piece of work took. */
31
+ monotonic(): number;
32
+ }
33
+ /** The system's clock, read when asked: `Date.now` and `performance.now`. */
34
+ export declare const SYSTEM_CLOCK: BudgetClock;
35
+ /**
36
+ * The time each tenant spent on one kind of work in the last 60 seconds,
37
+ * against `budgetMs`; `refuse` makes the error for a tenant past it. An
38
+ * infinite budget keeps no count. Charging a piece costs the same however
39
+ * many pieces the window holds.
40
+ */
41
+ export declare class TenantTimeBudget {
42
+ private readonly budgetMs;
43
+ private readonly refuse;
44
+ private readonly clock;
45
+ private readonly ledgers;
46
+ private readonly budgetUs;
47
+ private sweptAt;
48
+ constructor(budgetMs: number, refuse: (budgetMs: number, retryAfterMs: number) => TenantBudgetError, clock?: BudgetClock);
49
+ /**
50
+ * Runs `work` as `tenant`'s, and returns what it returns: refused with
51
+ * `refuse`'s error, before it starts, once the tenant has spent its
52
+ * budget. Its time is charged, a failed piece's too.
53
+ */
54
+ charge<T>(tenant: string, work: () => T): T;
55
+ /** Once a window: drops the work that left it, and the tenants with none left. */
56
+ private sweep;
57
+ /** Throws `refuse`'s error when `tenant` has spent its budget. */
58
+ private check;
59
+ /** Charges `tenant` for work started `at` that took `ms`. */
60
+ private spend;
61
+ /** Drops `ledger`'s work that left the window ending `now`; returns how many pieces are left. */
62
+ private inWindow;
63
+ private ledgerOf;
64
+ }
65
+ //# sourceMappingURL=budget.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"budget.d.ts","sourceRoot":"","sources":["../src/budget.ts"],"names":[],"mappings":"AAGA;;;;;;;;GAQG;AAEH,wEAAwE;AACxE,eAAO,MAAM,gBAAgB,QAAS,CAAC;AAEvC,6EAA6E;AAC7E,MAAM,MAAM,iBAAiB,GAAG,qBAAqB,GAAG,sBAAsB,CAAC;AAE/E;;;;;GAKG;AACH,qBAAa,iBAAkB,SAAQ,KAAK;IAGxC,QAAQ,CAAC,KAAK,EAAE,iBAAiB;IACjC,QAAQ,CAAC,QAAQ,EAAE,MAAM;IACzB,QAAQ,CAAC,YAAY,EAAE,MAAM;gBAH7B,OAAO,EAAE,MAAM,EACN,KAAK,EAAE,iBAAi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