@defai.digital/token-budget 13.0.3

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,214 @@
1
+ AutomatosX Open Source Edition - Apache License 2.0
2
+
3
+ This license applies ONLY to the AutomatosX Open Source Edition code
4
+ published on GitHub at https://github.com/defai-digital/automatosx
5
+
6
+ This license does NOT apply to:
7
+ - AutomatosX Pro Edition (proprietary software - separate EULA)
8
+ - AutomatosX Enterprise Edition (proprietary software - separate agreement)
9
+
10
+ For commercial editions, see COMMERCIAL-LICENSE.md
11
+
12
+ ===============================================================================
13
+
14
+ Apache License
15
+ Version 2.0, January 2004
16
+ http://www.apache.org/licenses/
17
+
18
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
19
+
20
+ 1. Definitions.
21
+
22
+ "License" shall mean the terms and conditions for use, reproduction,
23
+ and distribution as defined by Sections 1 through 9 of this document.
24
+
25
+ "Licensor" shall mean the copyright owner or entity authorized by
26
+ the copyright owner that is granting the License.
27
+
28
+ "Legal Entity" shall mean the union of the acting entity and all
29
+ other entities that control, are controlled by, or are under common
30
+ control with that entity. For the purposes of this definition,
31
+ "control" means (i) the power, direct or indirect, to cause the
32
+ direction or management of such entity, whether by contract or
33
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
34
+ outstanding shares, or (iii) beneficial ownership of such entity.
35
+
36
+ "You" (or "Your") shall mean an individual or Legal Entity
37
+ exercising permissions granted by this License.
38
+
39
+ "Source" form shall mean the preferred form for making modifications,
40
+ including but not limited to software source code, documentation
41
+ source, and configuration files.
42
+
43
+ "Object" form shall mean any form resulting from mechanical
44
+ transformation or translation of a Source form, including but
45
+ not limited to compiled object code, generated documentation,
46
+ and conversions to other media types.
47
+
48
+ "Work" shall mean the work of authorship, whether in Source or
49
+ Object form, made available under the License, as indicated by a
50
+ copyright notice that is included in or attached to the work
51
+ (an example is provided in the Appendix below).
52
+
53
+ "Derivative Works" shall mean any work, whether in Source or Object
54
+ form, that is based on (or derived from) the Work and for which the
55
+ editorial revisions, annotations, elaborations, or other modifications
56
+ represent, as a whole, an original work of authorship. For the purposes
57
+ of this License, Derivative Works shall not include works that remain
58
+ separable from, or merely link (or bind by name) to the interfaces of,
59
+ the Work and Derivative Works thereof.
60
+
61
+ "Contribution" shall mean any work of authorship, including
62
+ the original version of the Work and any modifications or additions
63
+ to that Work or Derivative Works thereof, that is intentionally
64
+ submitted to Licensor for inclusion in the Work by the copyright owner
65
+ or by an individual or Legal Entity authorized to submit on behalf of
66
+ the copyright owner. For the purposes of this definition, "submitted"
67
+ means any form of electronic, verbal, or written communication sent
68
+ to the Licensor or its representatives, including but not limited to
69
+ communication on electronic mailing lists, source code control systems,
70
+ and issue tracking systems that are managed by, or on behalf of, the
71
+ Licensor for the purpose of discussing and improving the Work, but
72
+ excluding communication that is conspicuously marked or otherwise
73
+ designated in writing by the copyright owner as "Not a Contribution."
74
+
75
+ "Contributor" shall mean Licensor and any individual or Legal Entity
76
+ on behalf of whom a Contribution has been received by Licensor and
77
+ subsequently incorporated within the Work.
78
+
79
+ 2. Grant of Copyright License. Subject to the terms and conditions of
80
+ this License, each Contributor hereby grants to You a perpetual,
81
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
82
+ copyright license to reproduce, prepare Derivative Works of,
83
+ publicly display, publicly perform, sublicense, and distribute the
84
+ Work and such Derivative Works in Source or Object form.
85
+
86
+ 3. Grant of Patent License. Subject to the terms and conditions of
87
+ this License, each Contributor hereby grants to You a perpetual,
88
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
89
+ (except as stated in this section) patent license to make, have made,
90
+ use, offer to sell, sell, import, and otherwise transfer the Work,
91
+ where such license applies only to those patent claims licensable
92
+ by such Contributor that are necessarily infringed by their
93
+ Contribution(s) alone or by combination of their Contribution(s)
94
+ with the Work to which such Contribution(s) was submitted. If You
95
+ institute patent litigation against any entity (including a
96
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
97
+ or a Contribution incorporated within the Work constitutes direct
98
+ or contributory patent infringement, then any patent licenses
99
+ granted to You under this License for that Work shall terminate
100
+ as of the date such litigation is filed.
101
+
102
+ 4. Redistribution. You may reproduce and distribute copies of the
103
+ Work or Derivative Works thereof in any medium, with or without
104
+ modifications, and in Source or Object form, provided that You
105
+ meet the following conditions:
106
+
107
+ (a) You must give any other recipients of the Work or
108
+ Derivative Works a copy of this License; and
109
+
110
+ (b) You must cause any modified files to carry prominent notices
111
+ stating that You changed the files; and
112
+
113
+ (c) You must retain, in the Source form of any Derivative Works
114
+ that You distribute, all copyright, patent, trademark, and
115
+ attribution notices from the Source form of the Work,
116
+ excluding those notices that do not pertain to any part of
117
+ the Derivative Works; and
118
+
119
+ (d) If the Work includes a "NOTICE" text file as part of its
120
+ distribution, then any Derivative Works that You distribute must
121
+ include a readable copy of the attribution notices contained
122
+ within such NOTICE file, excluding those notices that do not
123
+ pertain to any part of the Derivative Works, in at least one
124
+ of the following places: within a NOTICE text file distributed
125
+ as part of the Derivative Works; within the Source form or
126
+ documentation, if provided along with the Derivative Works; or,
127
+ within a display generated by the Derivative Works, if and
128
+ wherever such third-party notices normally appear. The contents
129
+ of the NOTICE file are for informational purposes only and
130
+ do not modify the License. You may add Your own attribution
131
+ notices within Derivative Works that You distribute, alongside
132
+ or as an addendum to the NOTICE text from the Work, provided
133
+ that such additional attribution notices cannot be construed
134
+ as modifying the License.
135
+
136
+ You may add Your own copyright statement to Your modifications and
137
+ may provide additional or different license terms and conditions
138
+ for use, reproduction, or distribution of Your modifications, or
139
+ for any such Derivative Works as a whole, provided Your use,
140
+ reproduction, and distribution of the Work otherwise complies with
141
+ the conditions stated in this License.
142
+
143
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
144
+ any Contribution intentionally submitted for inclusion in the Work
145
+ by You to the Licensor shall be under the terms and conditions of
146
+ this License, without any additional terms or conditions.
147
+ Notwithstanding the above, nothing herein shall supersede or modify
148
+ the terms of any separate license agreement you may have executed
149
+ with Licensor regarding such Contributions.
150
+
151
+ 6. Trademarks. This License does not grant permission to use the trade
152
+ names, trademarks, service marks, or product names of the Licensor,
153
+ except as required for reasonable and customary use in describing the
154
+ origin of the Work and reproducing the content of the NOTICE file.
155
+
156
+ 7. Disclaimer of Warranty. Unless required by applicable law or
157
+ agreed to in writing, Licensor provides the Work (and each
158
+ Contributor provides its Contributions) on an "AS IS" BASIS,
159
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
160
+ implied, including, without limitation, any warranties or conditions
161
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
162
+ PARTICULAR PURPOSE. You are solely responsible for determining the
163
+ appropriateness of using or redistributing the Work and assume any
164
+ risks associated with Your exercise of permissions under this License.
165
+
166
+ 8. Limitation of Liability. In no event and under no legal theory,
167
+ whether in tort (including negligence), contract, or otherwise,
168
+ unless required by applicable law (such as deliberate and grossly
169
+ negligent acts) or agreed to in writing, shall any Contributor be
170
+ liable to You for damages, including any direct, indirect, special,
171
+ incidental, or consequential damages of any character arising as a
172
+ result of this License or out of the use or inability to use the
173
+ Work (including but not limited to damages for loss of goodwill,
174
+ work stoppage, computer failure or malfunction, or any and all
175
+ other commercial damages or losses), even if such Contributor
176
+ has been advised of the possibility of such damages.
177
+
178
+ 9. Accepting Warranty or Additional Liability. While redistributing
179
+ the Work or Derivative Works thereof, You may choose to offer,
180
+ and charge a fee for, acceptance of support, warranty, indemnity,
181
+ or other liability obligations and/or rights consistent with this
182
+ License. However, in accepting such obligations, You may act only
183
+ on Your own behalf and on Your sole responsibility, not on behalf
184
+ of any other Contributor, and only if You agree to indemnify,
185
+ defend, and hold each Contributor harmless for any liability
186
+ incurred by, or claims asserted against, such Contributor by reason
187
+ of your accepting any such warranty or additional liability.
188
+
189
+ END OF TERMS AND CONDITIONS
190
+
191
+ APPENDIX: How to apply the Apache License to your work.
192
+
193
+ To apply the Apache License to your work, attach the following
194
+ boilerplate notice, with the fields enclosed by brackets "[]"
195
+ replaced with your own identifying information. (Don't include
196
+ the brackets!) The text should be enclosed in the appropriate
197
+ comment syntax for the file format. We also recommend that a
198
+ file or class name and description of purpose be included on the
199
+ same "printed page" as the copyright notice for easier
200
+ identification within third-party archives.
201
+
202
+ Copyright 2024-2025 DEFAI Private Limited
203
+
204
+ Licensed under the Apache License, Version 2.0 (the "License");
205
+ you may not use this file except in compliance with the License.
206
+ You may obtain a copy of the License at
207
+
208
+ http://www.apache.org/licenses/LICENSE-2.0
209
+
210
+ Unless required by applicable law or agreed to in writing, software
211
+ distributed under the License is distributed on an "AS IS" BASIS,
212
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
213
+ See the License for the specific language governing permissions and
214
+ limitations under the License.
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Token Budget Allocator Implementation
3
+ *
4
+ * Manages token allocation for embedded instructions to prevent
5
+ * context window overflow.
6
+ */
7
+ import { type EmbeddedInstruction, type TokenBudgetConfig, type BudgetAllocation, type BudgetStatus, type InstructionType, type InstructionPriority } from '@defai.digital/contracts';
8
+ /**
9
+ * Token budget allocator interface
10
+ */
11
+ export interface TokenBudgetAllocator {
12
+ /**
13
+ * Allocate budget for instructions
14
+ */
15
+ allocate(instructions: EmbeddedInstruction[]): BudgetAllocation;
16
+ /**
17
+ * Get current budget status
18
+ */
19
+ getStatus(): BudgetStatus;
20
+ /**
21
+ * Update configuration
22
+ */
23
+ setConfig(config: TokenBudgetConfig): void;
24
+ /**
25
+ * Get current configuration
26
+ */
27
+ getConfig(): TokenBudgetConfig;
28
+ /**
29
+ * Estimate tokens for content
30
+ */
31
+ estimateTokens(content: string): number;
32
+ }
33
+ /**
34
+ * Default token budget allocator implementation
35
+ */
36
+ export declare class DefaultTokenBudgetAllocator implements TokenBudgetAllocator {
37
+ private config;
38
+ private currentAllocation;
39
+ constructor(config?: TokenBudgetConfig);
40
+ /**
41
+ * Allocate budget for instructions
42
+ */
43
+ allocate(instructions: EmbeddedInstruction[]): BudgetAllocation;
44
+ /**
45
+ * Get current budget status
46
+ */
47
+ getStatus(): BudgetStatus;
48
+ /**
49
+ * Update configuration
50
+ */
51
+ setConfig(config: TokenBudgetConfig): void;
52
+ /**
53
+ * Get current configuration
54
+ */
55
+ getConfig(): TokenBudgetConfig;
56
+ /**
57
+ * Estimate tokens for content using rule-based approximation
58
+ *
59
+ * Uses a simple heuristic: ~4 characters per token for English text.
60
+ * This is a rough approximation - for exact counts, use a tokenizer.
61
+ */
62
+ estimateTokens(content: string): number;
63
+ /**
64
+ * Get type limit from config
65
+ */
66
+ private getTypeLimit;
67
+ }
68
+ /**
69
+ * Token budget error
70
+ */
71
+ export declare class TokenBudgetError extends Error {
72
+ readonly code: string;
73
+ readonly details?: Record<string, unknown> | undefined;
74
+ constructor(code: string, message: string, details?: Record<string, unknown> | undefined);
75
+ }
76
+ /**
77
+ * Creates a new token budget allocator
78
+ */
79
+ export declare function createTokenBudgetAllocator(config?: TokenBudgetConfig): TokenBudgetAllocator;
80
+ /**
81
+ * Creates an embedded instruction
82
+ */
83
+ export declare function createInstruction(type: InstructionType, content: string, priority?: InstructionPriority, metadata?: Record<string, unknown>): EmbeddedInstruction;
84
+ //# sourceMappingURL=allocator.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"allocator.d.ts","sourceRoot":"","sources":["../src/allocator.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EACL,KAAK,mBAAmB,EACxB,KAAK,iBAAiB,EACtB,KAAK,gBAAgB,EACrB,KAAK,YAAY,EACjB,KAAK,eAAe,EACpB,KAAK,mBAAmB,EAIzB,MAAM,0BAA0B,CAAC;AAElC;;GAEG;AACH,MAAM,WAAW,oBAAoB;IACnC;;OAEG;IACH,QAAQ,CAAC,YAAY,EAAE,mBAAmB,EAAE,GAAG,gBAAgB,CAAC;IAEhE;;OAEG;IACH,SAAS,IAAI,YAAY,CAAC;IAE1B;;OAEG;IACH,SAAS,CAAC,MAAM,EA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ions to prevent
5
+ * context window overflow.
6
+ */
7
+ import { DEFAULT_TOKEN_BUDGET, getPriorityValue, getTypePriorityValue, } from '@defai.digital/contracts';
8
+ /**
9
+ * Default token budget allocator implementation
10
+ */
11
+ export class DefaultTokenBudgetAllocator {
12
+ config;
13
+ currentAllocation = null;
14
+ constructor(config = DEFAULT_TOKEN_BUDGET) {
15
+ this.config = config;
16
+ }
17
+ /**
18
+ * Allocate budget for instructions
19
+ */
20
+ allocate(instructions) {
21
+ const now = new Date().toISOString();
22
+ // Estimate tokens for instructions without estimates
23
+ const instructionsWithTokens = instructions.map((instr) => ({
24
+ ...instr,
25
+ estimatedTokens: instr.estimatedTokens ?? this.estimateTokens(instr.content),
26
+ }));
27
+ // Sort by priority (critical first, then by type priority)
28
+ const sorted = [...instructionsWithTokens].sort((a, b) => {
29
+ const priorityDiff = getPriorityValue(b.priority) - getPriorityValue(a.priority);
30
+ if (priorityDiff !== 0)
31
+ return priorityDiff;
32
+ return getTypePriorityValue(b.type) - getTypePriorityValue(a.type);
33
+ });
34
+ const included = [];
35
+ const excluded = [];
36
+ const usageByType = {
37
+ memory: 0,
38
+ todo: 0,
39
+ session: 0,
40
+ context: 0,
41
+ system: 0,
42
+ };
43
+ let totalTokens = 0;
44
+ let criticalReserveUsed = 0;
45
+ // Allocate instructions
46
+ for (const instruction of sorted) {
47
+ const tokens = instruction.estimatedTokens ?? 0;
48
+ const type = instruction.type;
49
+ // Check type limit
50
+ const typeLimit = this.getTypeLimit(type);
51
+ const typeUsage = usageByType[type];
52
+ const typeRemaining = typeLimit - typeUsage;
53
+ // Check total budget
54
+ const totalRemaining = this.config.maxTotal - totalTokens;
55
+ // Critical instructions can use reserve
56
+ if (instruction.priority === 'critical') {
57
+ const availableWithReserve = totalRemaining + (this.config.criticalReserve - criticalReserveUsed);
58
+ if (tokens <= availableWithReserve && tokens <= typeRemaining) {
59
+ // Use regular budget first, then reserve
60
+ const fromRegular = Math.min(tokens, totalRemaining);
61
+ const fromReserve = tokens - fromRegular;
62
+ totalTokens += fromRegular;
63
+ criticalReserveUsed += fromReserve;
64
+ usageByType[type] += tokens;
65
+ included.push(instruction);
66
+ }
67
+ else {
68
+ excluded.push(instruction);
69
+ }
70
+ }
71
+ else {
72
+ // Non-critical: must fit within regular budget
73
+ if (tokens <= totalRemaining && tokens <= typeRemaining) {
74
+ totalTokens += tokens;
75
+ usageByType[type] += tokens;
76
+ included.push(instruction);
77
+ }
78
+ else {
79
+ excluded.push(instruction);
80
+ }
81
+ }
82
+ }
83
+ const allocation = {
84
+ included,
85
+ excluded,
86
+ totalTokens: totalTokens + criticalReserveUsed,
87
+ remaining: this.config.maxTotal - totalTokens,
88
+ usageByType,
89
+ criticalReserveUsed,
90
+ allocationTimestamp: now,
91
+ };
92
+ this.currentAllocation = allocation;
93
+ return allocation;
94
+ }
95
+ /**
96
+ * Get current budget status
97
+ */
98
+ getStatus() {
99
+ const currentUsage = this.currentAllocation?.totalTokens ?? 0;
100
+ const usageByType = this.currentAllocation?.usageByType ?? {
101
+ memory: 0,
102
+ todo: 0,
103
+ session: 0,
104
+ context: 0,
105
+ system: 0,
106
+ };
107
+ const remaining = this.config.maxTotal - currentUsage;
108
+ const criticalReserveAvailable = this.config.criticalReserve -
109
+ (this.currentAllocation?.criticalReserveUsed ?? 0);
110
+ return {
111
+ config: this.config,
112
+ currentUsage,
113
+ usageByType,
114
+ remaining,
115
+ criticalReserveAvailable,
116
+ utilizationPercent: (currentUsage / this.config.maxTotal) * 100,
117
+ canAcceptMore: remaining > 0,
118
+ };
119
+ }
120
+ /**
121
+ * Update configuration
122
+ */
123
+ setConfig(config) {
124
+ this.config = config;
125
+ this.currentAllocation = null;
126
+ }
127
+ /**
128
+ * Get current configuration
129
+ */
130
+ getConfig() {
131
+ return { ...this.config };
132
+ }
133
+ /**
134
+ * Estimate tokens for content using rule-based approximation
135
+ *
136
+ * Uses a simple heuristic: ~4 characters per token for English text.
137
+ * This is a rough approximation - for exact counts, use a tokenizer.
138
+ */
139
+ estimateTokens(content) {
140
+ // Basic heuristic: ~4 characters per token
141
+ // This works reasonably well for English text
142
+ const charCount = content.length;
143
+ const wordCount = content.split(/\s+/).length;
144
+ // Average of character-based and word-based estimates
145
+ const charEstimate = Math.ceil(charCount / 4);
146
+ const wordEstimate = Math.ceil(wordCount * 1.3); // ~1.3 tokens per word
147
+ return Math.ceil((charEstimate + wordEstimate) / 2);
148
+ }
149
+ /**
150
+ * Get type limit from config
151
+ */
152
+ getTypeLimit(type) {
153
+ const limit = this.config.perType[type];
154
+ return limit ?? this.config.maxTotal;
155
+ }
156
+ }
157
+ /**
158
+ * Token budget error
159
+ */
160
+ export class TokenBudgetError extends Error {
161
+ code;
162
+ details;
163
+ constructor(code, message, details) {
164
+ super(message);
165
+ this.code = code;
166
+ this.details = details;
167
+ this.name = 'TokenBudgetError';
168
+ }
169
+ }
170
+ /**
171
+ * Creates a new token budget allocator
172
+ */
173
+ export function createTokenBudgetAllocator(config) {
174
+ return new DefaultTokenBudgetAllocator(config);
175
+ }
176
+ /**
177
+ * Creates an embedded instruction
178
+ */
179
+ export function createInstruction(type, content, priority = 'normal', metadata) {
180
+ return {
181
+ id: crypto.randomUUID(),
182
+ type,
183
+ content,
184
+ priority,
185
+ createdAt: new Date().toISOString(),
186
+ metadata,
187
+ };
188
+ }
189
+ //# sourceMappingURL=allocator.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"allocator.js","sourceRoot":"","sources":["../src/allocator.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAOL,oBAAoB,EACpB,gBAAgB,EAChB,oBAAoB,GACrB,MAAM,0BAA0B,CAAC;AAgClC;;GAEG;AACH,MAAM,OAAO,2BAA2B;IAC9B,MAAM,CAAoB;IAC1B,iBAAiB,GAA4B,IAAI,CAAC;IAE1D,YAAY,SAA4B,oBAAoB;QAC1D,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB,CAAC;IAED;;OAEG;IACH,QAAQ,CAAC,YAA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M,CAAC,UAAU,EAAE;QACvB,IAAI;QACJ,OAAO;QACP,QAAQ;QACR,SAAS,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;QACnC,QAAQ;KACT,CAAC;AACJ,CAAC"}
@@ -0,0 +1,14 @@
1
+ /**
2
+ * @defai.digital/token-budget
3
+ *
4
+ * Token budget management for AutomatosX context windows.
5
+ * Manages token allocation for embedded instructions to prevent
6
+ * context window overflow.
7
+ *
8
+ * Note: This is NOT cost-based - it manages limited context window tokens.
9
+ */
10
+ export type { TokenBudgetAllocator } from './allocator.js';
11
+ export { DefaultTokenBudgetAllocator, TokenBudgetError, createTokenBudgetAllocator, createInstruction, } from './allocator.js';
12
+ export type { InstructionType, InstructionPriority, PerTypeLimits, TokenBudgetConfig, EmbeddedInstruction, BudgetAllocation, BudgetStatus, TokenEstimationRequest, TokenEstimationResult, AllocationInput, TokenBudgetError as TokenBudgetErrorType, } from '@defai.digital/contracts';
13
+ export { InstructionTypeSchema, InstructionPrioritySchema, PerTypeLimitsSchema, TokenBudgetConfigSchema, EmbeddedInstructionSchema, BudgetAllocationSchema, BudgetStatusSchema, TokenBudgetErrorCode, TokenBudgetErrorSchema, DEFAULT_TOKEN_BUDGET, PRIORITY_ORDER, TYPE_PRIORITY_ORDER, validateTokenBudgetConfig, safeValidateTokenBudgetConfig, validateEmbeddedInstruction, safeValidateEmbeddedInstruction, validateAllocationInput, getPriorityValue, getTypePriorityValue, } from '@defai.digital/contracts';
14
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAGH,YAAY,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AAE3D,OAAO,EACL,2BAA2B,EAC3B,gBAAgB,EAChB,0BAA0B,EAC1B,iBAAiB,GAClB,MAAM,gBAAgB,CAAC;AAGxB,YAAY,EACV,eAAe,EACf,mBAAmB,EACnB,aAAa,EACb,iBAAiB,EACjB,mBAAmB,EACnB,gBAAgB,EAChB,YAAY,EACZ,sBAAsB,EACtB,qBAAqB,EACrB,eAAe,EACf,gBAAgB,IAAI,oBAAoB,GACzC,MAAM,0BAA0B,CAAC;AAElC,OAAO,EACL,qBAAqB,EACrB,yBAAyB,EACzB,mBAAmB,EACnB,uBAAuB,EACvB,yBAAyB,EACzB,sBAAsB,EACtB,kBAAkB,EAClB,oBAAoB,EACpB,sBAAsB,EACtB,oBAAoB,EACpB,cAAc,EACd,mBAAmB,EACnB,yBAAyB,EACzB,6BAA6B,EAC7B,2BAA2B,EAC3B,+BAA+B,EAC/B,uBAAuB,EACvB,gBAAgB,EAChB,oBAAoB,GACrB,MAAM,0BAA0B,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,12 @@
1
+ /**
2
+ * @defai.digital/token-budget
3
+ *
4
+ * Token budget management for AutomatosX context windows.
5
+ * Manages token allocation for embedded instructions to prevent
6
+ * context window overflow.
7
+ *
8
+ * Note: This is NOT cost-based - it manages limited context window tokens.
9
+ */
10
+ export { DefaultTokenBudgetAllocator, TokenBudgetError, createTokenBudgetAllocator, createInstruction, } from './allocator.js';
11
+ export { InstructionTypeSchema, InstructionPrioritySchema, PerTypeLimitsSchema, TokenBudgetConfigSchema, EmbeddedInstructionSchema, BudgetAllocationSchema, BudgetStatusSchema, TokenBudgetErrorCode, TokenBudgetErrorSchema, DEFAULT_TOKEN_BUDGET, PRIORITY_ORDER, TYPE_PRIORITY_ORDER, validateTokenBudgetConfig, safeValidateTokenBudgetConfig, validateEmbeddedInstruction, safeValidateEmbeddedInstruction, validateAllocationInput, getPriorityValue, getTypePriorityValue, } from '@defai.digital/contracts';
12
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAKH,OAAO,EACL,2BAA2B,EAC3B,gBAAgB,EAChB,0BAA0B,EAC1B,iBAAiB,GAClB,MAAM,gBAAgB,CAAC;AAiBxB,OAAO,EACL,qBAAqB,EACrB,yBAAyB,EACzB,mBAAmB,EACnB,uBAAuB,EACvB,yBAAyB,EACzB,sBAAsB,EACtB,kBAAkB,EAClB,oBAAoB,EACpB,sBAAsB,EACtB,oBAAoB,EACpB,cAAc,EACd,mBAAmB,EACnB,yBAAyB,EACzB,6BAA6B,EAC7B,2BAA2B,EAC3B,+BAA+B,EAC/B,uBAAuB,EACvB,gBAAgB,EAChB,oBAAoB,GACrB,MAAM,0BAA0B,CAAC"}
package/package.json ADDED
@@ -0,0 +1,48 @@
1
+ {
2
+ "name": "@defai.digital/token-budget",
3
+ "version": "13.0.3",
4
+ "type": "module",
5
+ "description": "Token budget management for AutomatosX context windows",
6
+ "license": "Apache-2.0",
7
+ "author": "DEFAI Private Limited",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "https://github.com/defai-digital/automatosx.git",
11
+ "directory": "packages/core/token-budget"
12
+ },
13
+ "homepage": "https://github.com/defai-digital/automatosx#readme",
14
+ "bugs": {
15
+ "url": "https://github.com/defai-digital/automatosx/issues"
16
+ },
17
+ "main": "dist/index.js",
18
+ "types": "dist/index.d.ts",
19
+ "exports": {
20
+ ".": {
21
+ "types": "./dist/index.d.ts",
22
+ "import": "./dist/index.js"
23
+ }
24
+ },
25
+ "files": [
26
+ "dist",
27
+ "src"
28
+ ],
29
+ "engines": {
30
+ "node": ">=20.0.0"
31
+ },
32
+ "publishConfig": {
33
+ "access": "public"
34
+ },
35
+ "dependencies": {
36
+ "@defai.digital/contracts": "13.0.3"
37
+ },
38
+ "devDependencies": {
39
+ "typescript": "^5.7.2"
40
+ },
41
+ "peerDependencies": {
42
+ "zod": "^3.23.0"
43
+ },
44
+ "scripts": {
45
+ "build": "tsc --build",
46
+ "clean": "rm -rf dist"
47
+ }
48
+ }
@@ -0,0 +1,261 @@
1
+ /**
2
+ * Token Budget Allocator Implementation
3
+ *
4
+ * Manages token allocation for embedded instructions to prevent
5
+ * context window overflow.
6
+ */
7
+
8
+ import {
9
+ type EmbeddedInstruction,
10
+ type TokenBudgetConfig,
11
+ type BudgetAllocation,
12
+ type BudgetStatus,
13
+ type InstructionType,
14
+ type InstructionPriority,
15
+ DEFAULT_TOKEN_BUDGET,
16
+ getPriorityValue,
17
+ getTypePriorityValue,
18
+ } from '@defai.digital/contracts';
19
+
20
+ /**
21
+ * Token budget allocator interface
22
+ */
23
+ export interface TokenBudgetAllocator {
24
+ /**
25
+ * Allocate budget for instructions
26
+ */
27
+ allocate(instructions: EmbeddedInstruction[]): BudgetAllocation;
28
+
29
+ /**
30
+ * Get current budget status
31
+ */
32
+ getStatus(): BudgetStatus;
33
+
34
+ /**
35
+ * Update configuration
36
+ */
37
+ setConfig(config: TokenBudgetConfig): void;
38
+
39
+ /**
40
+ * Get current configuration
41
+ */
42
+ getConfig(): TokenBudgetConfig;
43
+
44
+ /**
45
+ * Estimate tokens for content
46
+ */
47
+ estimateTokens(content: string): number;
48
+ }
49
+
50
+ /**
51
+ * Default token budget allocator implementation
52
+ */
53
+ export class DefaultTokenBudgetAllocator implements TokenBudgetAllocator {
54
+ private config: TokenBudgetConfig;
55
+ private currentAllocation: BudgetAllocation | null = null;
56
+
57
+ constructor(config: TokenBudgetConfig = DEFAULT_TOKEN_BUDGET) {
58
+ this.config = config;
59
+ }
60
+
61
+ /**
62
+ * Allocate budget for instructions
63
+ */
64
+ allocate(instructions: EmbeddedInstruction[]): BudgetAllocation {
65
+ const now = new Date().toISOString();
66
+
67
+ // Estimate tokens for instructions without estimates
68
+ const instructionsWithTokens = instructions.map((instr) => ({
69
+ ...instr,
70
+ estimatedTokens: instr.estimatedTokens ?? this.estimateTokens(instr.content),
71
+ }));
72
+
73
+ // Sort by priority (critical first, then by type priority)
74
+ const sorted = [...instructionsWithTokens].sort((a, b) => {
75
+ const priorityDiff = getPriorityValue(b.priority) - getPriorityValue(a.priority);
76
+ if (priorityDiff !== 0) return priorityDiff;
77
+ return getTypePriorityValue(b.type) - getTypePriorityValue(a.type);
78
+ });
79
+
80
+ const included: EmbeddedInstruction[] = [];
81
+ const excluded: EmbeddedInstruction[] = [];
82
+ const usageByType: Record<InstructionType, number> = {
83
+ memory: 0,
84
+ todo: 0,
85
+ session: 0,
86
+ context: 0,
87
+ system: 0,
88
+ };
89
+
90
+ let totalTokens = 0;
91
+ let criticalReserveUsed = 0;
92
+
93
+ // Allocate instructions
94
+ for (const instruction of sorted) {
95
+ const tokens = instruction.estimatedTokens ?? 0;
96
+ const type = instruction.type;
97
+
98
+ // Check type limit
99
+ const typeLimit = this.getTypeLimit(type);
100
+ const typeUsage = usageByType[type];
101
+ const typeRemaining = typeLimit - typeUsage;
102
+
103
+ // Check total budget
104
+ const totalRemaining = this.config.maxTotal - totalTokens;
105
+
106
+ // Critical instructions can use reserve
107
+ if (instruction.priority === 'critical') {
108
+ const availableWithReserve =
109
+ totalRemaining + (this.config.criticalReserve - criticalReserveUsed);
110
+
111
+ if (tokens <= availableWithReserve && tokens <= typeRemaining) {
112
+ // Use regular budget first, then reserve
113
+ const fromRegular = Math.min(tokens, totalRemaining);
114
+ const fromReserve = tokens - fromRegular;
115
+
116
+ totalTokens += fromRegular;
117
+ criticalReserveUsed += fromReserve;
118
+ usageByType[type] += tokens;
119
+ included.push(instruction);
120
+ } else {
121
+ excluded.push(instruction);
122
+ }
123
+ } else {
124
+ // Non-critical: must fit within regular budget
125
+ if (tokens <= totalRemaining && tokens <= typeRemaining) {
126
+ totalTokens += tokens;
127
+ usageByType[type] += tokens;
128
+ included.push(instruction);
129
+ } else {
130
+ excluded.push(instruction);
131
+ }
132
+ }
133
+ }
134
+
135
+ const allocation: BudgetAllocation = {
136
+ included,
137
+ excluded,
138
+ totalTokens: totalTokens + criticalReserveUsed,
139
+ remaining: this.config.maxTotal - totalTokens,
140
+ usageByType,
141
+ criticalReserveUsed,
142
+ allocationTimestamp: now,
143
+ };
144
+
145
+ this.currentAllocation = allocation;
146
+ return allocation;
147
+ }
148
+
149
+ /**
150
+ * Get current budget status
151
+ */
152
+ getStatus(): BudgetStatus {
153
+ const currentUsage = this.currentAllocation?.totalTokens ?? 0;
154
+ const usageByType = this.currentAllocation?.usageByType ?? {
155
+ memory: 0,
156
+ todo: 0,
157
+ session: 0,
158
+ context: 0,
159
+ system: 0,
160
+ };
161
+
162
+ const remaining = this.config.maxTotal - currentUsage;
163
+ const criticalReserveAvailable =
164
+ this.config.criticalReserve -
165
+ (this.currentAllocation?.criticalReserveUsed ?? 0);
166
+
167
+ return {
168
+ config: this.config,
169
+ currentUsage,
170
+ usageByType,
171
+ remaining,
172
+ criticalReserveAvailable,
173
+ utilizationPercent: (currentUsage / this.config.maxTotal) * 100,
174
+ canAcceptMore: remaining > 0,
175
+ };
176
+ }
177
+
178
+ /**
179
+ * Update configuration
180
+ */
181
+ setConfig(config: TokenBudgetConfig): void {
182
+ this.config = config;
183
+ this.currentAllocation = null;
184
+ }
185
+
186
+ /**
187
+ * Get current configuration
188
+ */
189
+ getConfig(): TokenBudgetConfig {
190
+ return { ...this.config };
191
+ }
192
+
193
+ /**
194
+ * Estimate tokens for content using rule-based approximation
195
+ *
196
+ * Uses a simple heuristic: ~4 characters per token for English text.
197
+ * This is a rough approximation - for exact counts, use a tokenizer.
198
+ */
199
+ estimateTokens(content: string): number {
200
+ // Basic heuristic: ~4 characters per token
201
+ // This works reasonably well for English text
202
+ const charCount = content.length;
203
+ const wordCount = content.split(/\s+/).length;
204
+
205
+ // Average of character-based and word-based estimates
206
+ const charEstimate = Math.ceil(charCount / 4);
207
+ const wordEstimate = Math.ceil(wordCount * 1.3); // ~1.3 tokens per word
208
+
209
+ return Math.ceil((charEstimate + wordEstimate) / 2);
210
+ }
211
+
212
+ /**
213
+ * Get type limit from config
214
+ */
215
+ private getTypeLimit(type: InstructionType): number {
216
+ const limit = this.config.perType[type];
217
+ return limit ?? this.config.maxTotal;
218
+ }
219
+ }
220
+
221
+ /**
222
+ * Token budget error
223
+ */
224
+ export class TokenBudgetError extends Error {
225
+ constructor(
226
+ public readonly code: string,
227
+ message: string,
228
+ public readonly details?: Record<string, unknown>
229
+ ) {
230
+ super(message);
231
+ this.name = 'TokenBudgetError';
232
+ }
233
+ }
234
+
235
+ /**
236
+ * Creates a new token budget allocator
237
+ */
238
+ export function createTokenBudgetAllocator(
239
+ config?: TokenBudgetConfig
240
+ ): TokenBudgetAllocator {
241
+ return new DefaultTokenBudgetAllocator(config);
242
+ }
243
+
244
+ /**
245
+ * Creates an embedded instruction
246
+ */
247
+ export function createInstruction(
248
+ type: InstructionType,
249
+ content: string,
250
+ priority: InstructionPriority = 'normal',
251
+ metadata?: Record<string, unknown>
252
+ ): EmbeddedInstruction {
253
+ return {
254
+ id: crypto.randomUUID(),
255
+ type,
256
+ content,
257
+ priority,
258
+ createdAt: new Date().toISOString(),
259
+ metadata,
260
+ };
261
+ }
package/src/index.ts ADDED
@@ -0,0 +1,56 @@
1
+ /**
2
+ * @defai.digital/token-budget
3
+ *
4
+ * Token budget management for AutomatosX context windows.
5
+ * Manages token allocation for embedded instructions to prevent
6
+ * context window overflow.
7
+ *
8
+ * Note: This is NOT cost-based - it manages limited context window tokens.
9
+ */
10
+
11
+ // Allocator
12
+ export type { TokenBudgetAllocator } from './allocator.js';
13
+
14
+ export {
15
+ DefaultTokenBudgetAllocator,
16
+ TokenBudgetError,
17
+ createTokenBudgetAllocator,
18
+ createInstruction,
19
+ } from './allocator.js';
20
+
21
+ // Re-export contract types for convenience
22
+ export type {
23
+ InstructionType,
24
+ InstructionPriority,
25
+ PerTypeLimits,
26
+ TokenBudgetConfig,
27
+ EmbeddedInstruction,
28
+ BudgetAllocation,
29
+ BudgetStatus,
30
+ TokenEstimationRequest,
31
+ TokenEstimationResult,
32
+ AllocationInput,
33
+ TokenBudgetError as TokenBudgetErrorType,
34
+ } from '@defai.digital/contracts';
35
+
36
+ export {
37
+ InstructionTypeSchema,
38
+ InstructionPrioritySchema,
39
+ PerTypeLimitsSchema,
40
+ TokenBudgetConfigSchema,
41
+ EmbeddedInstructionSchema,
42
+ BudgetAllocationSchema,
43
+ BudgetStatusSchema,
44
+ TokenBudgetErrorCode,
45
+ TokenBudgetErrorSchema,
46
+ DEFAULT_TOKEN_BUDGET,
47
+ PRIORITY_ORDER,
48
+ TYPE_PRIORITY_ORDER,
49
+ validateTokenBudgetConfig,
50
+ safeValidateTokenBudgetConfig,
51
+ validateEmbeddedInstruction,
52
+ safeValidateEmbeddedInstruction,
53
+ validateAllocationInput,
54
+ getPriorityValue,
55
+ getTypePriorityValue,
56
+ } from '@defai.digital/contracts';