@noetic-tools/context 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 (49) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +28 -0
  3. package/dist/context/budget.d.ts +39 -0
  4. package/dist/context/budget.js +183 -0
  5. package/dist/context/exec-context-factory.d.ts +24 -0
  6. package/dist/context/exec-context-factory.js +30 -0
  7. package/dist/context/function-call-utils.d.ts +6 -0
  8. package/dist/context/function-call-utils.js +27 -0
  9. package/dist/context/layer-api.d.ts +11 -0
  10. package/dist/context/layer-api.js +91 -0
  11. package/dist/context/layer-lifecycle.d.ts +239 -0
  12. package/dist/context/layer-lifecycle.js +800 -0
  13. package/dist/context/layer-provides.d.ts +32 -0
  14. package/dist/context/layer-provides.js +33 -0
  15. package/dist/context/layer-usage.d.ts +13 -0
  16. package/dist/context/layer-usage.js +54 -0
  17. package/dist/context/layers/durable-task-state.d.ts +107 -0
  18. package/dist/context/layers/durable-task-state.js +250 -0
  19. package/dist/context/layers/file-reference.d.ts +55 -0
  20. package/dist/context/layers/file-reference.js +729 -0
  21. package/dist/context/layers/history-window.d.ts +31 -0
  22. package/dist/context/layers/history-window.js +150 -0
  23. package/dist/context/layers/observational-context.d.ts +56 -0
  24. package/dist/context/layers/observational-context.js +152 -0
  25. package/dist/context/layers/plan-context.d.ts +73 -0
  26. package/dist/context/layers/plan-context.js +749 -0
  27. package/dist/context/layers/static-content.d.ts +27 -0
  28. package/dist/context/layers/static-content.js +46 -0
  29. package/dist/context/layers/steering.d.ts +50 -0
  30. package/dist/context/layers/steering.js +291 -0
  31. package/dist/context/layers/temporal-context.d.ts +91 -0
  32. package/dist/context/layers/temporal-context.js +327 -0
  33. package/dist/context/layers/tool-context-layer.d.ts +15 -0
  34. package/dist/context/layers/tool-context-layer.js +43 -0
  35. package/dist/context/layers/working-memory-context.d.ts +46 -0
  36. package/dist/context/layers/working-memory-context.js +155 -0
  37. package/dist/context/projector.d.ts +19 -0
  38. package/dist/context/projector.js +89 -0
  39. package/dist/context/scope.d.ts +3 -0
  40. package/dist/context/scope.js +42 -0
  41. package/dist/context/storage-batch.d.ts +18 -0
  42. package/dist/context/storage-batch.js +35 -0
  43. package/dist/context/strip-unresolved.d.ts +13 -0
  44. package/dist/context/strip-unresolved.js +35 -0
  45. package/dist/deprecated.d.ts +43 -0
  46. package/dist/deprecated.js +28 -0
  47. package/dist/index.d.ts +29 -0
  48. package/dist/index.js +31 -0
  49. package/package.json +63 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for describing the origin of the Work and
141
+ reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Support. While redistributing the Work or
166
+ Derivative Works thereof, You may choose to offer, and charge a
167
+ fee for, acceptance of support, warranty, indemnity, or other
168
+ liability obligations and/or rights consistent with this License.
169
+ However, in accepting such obligations, You may act only on Your
170
+ own behalf and on Your sole responsibility, not on behalf of any
171
+ other Contributor, and only if You agree to indemnify, defend,
172
+ and hold each Contributor harmless for any liability incurred by,
173
+ or claims asserted against, such Contributor by reason of your
174
+ accepting any such warranty or support.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Matt Apperson
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
200
+ implied. See the License for the specific language governing
201
+ permissions and limitations under the License.
package/README.md ADDED
@@ -0,0 +1,28 @@
1
+ # @noetic-tools/context
2
+
3
+ The context layer system for Noetic agents.
4
+
5
+ A *context layer* is a composable unit that shapes what an agent sees in its
6
+ context window — capping history, summarising old turns, tracking a plan,
7
+ exposing tool results, redacting items, and steering tool calls. This package
8
+ provides:
9
+
10
+ - The **`ContextLayer` contract** — the interface every layer implements.
11
+ - The **lifecycle, budget, and projection machinery** that converges layer
12
+ outputs into the assembled LLM context (`assembleView`, `allocateBudgets`,
13
+ layer state stores, scoping).
14
+ - The **built-in layers**: working memory, history window, observational
15
+ context, plan, temporal, steering, file reference, static content, durable
16
+ task state, and the tool context layer.
17
+
18
+ It depends only on [`@noetic-tools/types`](https://www.npmjs.com/package/@noetic-tools/types).
19
+ [`@noetic-tools/core`](https://www.npmjs.com/package/@noetic-tools/core) builds
20
+ on it and re-exports its public surface, so application code typically imports
21
+ context layers from `@noetic-tools/core`.
22
+
23
+ > Formerly published as `@noetic-tools/memory`. That package still resolves — it
24
+ > re-exports everything here — but is deprecated and will stop being updated.
25
+
26
+ ## License
27
+
28
+ Apache-2.0
@@ -0,0 +1,39 @@
1
+ import type { Context, ContextLayer, ProjectionPolicy } from '@noetic-tools/types';
2
+ export interface BudgetAllocation {
3
+ layerId: string;
4
+ allocated: number;
5
+ }
6
+ /**
7
+ * Fallback projection policy when neither a step nor the harness configures one.
8
+ * The token budget is a conservative default; configure `harness.projection` or
9
+ * `step.projection` to match the target model's real context length.
10
+ */
11
+ export declare const DEFAULT_PROJECTION: ProjectionPolicy;
12
+ interface AllocateBudgetsOpts {
13
+ layers: ContextLayer[];
14
+ totalBudget: number;
15
+ systemPromptTokens: number;
16
+ responseReserve: number;
17
+ }
18
+ /**
19
+ * Split the recall budget across layers: minimums first, then 60% of the
20
+ * remainder as a proportional pool (by headroom `max − min`; `'auto'` and
21
+ * omitted budgets have infinite headroom and split the pool after finite
22
+ * layers take their share), 40% reserved for history. The pool is conserved —
23
+ * finite shares plus the infinite layers' split always sum to the pool.
24
+ *
25
+ * Input contract: `totalBudget` / `systemPromptTokens` / `responseReserve`
26
+ * MUST NOT be NaN (throws `NoeticConfigError` code `INVALID_BUDGET_INPUT`).
27
+ * `Infinity` is allowed (= uncapped) and fractional values are accepted.
28
+ */
29
+ export declare function allocateBudgets({ layers, totalBudget, systemPromptTokens, responseReserve, }: AllocateBudgetsOpts): {
30
+ allocations: BudgetAllocation[];
31
+ historyBudget: number;
32
+ };
33
+ export interface BudgetLimits {
34
+ maxCost?: number;
35
+ maxSteps?: number;
36
+ maxDuration?: number;
37
+ }
38
+ export declare function checkBudget(ctx: Context, limits: BudgetLimits): void;
39
+ export {};
@@ -0,0 +1,183 @@
1
+ import { NoeticConfigError, NoeticErrorImpl } from '@noetic-tools/types';
2
+ /**
3
+ * Fallback projection policy when neither a step nor the harness configures one.
4
+ * The token budget is a conservative default; configure `harness.projection` or
5
+ * `step.projection` to match the target model's real context length.
6
+ */
7
+ export const DEFAULT_PROJECTION = {
8
+ tokenBudget: 128e3,
9
+ responseReserve: 4e3,
10
+ overflow: 'sliding_window',
11
+ };
12
+ function extractMin(config) {
13
+ if (config && typeof config === 'object' && 'min' in config) {
14
+ return config.min;
15
+ }
16
+ return 0;
17
+ }
18
+ function extractMax(config) {
19
+ // 'auto' AND omitted budgets have infinite headroom (spec 11): a layer that
20
+ // declares no budget splits the proportional pool with the 'auto' layers
21
+ // rather than being starved at 0.
22
+ if (config === 'auto' || config === undefined) {
23
+ return Number.POSITIVE_INFINITY;
24
+ }
25
+ if (typeof config === 'number') {
26
+ return config;
27
+ }
28
+ if (typeof config === 'object' && 'min' in config) {
29
+ return config.max;
30
+ }
31
+ return 0;
32
+ }
33
+ /**
34
+ * Single-priced finite shares: each finite layer's share is computed ONCE and
35
+ * that same value is subtracted from the pool before infinite-headroom layers
36
+ * split the remainder — so the pool is conserved (Σ shares === layerPool when
37
+ * any infinite layer exists). With no infinite layers, finite layers split the
38
+ * whole pool proportionally; with a mix, finite layers share half the pool,
39
+ * clamped to their headroom.
40
+ */
41
+ function computeFiniteShares(headrooms, layerPool) {
42
+ const infiniteCount = headrooms.filter((h) => !Number.isFinite(h)).length;
43
+ const finiteTotal = headrooms.reduce((sum, h) => (Number.isFinite(h) ? sum + h : sum), 0);
44
+ const finitePool = infiniteCount === 0 ? layerPool : layerPool * 0.5;
45
+ return headrooms.map((h) => {
46
+ if (!Number.isFinite(h) || finiteTotal === 0) {
47
+ return 0;
48
+ }
49
+ const proportional = (h / finiteTotal) * finitePool;
50
+ return infiniteCount === 0 ? proportional : Math.min(h, proportional);
51
+ });
52
+ }
53
+ const BUDGET_INPUT_FIELDS = [
54
+ 'totalBudget',
55
+ 'systemPromptTokens',
56
+ 'responseReserve',
57
+ ];
58
+ /**
59
+ * NaN in any budget input silently poisons every allocation downstream
60
+ * (NaN fails the `available <= 0` guard, then every arithmetic op yields
61
+ * NaN). Reject it loudly at the boundary. `Infinity` stays allowed — it is a
62
+ * coherent "uncapped" budget — and fractional values are fine (allocations
63
+ * floor where it matters).
64
+ */
65
+ function assertBudgetInputs(opts) {
66
+ for (const field of BUDGET_INPUT_FIELDS) {
67
+ if (Number.isNaN(opts[field])) {
68
+ throw new NoeticConfigError({
69
+ code: 'INVALID_BUDGET_INPUT',
70
+ message: `allocateBudgets: ${field} is NaN.`,
71
+ hint: 'Pass a real number (Infinity is allowed for an uncapped budget).',
72
+ });
73
+ }
74
+ }
75
+ }
76
+ /**
77
+ * Split the recall budget across layers: minimums first, then 60% of the
78
+ * remainder as a proportional pool (by headroom `max − min`; `'auto'` and
79
+ * omitted budgets have infinite headroom and split the pool after finite
80
+ * layers take their share), 40% reserved for history. The pool is conserved —
81
+ * finite shares plus the infinite layers' split always sum to the pool.
82
+ *
83
+ * Input contract: `totalBudget` / `systemPromptTokens` / `responseReserve`
84
+ * MUST NOT be NaN (throws `NoeticConfigError` code `INVALID_BUDGET_INPUT`).
85
+ * `Infinity` is allowed (= uncapped) and fractional values are accepted.
86
+ */
87
+ export function allocateBudgets({ layers, totalBudget, systemPromptTokens, responseReserve, }) {
88
+ assertBudgetInputs({
89
+ layers,
90
+ totalBudget,
91
+ systemPromptTokens,
92
+ responseReserve,
93
+ });
94
+ const available = totalBudget - responseReserve - systemPromptTokens;
95
+ if (available <= 0) {
96
+ return {
97
+ allocations: layers.map((l) => ({
98
+ layerId: l.id,
99
+ allocated: 0,
100
+ })),
101
+ historyBudget: 0,
102
+ };
103
+ }
104
+ // Phase 1: satisfy minimums
105
+ let remaining = available;
106
+ const allocations = [];
107
+ for (const layer of layers) {
108
+ const min = extractMin(layer.budget);
109
+ allocations.push({
110
+ layerId: layer.id,
111
+ allocated: min,
112
+ });
113
+ remaining -= min;
114
+ }
115
+ // Declared minimums overcommit the available budget: scale them down
116
+ // proportionally so the total fits `available` (never negative, never over).
117
+ // Nothing is left for the proportional pool or history.
118
+ if (remaining < 0) {
119
+ const totalMin = available - remaining;
120
+ const scale = totalMin > 0 ? available / totalMin : 0;
121
+ for (const alloc of allocations) {
122
+ alloc.allocated = Math.floor(alloc.allocated * scale);
123
+ }
124
+ return {
125
+ allocations,
126
+ historyBudget: 0,
127
+ };
128
+ }
129
+ // Phase 2: distribute 60% of remaining to layers proportionally, 40% to history
130
+ const layerPool = remaining * 0.6;
131
+ const historyBudget = remaining * 0.4;
132
+ // Compute headroom per layer (how much above the minimum each layer can absorb)
133
+ let totalMax = 0;
134
+ const headrooms = [];
135
+ for (let i = 0; i < layers.length; i++) {
136
+ const max = extractMax(layers[i].budget);
137
+ const headroom = Math.max(0, max - allocations[i].allocated);
138
+ headrooms.push(headroom);
139
+ totalMax += headroom;
140
+ }
141
+ if (totalMax > 0) {
142
+ const infiniteCount = headrooms.filter((h) => !Number.isFinite(h)).length;
143
+ const finiteShares = computeFiniteShares(headrooms, layerPool);
144
+ const finiteUsed = finiteShares.reduce((sum, s) => sum + s, 0);
145
+ // Infinite-headroom layers split exactly what the finite shares left over,
146
+ // so no part of the pool is silently lost.
147
+ const infiniteShare = infiniteCount > 0 ? (layerPool - finiteUsed) / infiniteCount : 0;
148
+ for (let i = 0; i < headrooms.length; i++) {
149
+ const share = Number.isFinite(headrooms[i]) ? finiteShares[i] : infiniteShare;
150
+ allocations[i].allocated += Math.min(share, headrooms[i]);
151
+ }
152
+ }
153
+ return {
154
+ allocations,
155
+ historyBudget: Math.max(0, historyBudget),
156
+ };
157
+ }
158
+ export function checkBudget(ctx, limits) {
159
+ if (limits.maxCost !== undefined && ctx.cost > limits.maxCost) {
160
+ throw new NoeticErrorImpl({
161
+ kind: 'budget_exceeded',
162
+ field: 'cost',
163
+ limit: limits.maxCost,
164
+ actual: ctx.cost,
165
+ });
166
+ }
167
+ if (limits.maxSteps !== undefined && ctx.stepCount > limits.maxSteps) {
168
+ throw new NoeticErrorImpl({
169
+ kind: 'budget_exceeded',
170
+ field: 'steps',
171
+ limit: limits.maxSteps,
172
+ actual: ctx.stepCount,
173
+ });
174
+ }
175
+ if (limits.maxDuration !== undefined && ctx.elapsed > limits.maxDuration) {
176
+ throw new NoeticErrorImpl({
177
+ kind: 'budget_exceeded',
178
+ field: 'duration',
179
+ limit: limits.maxDuration,
180
+ actual: ctx.elapsed,
181
+ });
182
+ }
183
+ }
@@ -0,0 +1,24 @@
1
+ import type { Context, ExecutionContext } from '@noetic-tools/types';
2
+ /**
3
+ * Optional overrides for `contextToExecCtx`. Used by `executeSpawn` to build
4
+ * parent and child execution contexts that reuse the same tokenize / trace /
5
+ * layer-state wiring as the main path, but with spawn-specific identity
6
+ * (`executionId`, `depth`, `stepNumber`, and the scope used for layer-state
7
+ * reads).
8
+ */
9
+ export interface ExecCtxOverrides {
10
+ callModel?: ExecutionContext['callModel'];
11
+ executionId?: string;
12
+ depth?: number;
13
+ stepNumber?: number;
14
+ tokenUsage?: ExecutionContext['tokenUsage'];
15
+ cost?: number;
16
+ /** Execution id to scope `readLayerState` to (defaults to `ctx.id`). */
17
+ readLayerStateId?: string;
18
+ }
19
+ /**
20
+ * Maps a full `Context` to the lightweight `ExecutionContext` consumed by context layer hooks.
21
+ * Centralised here so the mapping stays consistent across agent-harness, layer-api, and the
22
+ * spawn interpreter.
23
+ */
24
+ export declare function contextToExecCtx(ctx: Context, overrides?: ExecCtxOverrides): ExecutionContext;
@@ -0,0 +1,30 @@
1
+ import { estimateTokens } from '@noetic-tools/types';
2
+ /**
3
+ * Maps a full `Context` to the lightweight `ExecutionContext` consumed by context layer hooks.
4
+ * Centralised here so the mapping stays consistent across agent-harness, layer-api, and the
5
+ * spawn interpreter.
6
+ */
7
+ export function contextToExecCtx(ctx, overrides) {
8
+ const readLayerStateId = overrides?.readLayerStateId ?? ctx.id;
9
+ return {
10
+ executionId: overrides?.executionId ?? ctx.id,
11
+ threadId: ctx.threadId,
12
+ resourceId: ctx.resourceId,
13
+ depth: overrides?.depth ?? ctx.depth,
14
+ stepNumber: overrides?.stepNumber ?? ctx.stepCount,
15
+ tokenUsage: overrides?.tokenUsage ?? {
16
+ input: ctx.tokens.input,
17
+ output: ctx.tokens.output,
18
+ },
19
+ cost: overrides?.cost ?? ctx.cost,
20
+ fs: ctx.harness.fs,
21
+ shell: ctx.harness.shell,
22
+ callModel: overrides?.callModel,
23
+ tokenize: estimateTokens,
24
+ trace: {
25
+ setAttribute: (key, value) => ctx.span.setAttribute(key, value),
26
+ addEvent: (name, attributes) => ctx.span.addEvent(name, attributes),
27
+ },
28
+ readLayerState: (layerId) => ctx.harness.getLayerState(readLayerStateId, layerId),
29
+ };
30
+ }
@@ -0,0 +1,6 @@
1
+ import type { Item } from '@noetic-tools/types';
2
+ /**
3
+ * Finds the first function_call item matching `name`, parses its JSON arguments,
4
+ * and returns the result as a record. Returns null if no match or invalid data.
5
+ */
6
+ export declare function findFunctionCall(items: ReadonlyArray<Item>, name: string): Record<string, unknown> | null;
@@ -0,0 +1,27 @@
1
+ import { frameworkCast } from '@noetic-tools/types';
2
+ function isFunctionCall(item) {
3
+ return item.type === 'function_call' && 'callId' in item && 'name' in item;
4
+ }
5
+ /**
6
+ * Finds the first function_call item matching `name`, parses its JSON arguments,
7
+ * and returns the result as a record. Returns null if no match or invalid data.
8
+ */
9
+ export function findFunctionCall(items, name) {
10
+ for (const item of items) {
11
+ if (!isFunctionCall(item)) {
12
+ continue;
13
+ }
14
+ if (item.name !== name) {
15
+ continue;
16
+ }
17
+ try {
18
+ const raw = JSON.parse(item.arguments);
19
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {
20
+ continue;
21
+ }
22
+ return frameworkCast(raw);
23
+ }
24
+ catch { }
25
+ }
26
+ return null;
27
+ }
@@ -0,0 +1,11 @@
1
+ import type { AgentHarnessContract, Context, ContextData, ContextLayer, Tool } from '@noetic-tools/types';
2
+ /**
3
+ * Build the `ctx.context` object — a readonly map of layer ID → resolved handle.
4
+ * Handles use getters for data (live reads) and closures for functions (lazy state).
5
+ */
6
+ export declare function buildContextData(layers: ReadonlyArray<ContextLayer>, ctx: Context): ContextData;
7
+ /**
8
+ * Collect all `provides` function declarations from active layers and convert them to Tools.
9
+ * Tool names are namespaced as `layerId/functionName`.
10
+ */
11
+ export declare function resolveLayerTools(layers: ReadonlyArray<ContextLayer>, harness: AgentHarnessContract, ctx: Context): Tool[];
@@ -0,0 +1,91 @@
1
+ import { frameworkCast } from '@noetic-tools/types';
2
+ import { contextToExecCtx } from './exec-context-factory.js';
3
+ function executeLayerFn(params) {
4
+ const { fn, args, layerId, harness, ctx } = params;
5
+ const validated = fn.input.parse(args);
6
+ const state = harness.getLayerState(ctx.id, layerId);
7
+ const execCtx = contextToExecCtx(ctx);
8
+ return fn.execute(validated, state, execCtx).then((outcome) => {
9
+ if (outcome.state !== undefined) {
10
+ harness.setLayerState(ctx.id, layerId, outcome.state);
11
+ }
12
+ return outcome.result;
13
+ });
14
+ }
15
+ function buildLayerHandle(layer, ctx) {
16
+ const provides = layer.provides;
17
+ if (!provides) {
18
+ return {};
19
+ }
20
+ const handle = {};
21
+ const harness = ctx.harness;
22
+ const layerId = layer.id;
23
+ for (const [name, decl] of Object.entries(provides)) {
24
+ if (decl.kind === 'data') {
25
+ Object.defineProperty(handle, name, {
26
+ get() {
27
+ const state = harness.getLayerState(ctx.id, layerId);
28
+ return decl.read(state);
29
+ },
30
+ enumerable: true,
31
+ });
32
+ continue;
33
+ }
34
+ handle[name] = (args) => executeLayerFn({
35
+ fn: decl,
36
+ args,
37
+ layerId,
38
+ harness,
39
+ ctx,
40
+ });
41
+ }
42
+ return handle;
43
+ }
44
+ //#endregion
45
+ //#region Context Data
46
+ /**
47
+ * Build the `ctx.context` object — a readonly map of layer ID → resolved handle.
48
+ * Handles use getters for data (live reads) and closures for functions (lazy state).
49
+ */
50
+ export function buildContextData(layers, ctx) {
51
+ const data = {};
52
+ for (const layer of layers) {
53
+ data[layer.id] = buildLayerHandle(layer, ctx);
54
+ }
55
+ return frameworkCast(data);
56
+ }
57
+ //#endregion
58
+ //#region Layer Tools Resolution
59
+ /**
60
+ * Collect all `provides` function declarations from active layers and convert them to Tools.
61
+ * Tool names are namespaced as `layerId/functionName`.
62
+ */
63
+ export function resolveLayerTools(layers, harness, ctx) {
64
+ const tools = [];
65
+ for (const layer of layers) {
66
+ if (!layer.provides) {
67
+ continue;
68
+ }
69
+ for (const [name, decl] of Object.entries(layer.provides)) {
70
+ if (decl.kind !== 'function') {
71
+ continue;
72
+ }
73
+ const layerId = layer.id;
74
+ tools.push({
75
+ name: `${layerId}/${name}`,
76
+ description: decl.description,
77
+ input: decl.input,
78
+ output: decl.output,
79
+ execute: (args, _toolCtx) => executeLayerFn({
80
+ fn: decl,
81
+ args,
82
+ layerId,
83
+ harness,
84
+ ctx,
85
+ }),
86
+ });
87
+ }
88
+ }
89
+ return tools;
90
+ }
91
+ //#endregion