@noetic-tools/core 0.2.1 → 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 (207) hide show
  1. package/dist/adapters/in-memory-fs-adapter.d.ts +1 -1
  2. package/dist/adapters/in-memory-fs-adapter.js +1 -1
  3. package/dist/adapters/in-memory-shell-adapter.d.ts +1 -1
  4. package/dist/adapters/in-memory-subprocess/manifest-persistence.d.ts +2 -2
  5. package/dist/adapters/in-memory-subprocess/metadata.d.ts +1 -1
  6. package/dist/adapters/in-memory-subprocess/types.d.ts +2 -2
  7. package/dist/adapters/in-memory-subprocess-adapter.d.ts +1 -1
  8. package/dist/adapters/openrouter.d.ts +2 -6
  9. package/dist/adapters/openrouter.js +1 -4
  10. package/dist/builders/channel-builder.d.ts +1 -1
  11. package/dist/builders/control-flow-builders.d.ts +2 -3
  12. package/dist/builders/control-flow-builders.js +1 -2
  13. package/dist/builders/every.d.ts +2 -3
  14. package/dist/builders/every.js +1 -1
  15. package/dist/builders/layer-provides-builders.d.ts +1 -1
  16. package/dist/builders/layer-provides-builders.js +1 -1
  17. package/dist/builders/loop-builder.d.ts +2 -2
  18. package/dist/builders/loop-builder.js +1 -1
  19. package/dist/builders/memory-builder.d.ts +1 -1
  20. package/dist/builders/memory-builder.js +1 -1
  21. package/dist/builders/provide-builder.d.ts +2 -2
  22. package/dist/builders/provide-builder.js +1 -1
  23. package/dist/builders/spawn-builder.d.ts +2 -3
  24. package/dist/builders/spawn-builder.js +1 -1
  25. package/dist/builders/step-builders.d.ts +2 -6
  26. package/dist/builders/step-builders.js +1 -1
  27. package/dist/builders/tool-builder.d.ts +1 -3
  28. package/dist/builders/tool-builder.js +1 -1
  29. package/dist/builders/workflow-hydrator.d.ts +2 -3
  30. package/dist/builders/workflow-hydrator.js +1 -2
  31. package/dist/conditions/conditions.d.ts +2 -3
  32. package/dist/conditions/conditions.js +1 -1
  33. package/dist/harness/agent-harness.d.ts +15 -5
  34. package/dist/harness/agent-harness.js +65 -10
  35. package/dist/harness/deps/memory.d.ts +2 -5
  36. package/dist/harness/deps/memory.js +1 -4
  37. package/dist/harness/deps/types.d.ts +3 -16
  38. package/dist/harness/deps/types.js +1 -1
  39. package/dist/harness/model-call.d.ts +1 -3
  40. package/dist/harness/model-call.js +10 -10
  41. package/dist/harness/model-schema.d.ts +10 -4
  42. package/dist/harness/model-schema.js +9 -1
  43. package/dist/index.d.ts +28 -49
  44. package/dist/index.js +9 -27
  45. package/dist/interpreter/action-deps.d.ts +4 -8
  46. package/dist/interpreter/action-deps.js +2 -6
  47. package/dist/interpreter/action-types.d.ts +3 -8
  48. package/dist/interpreter/action-types.js +1 -1
  49. package/dist/interpreter/collect-tools.d.ts +1 -2
  50. package/dist/interpreter/collect-tools.js +1 -1
  51. package/dist/interpreter/execute-action.js +122 -27
  52. package/dist/interpreter/execute-control.d.ts +1 -2
  53. package/dist/interpreter/execute-control.js +60 -7
  54. package/dist/interpreter/execute.d.ts +2 -3
  55. package/dist/interpreter/execute.js +1 -2
  56. package/dist/interpreter/message-helpers.d.ts +1 -1
  57. package/dist/interpreter/message-helpers.js +1 -1
  58. package/dist/interpreter/step-dispatcher.d.ts +2 -5
  59. package/dist/interpreter/typeguards.d.ts +3 -4
  60. package/dist/interpreter/typeguards.js +1 -1
  61. package/dist/observability/span-impl.d.ts +1 -1
  62. package/dist/observability/trace-exporter.d.ts +1 -1
  63. package/dist/patterns/dynamic-workflow.d.ts +2 -5
  64. package/dist/patterns/dynamic-workflow.js +1 -2
  65. package/dist/patterns/flow.d.ts +2 -2
  66. package/dist/patterns/flow.js +1 -1
  67. package/dist/patterns/interview.d.ts +2 -2
  68. package/dist/patterns/interview.js +1 -1
  69. package/dist/patterns/plans.d.ts +2 -3
  70. package/dist/patterns/plans.js +1 -1
  71. package/dist/patterns/ralph-wiggum.d.ts +2 -3
  72. package/dist/patterns/react.d.ts +2 -3
  73. package/dist/portable/memory-layers.d.ts +1 -7
  74. package/dist/portable/memory-layers.js +1 -7
  75. package/dist/portable.d.ts +2 -2
  76. package/dist/portable.js +2 -2
  77. package/dist/runtime/broadcaster-utils.d.ts +1 -1
  78. package/dist/runtime/channel-store.d.ts +43 -3
  79. package/dist/runtime/channel-store.js +233 -37
  80. package/dist/runtime/context-deps.d.ts +3 -3
  81. package/dist/runtime/context-deps.js +2 -2
  82. package/dist/runtime/context-impl.d.ts +17 -1
  83. package/dist/runtime/context-impl.js +30 -3
  84. package/dist/runtime/context-type-deps.d.ts +2 -11
  85. package/dist/runtime/cwd-helpers.d.ts +1 -1
  86. package/dist/runtime/detached-handle.d.ts +2 -3
  87. package/dist/runtime/detached-handle.js +1 -3
  88. package/dist/runtime/durable/checkpoint-store.d.ts +1 -1
  89. package/dist/runtime/durable/checkpoint-store.js +1 -1
  90. package/dist/runtime/durable/harness-checkpoints.d.ts +2 -5
  91. package/dist/runtime/durable/runnable-loop.d.ts +1 -3
  92. package/dist/runtime/durable/session-seed.d.ts +1 -1
  93. package/dist/runtime/durable/stall-nudge.d.ts +17 -10
  94. package/dist/runtime/durable/stall-nudge.js +29 -10
  95. package/dist/runtime/event-broadcaster.d.ts +10 -2
  96. package/dist/runtime/event-broadcaster.js +43 -19
  97. package/dist/runtime/in-memory-storage.d.ts +1 -1
  98. package/dist/runtime/in-memory-storage.js +1 -1
  99. package/dist/runtime/item-log-impl.d.ts +1 -3
  100. package/dist/runtime/item-log-impl.js +1 -1
  101. package/dist/runtime/message-queue.d.ts +1 -2
  102. package/dist/runtime/session-runner.d.ts +1 -4
  103. package/dist/runtime/session-streams.d.ts +1 -2
  104. package/dist/runtime/session-streams.js +1 -1
  105. package/dist/runtime/step-registry.d.ts +2 -2
  106. package/dist/runtime/step-registry.js +1 -2
  107. package/dist/runtime/tool-memory.d.ts +1 -3
  108. package/dist/types/mutable-context.d.ts +2 -3
  109. package/dist/types/step-registrar.d.ts +1 -1
  110. package/dist/unstable.d.ts +5 -9
  111. package/dist/unstable.js +3 -6
  112. package/dist/until/combinators.d.ts +1 -1
  113. package/dist/until/never.d.ts +1 -1
  114. package/dist/until/predicates.d.ts +2 -2
  115. package/package.json +4 -2
  116. package/dist/errors/noetic-config-error.d.ts +0 -41
  117. package/dist/errors/noetic-config-error.js +0 -44
  118. package/dist/errors/noetic-error.d.ts +0 -18
  119. package/dist/errors/noetic-error.js +0 -54
  120. package/dist/memory/budget.d.ts +0 -23
  121. package/dist/memory/budget.js +0 -117
  122. package/dist/memory/exec-context-factory.d.ts +0 -25
  123. package/dist/memory/exec-context-factory.js +0 -30
  124. package/dist/memory/flow-schema.d.ts +0 -52
  125. package/dist/memory/flow-schema.js +0 -102
  126. package/dist/memory/function-call-utils.d.ts +0 -6
  127. package/dist/memory/function-call-utils.js +0 -27
  128. package/dist/memory/layer-api.d.ts +0 -14
  129. package/dist/memory/layer-api.js +0 -91
  130. package/dist/memory/layer-lifecycle.d.ts +0 -160
  131. package/dist/memory/layer-lifecycle.js +0 -552
  132. package/dist/memory/layer-provides.d.ts +0 -32
  133. package/dist/memory/layer-provides.js +0 -33
  134. package/dist/memory/layer-usage.d.ts +0 -16
  135. package/dist/memory/layer-usage.js +0 -54
  136. package/dist/memory/layers/durable-task-state.d.ts +0 -79
  137. package/dist/memory/layers/durable-task-state.js +0 -118
  138. package/dist/memory/layers/file-reference.d.ts +0 -55
  139. package/dist/memory/layers/file-reference.js +0 -594
  140. package/dist/memory/layers/history-window.d.ts +0 -29
  141. package/dist/memory/layers/history-window.js +0 -114
  142. package/dist/memory/layers/observational-memory.d.ts +0 -53
  143. package/dist/memory/layers/observational-memory.js +0 -109
  144. package/dist/memory/layers/plan.d.ts +0 -55
  145. package/dist/memory/layers/plan.js +0 -374
  146. package/dist/memory/layers/static-content.d.ts +0 -27
  147. package/dist/memory/layers/static-content.js +0 -35
  148. package/dist/memory/layers/steering.d.ts +0 -51
  149. package/dist/memory/layers/steering.js +0 -258
  150. package/dist/memory/layers/temporal.d.ts +0 -91
  151. package/dist/memory/layers/temporal.js +0 -245
  152. package/dist/memory/layers/tool-memory-layer.d.ts +0 -16
  153. package/dist/memory/layers/tool-memory-layer.js +0 -43
  154. package/dist/memory/layers/working-memory.d.ts +0 -44
  155. package/dist/memory/layers/working-memory.js +0 -92
  156. package/dist/memory/projector.d.ts +0 -10
  157. package/dist/memory/projector.js +0 -19
  158. package/dist/memory/scope.d.ts +0 -3
  159. package/dist/memory/scope.js +0 -31
  160. package/dist/memory/strip-unresolved.d.ts +0 -13
  161. package/dist/memory/strip-unresolved.js +0 -35
  162. package/dist/schemas/item.d.ts +0 -35
  163. package/dist/schemas/item.js +0 -155
  164. package/dist/types/channel.d.ts +0 -29
  165. package/dist/types/channel.js +0 -1
  166. package/dist/types/common.d.ts +0 -68
  167. package/dist/types/common.js +0 -1
  168. package/dist/types/context-parts/item-log.d.ts +0 -6
  169. package/dist/types/context-parts/item-log.js +0 -1
  170. package/dist/types/context-parts/layer-usage.d.ts +0 -18
  171. package/dist/types/context-parts/layer-usage.js +0 -1
  172. package/dist/types/context.d.ts +0 -202
  173. package/dist/types/context.js +0 -1
  174. package/dist/types/detached.d.ts +0 -17
  175. package/dist/types/detached.js +0 -7
  176. package/dist/types/error.d.ts +0 -66
  177. package/dist/types/error.js +0 -1
  178. package/dist/types/fs-adapter.d.ts +0 -51
  179. package/dist/types/fs-adapter.js +0 -3
  180. package/dist/types/harness-result.d.ts +0 -43
  181. package/dist/types/harness-result.js +0 -2
  182. package/dist/types/items.d.ts +0 -131
  183. package/dist/types/items.js +0 -2
  184. package/dist/types/memory-context.d.ts +0 -39
  185. package/dist/types/memory-context.js +0 -1
  186. package/dist/types/memory.d.ts +0 -306
  187. package/dist/types/memory.js +0 -13
  188. package/dist/types/observability.d.ts +0 -30
  189. package/dist/types/observability.js +0 -1
  190. package/dist/types/runtime.d.ts +0 -256
  191. package/dist/types/runtime.js +0 -1
  192. package/dist/types/shell-adapter.d.ts +0 -34
  193. package/dist/types/shell-adapter.js +0 -10
  194. package/dist/types/steering.d.ts +0 -89
  195. package/dist/types/steering.js +0 -14
  196. package/dist/types/step.d.ts +0 -231
  197. package/dist/types/step.js +0 -1
  198. package/dist/types/subprocess-adapter.d.ts +0 -157
  199. package/dist/types/subprocess-adapter.js +0 -3
  200. package/dist/types/tool-context.d.ts +0 -34
  201. package/dist/types/tool-context.js +0 -1
  202. package/dist/types/tool.d.ts +0 -64
  203. package/dist/types/tool.js +0 -1
  204. package/dist/util/framework-cast.d.ts +0 -10
  205. package/dist/util/framework-cast.js +0 -16
  206. package/dist/util/message-helpers.d.ts +0 -17
  207. package/dist/util/message-helpers.js +0 -64
@@ -1,117 +0,0 @@
1
- import { NoeticErrorImpl } from '../errors/noetic-error.js';
2
- function extractMin(config) {
3
- if (config && typeof config === 'object' && 'min' in config) {
4
- return config.min;
5
- }
6
- return 0;
7
- }
8
- function extractMax(config) {
9
- if (config === 'auto') {
10
- return Number.POSITIVE_INFINITY;
11
- }
12
- if (typeof config === 'number') {
13
- return config;
14
- }
15
- if (config && typeof config === 'object' && 'min' in config) {
16
- return config.max;
17
- }
18
- return 0;
19
- }
20
- function computeShare({ headroom, layerPool, infiniteCount, finiteTotal, totalMax, allHeadrooms, layerIndex, }) {
21
- if (!Number.isFinite(headroom)) {
22
- // All infinite-headroom layers split the pool after finite layers take their share.
23
- // `infiniteCount >= 1` is guaranteed here since headroom is infinite.
24
- const finiteUsed = Number.isFinite(totalMax)
25
- ? 0
26
- : allHeadrooms.reduce((sum, m, j) => Number.isFinite(m) && j !== layerIndex
27
- ? sum + Math.min(m, (m / (finiteTotal || 1)) * layerPool)
28
- : sum, 0);
29
- return (layerPool - finiteUsed) / infiniteCount;
30
- }
31
- if (Number.isFinite(totalMax)) {
32
- return (headroom / totalMax) * layerPool;
33
- }
34
- // Mix of finite and infinite: finite layers share half the pool proportionally.
35
- return finiteTotal > 0 ? (headroom / finiteTotal) * (layerPool * 0.5) : 0;
36
- }
37
- export function allocateBudgets({ layers, totalBudget, systemPromptTokens, responseReserve, }) {
38
- const available = totalBudget - responseReserve - systemPromptTokens;
39
- if (available <= 0) {
40
- return {
41
- allocations: layers.map((l) => ({
42
- layerId: l.id,
43
- allocated: 0,
44
- })),
45
- historyBudget: 0,
46
- };
47
- }
48
- // Phase 1: satisfy minimums
49
- let remaining = available;
50
- const allocations = [];
51
- for (const layer of layers) {
52
- const min = extractMin(layer.budget);
53
- allocations.push({
54
- layerId: layer.id,
55
- allocated: min,
56
- });
57
- remaining -= min;
58
- }
59
- // Phase 2: distribute 60% of remaining to layers proportionally, 40% to history
60
- const layerPool = remaining * 0.6;
61
- const historyBudget = remaining * 0.4;
62
- // Compute headroom per layer (how much above the minimum each layer can absorb)
63
- let totalMax = 0;
64
- const headrooms = [];
65
- for (let i = 0; i < layers.length; i++) {
66
- const max = extractMax(layers[i].budget);
67
- const headroom = Math.max(0, max - allocations[i].allocated);
68
- headrooms.push(headroom);
69
- totalMax += headroom;
70
- }
71
- if (totalMax > 0) {
72
- const infiniteCount = headrooms.filter((h) => !Number.isFinite(h)).length;
73
- const finiteTotal = headrooms.reduce((sum, h) => (Number.isFinite(h) ? sum + h : sum), 0);
74
- for (let i = 0; i < headrooms.length; i++) {
75
- const share = computeShare({
76
- headroom: headrooms[i],
77
- layerPool,
78
- infiniteCount,
79
- finiteTotal,
80
- totalMax,
81
- allHeadrooms: headrooms,
82
- layerIndex: i,
83
- });
84
- allocations[i].allocated += Math.min(share, headrooms[i]);
85
- }
86
- }
87
- return {
88
- allocations,
89
- historyBudget: Math.max(0, historyBudget),
90
- };
91
- }
92
- export function checkBudget(ctx, limits) {
93
- if (limits.maxCost !== undefined && ctx.cost > limits.maxCost) {
94
- throw new NoeticErrorImpl({
95
- kind: 'budget_exceeded',
96
- field: 'cost',
97
- limit: limits.maxCost,
98
- actual: ctx.cost,
99
- });
100
- }
101
- if (limits.maxSteps !== undefined && ctx.stepCount > limits.maxSteps) {
102
- throw new NoeticErrorImpl({
103
- kind: 'budget_exceeded',
104
- field: 'steps',
105
- limit: limits.maxSteps,
106
- actual: ctx.stepCount,
107
- });
108
- }
109
- if (limits.maxDuration !== undefined && ctx.elapsed > limits.maxDuration) {
110
- throw new NoeticErrorImpl({
111
- kind: 'budget_exceeded',
112
- field: 'duration',
113
- limit: limits.maxDuration,
114
- actual: ctx.elapsed,
115
- });
116
- }
117
- }
@@ -1,25 +0,0 @@
1
- import type { Context } from '../types/context.js';
2
- import type { ExecutionContext } from '../types/memory.js';
3
- /**
4
- * Optional overrides for `contextToExecCtx`. Used by `executeSpawn` to build
5
- * parent and child execution contexts that reuse the same tokenize / trace /
6
- * layer-state wiring as the main path, but with spawn-specific identity
7
- * (`executionId`, `depth`, `stepNumber`, and the scope used for layer-state
8
- * reads).
9
- */
10
- export interface ExecCtxOverrides {
11
- callModel?: ExecutionContext['callModel'];
12
- executionId?: string;
13
- depth?: number;
14
- stepNumber?: number;
15
- tokenUsage?: ExecutionContext['tokenUsage'];
16
- cost?: number;
17
- /** Execution id to scope `readLayerState` to (defaults to `ctx.id`). */
18
- readLayerStateId?: string;
19
- }
20
- /**
21
- * Maps a full `Context` to the lightweight `ExecutionContext` consumed by memory layer hooks.
22
- * Centralised here so the mapping stays consistent across agent-harness, layer-api, and the
23
- * spawn interpreter.
24
- */
25
- export declare function contextToExecCtx(ctx: Context, overrides?: ExecCtxOverrides): ExecutionContext;
@@ -1,30 +0,0 @@
1
- import { estimateTokens } from '../util/message-helpers.js';
2
- /**
3
- * Maps a full `Context` to the lightweight `ExecutionContext` consumed by memory 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
- }
@@ -1,52 +0,0 @@
1
- /**
2
- * Zod schema for plan-mode flow JSON.
3
- *
4
- * A "flow" is a JSON-serialisable subset of noetic's `Step` shape that the model
5
- * may emit during plan mode. The runtime expands each node into a concrete `Step`
6
- * via the existing builders (`step.llm`, `fork`, `spawn`) at execute time.
7
- *
8
- * Tool references inside `llm` nodes are name strings. They get resolved against
9
- * the harness's live tool registry when the flow runs.
10
- */
11
- import { z } from 'zod';
12
- interface NodeBase {
13
- id: string;
14
- subPlanRef?: string;
15
- }
16
- export interface LlmFlowNode extends NodeBase {
17
- kind: 'llm';
18
- model?: string;
19
- instructions: string;
20
- tools?: string[];
21
- }
22
- export interface SubagentFlowNode extends NodeBase {
23
- kind: 'subagent';
24
- preset: string;
25
- prompt: string;
26
- }
27
- export interface ForkFlowNode extends NodeBase {
28
- kind: 'fork';
29
- mode: 'all' | 'race' | 'settle';
30
- paths: FlowNode[];
31
- }
32
- export interface SpawnFlowNode extends NodeBase {
33
- kind: 'spawn';
34
- child: FlowNode;
35
- }
36
- export interface SequenceFlowNode extends NodeBase {
37
- kind: 'sequence';
38
- steps: FlowNode[];
39
- }
40
- export type FlowNode = LlmFlowNode | SubagentFlowNode | ForkFlowNode | SpawnFlowNode | SequenceFlowNode;
41
- /** Top-level flow document: a single root node. */
42
- export declare const FlowSchema: z.ZodType<FlowNode, unknown, z.core.$ZodTypeInternals<FlowNode, unknown>>;
43
- /** Validates a candidate flow document. Throws `ZodError` on invalid input. */
44
- export declare function validateFlow(input: unknown): FlowNode;
45
- /** Walks a flow tree depth-first, yielding each node. */
46
- export declare function walkFlow(root: FlowNode): Iterable<FlowNode>;
47
- /**
48
- * Returns the maximum depth of a flow tree. A leaf (llm/subagent) is depth 0.
49
- * Structural nodes (sequence/fork/spawn) contribute +1 over their deepest child.
50
- */
51
- export declare function flowDepth(node: FlowNode): number;
52
- export {};
@@ -1,102 +0,0 @@
1
- /**
2
- * Zod schema for plan-mode flow JSON.
3
- *
4
- * A "flow" is a JSON-serialisable subset of noetic's `Step` shape that the model
5
- * may emit during plan mode. The runtime expands each node into a concrete `Step`
6
- * via the existing builders (`step.llm`, `fork`, `spawn`) at execute time.
7
- *
8
- * Tool references inside `llm` nodes are name strings. They get resolved against
9
- * the harness's live tool registry when the flow runs.
10
- */
11
- import { z } from 'zod';
12
- //#endregion
13
- //#region Schema
14
- const FlowNodeRef = z.lazy(() => FlowNodeSchema);
15
- const SHARED_FIELDS = {
16
- id: z.string().min(1),
17
- subPlanRef: z.string().optional(),
18
- };
19
- const LlmNodeSchema = z.object({
20
- kind: z.literal('llm'),
21
- ...SHARED_FIELDS,
22
- model: z.string().optional(),
23
- instructions: z.string(),
24
- tools: z.array(z.string()).optional(),
25
- });
26
- const SubagentNodeSchema = z.object({
27
- kind: z.literal('subagent'),
28
- ...SHARED_FIELDS,
29
- preset: z.string().min(1),
30
- prompt: z.string(),
31
- });
32
- const ForkNodeSchema = z.object({
33
- kind: z.literal('fork'),
34
- ...SHARED_FIELDS,
35
- mode: z.enum([
36
- 'all',
37
- 'race',
38
- 'settle',
39
- ]),
40
- paths: z.array(FlowNodeRef).min(1),
41
- });
42
- const SpawnNodeSchema = z.object({
43
- kind: z.literal('spawn'),
44
- ...SHARED_FIELDS,
45
- child: FlowNodeRef,
46
- });
47
- const SequenceNodeSchema = z.object({
48
- kind: z.literal('sequence'),
49
- ...SHARED_FIELDS,
50
- steps: z.array(FlowNodeRef).min(1),
51
- });
52
- const FlowNodeSchema = z.discriminatedUnion('kind', [
53
- LlmNodeSchema,
54
- SubagentNodeSchema,
55
- ForkNodeSchema,
56
- SpawnNodeSchema,
57
- SequenceNodeSchema,
58
- ]);
59
- /** Top-level flow document: a single root node. */
60
- export const FlowSchema = FlowNodeSchema;
61
- //#endregion
62
- //#region Public API
63
- /** Validates a candidate flow document. Throws `ZodError` on invalid input. */
64
- export function validateFlow(input) {
65
- return FlowSchema.parse(input);
66
- }
67
- /** Walks a flow tree depth-first, yielding each node. */
68
- export function* walkFlow(root) {
69
- yield root;
70
- if (root.kind === 'fork') {
71
- for (const path of root.paths) {
72
- yield* walkFlow(path);
73
- }
74
- return;
75
- }
76
- if (root.kind === 'sequence') {
77
- for (const step of root.steps) {
78
- yield* walkFlow(step);
79
- }
80
- return;
81
- }
82
- if (root.kind === 'spawn') {
83
- yield* walkFlow(root.child);
84
- }
85
- }
86
- /**
87
- * Returns the maximum depth of a flow tree. A leaf (llm/subagent) is depth 0.
88
- * Structural nodes (sequence/fork/spawn) contribute +1 over their deepest child.
89
- */
90
- export function flowDepth(node) {
91
- if (node.kind === 'sequence') {
92
- return 1 + Math.max(0, ...node.steps.map(flowDepth));
93
- }
94
- if (node.kind === 'fork') {
95
- return 1 + Math.max(0, ...node.paths.map(flowDepth));
96
- }
97
- if (node.kind === 'spawn') {
98
- return 1 + flowDepth(node.child);
99
- }
100
- return 0;
101
- }
102
- //#endregion
@@ -1,6 +0,0 @@
1
- import type { Item } from '../types/items.js';
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;
@@ -1,27 +0,0 @@
1
- import { frameworkCast } from '../util/framework-cast.js';
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
- }
@@ -1,14 +0,0 @@
1
- import type { Context } from '../types/context.js';
2
- import type { ContextMemory, MemoryLayer } from '../types/memory.js';
3
- import type { AgentHarnessContract } from '../types/runtime.js';
4
- import type { Tool } from '../types/tool.js';
5
- /**
6
- * Build the `ctx.memory` object — a readonly map of layer ID → resolved handle.
7
- * Handles use getters for data (live reads) and closures for functions (lazy state).
8
- */
9
- export declare function buildContextMemory(layers: ReadonlyArray<MemoryLayer>, ctx: Context): ContextMemory;
10
- /**
11
- * Collect all `provides` function declarations from active layers and convert them to Tools.
12
- * Tool names are namespaced as `layerId/functionName`.
13
- */
14
- export declare function resolveLayerTools(layers: ReadonlyArray<MemoryLayer>, harness: AgentHarnessContract, ctx: Context): Tool[];
@@ -1,91 +0,0 @@
1
- import { frameworkCast } from '../util/framework-cast.js';
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 Memory
46
- /**
47
- * Build the `ctx.memory` 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 buildContextMemory(layers, ctx) {
51
- const memory = {};
52
- for (const layer of layers) {
53
- memory[layer.id] = buildLayerHandle(layer, ctx);
54
- }
55
- return frameworkCast(memory);
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
@@ -1,160 +0,0 @@
1
- import type { ItemSchemaRegistry } from '../schemas/item.js';
2
- import type { LLMResponse } from '../types/common.js';
3
- import type { ItemLog } from '../types/context-parts/item-log.js';
4
- import type { Item } from '../types/items.js';
5
- import type { ExecutionContext, MemoryLayer, StorageAdapter } from '../types/memory.js';
6
- import type { SteeringDecision } from '../types/steering.js';
7
- export interface LayerStateStore {
8
- get<T>(executionId: string, layerId: string): T | undefined;
9
- set<T>(executionId: string, layerId: string, state: T): void;
10
- cleanup(executionId: string): void;
11
- diagnostic: (layerId: string, hook: string, error: unknown) => void;
12
- }
13
- interface InitLayersParams {
14
- layers: MemoryLayer[];
15
- ctx: ExecutionContext;
16
- storage: StorageAdapter;
17
- store: LayerStateStore;
18
- }
19
- interface RecallLayersParams {
20
- layers: MemoryLayer[];
21
- query: string;
22
- ctx: ExecutionContext;
23
- log: ItemLog;
24
- budgets: Map<string, number>;
25
- store: LayerStateStore;
26
- itemSchemas?: ItemSchemaRegistry;
27
- }
28
- interface StoreLayersParams {
29
- layers: MemoryLayer[];
30
- response: LLMResponse;
31
- ctx: ExecutionContext;
32
- log: ItemLog;
33
- store: LayerStateStore;
34
- storage: StorageAdapter;
35
- }
36
- interface SpawnLayersParams {
37
- layers: MemoryLayer[];
38
- parentCtx: ExecutionContext;
39
- childCtx: ExecutionContext;
40
- store: LayerStateStore;
41
- itemSchemas?: ItemSchemaRegistry;
42
- }
43
- interface ReturnLayersParams<T = unknown> {
44
- layers: MemoryLayer[];
45
- parentCtx: ExecutionContext;
46
- childCtx: ExecutionContext;
47
- childLog: ItemLog;
48
- result: T;
49
- store: LayerStateStore;
50
- }
51
- interface CompleteLayersParams {
52
- layers: MemoryLayer[];
53
- ctx: ExecutionContext;
54
- log: ItemLog;
55
- outcome: 'success' | 'failure' | 'aborted';
56
- store: LayerStateStore;
57
- }
58
- interface DisposeLayersParams {
59
- layers: MemoryLayer[];
60
- ctx: ExecutionContext;
61
- store: LayerStateStore;
62
- }
63
- interface BeforeToolCallLayersParams {
64
- layers: MemoryLayer[];
65
- toolName: string;
66
- toolArgs: unknown;
67
- ctx: ExecutionContext;
68
- store: LayerStateStore;
69
- }
70
- interface AfterModelCallLayersParams {
71
- layers: MemoryLayer[];
72
- response: LLMResponse;
73
- ctx: ExecutionContext;
74
- store: LayerStateStore;
75
- }
76
- interface ProjectHistoryLayersParams {
77
- layers: MemoryLayer[];
78
- items: ReadonlyArray<Item>;
79
- ctx: ExecutionContext;
80
- store: LayerStateStore;
81
- }
82
- /** @public A request to re-render the context window, collected from onItemAppend hooks. */
83
- export interface RerenderRequest {
84
- layerId: string;
85
- slot: number;
86
- timing: 'immediate' | 'batched';
87
- scope: 'self' | 'slot-after' | 'all';
88
- }
89
- /** @public Result of running items through the onItemAppend pipeline. */
90
- export interface AppendPipelineResult {
91
- /** Final items to append after all transformations. */
92
- items: Item[];
93
- /** Re-render requests collected from layers. */
94
- rerenderRequests: RerenderRequest[];
95
- }
96
- interface RunAppendPipelineParams {
97
- layers: MemoryLayer[];
98
- items: Item[];
99
- ctx: ExecutionContext;
100
- log: ItemLog;
101
- store: LayerStateStore;
102
- }
103
- interface ExecuteRerenderParams {
104
- requests: RerenderRequest[];
105
- layers: MemoryLayer[];
106
- ctx: ExecutionContext;
107
- log: ItemLog;
108
- budgets: Map<string, number>;
109
- store: LayerStateStore;
110
- itemSchemas?: ItemSchemaRegistry;
111
- /** Query for context-aware recall (e.g., last user message) */
112
- query?: string;
113
- /** Current re-render depth (for loop protection) */
114
- depth?: number;
115
- }
116
- /** Resolve each layer's `BudgetConfig` to a concrete token budget for recall. */
117
- export declare function resolveLayerBudgets(layers: ReadonlyArray<MemoryLayer>): Map<string, number>;
118
- export declare function createLayerStateStore(diagnostic?: (layerId: string, hook: string, error: unknown) => void): LayerStateStore;
119
- export declare function mostRestrictive(decisions: SteeringDecision[]): SteeringDecision;
120
- export declare function initLayers({ layers, ctx, storage, store }: InitLayersParams): Promise<void>;
121
- export declare function recallLayers({ layers, query, ctx, log, budgets, store, itemSchemas, }: RecallLayersParams): Promise<{
122
- layerId: string;
123
- items: Item[];
124
- tokenCount: number;
125
- }[]>;
126
- export declare function storeLayers({ layers, response, ctx, log, store, storage, }: StoreLayersParams): Promise<void>;
127
- export declare function disposeLayers({ layers, ctx, store }: DisposeLayersParams): Promise<void>;
128
- export declare function spawnLayers({ layers, parentCtx, childCtx, store, itemSchemas, }: SpawnLayersParams): Promise<{
129
- layerId: string;
130
- childState: unknown;
131
- items: Item[];
132
- }[]>;
133
- export declare function returnLayers<T>({ layers, parentCtx, childCtx, childLog, result, store, }: ReturnLayersParams<T>): Promise<T>;
134
- export declare function completeLayers({ layers, ctx, log, outcome, store, }: CompleteLayersParams): Promise<void>;
135
- export declare function beforeToolCallLayers({ layers, toolName, toolArgs, ctx, store, }: BeforeToolCallLayersParams): Promise<SteeringDecision>;
136
- export declare function afterModelCallLayers({ layers, response, ctx, store, }: AfterModelCallLayersParams): Promise<SteeringDecision>;
137
- /**
138
- * Run history items through every layer's `projectHistory` hook in slot order.
139
- * Each layer receives the previous layer's output. Storage (`itemLog`) is
140
- * never mutated — this is a pure projection over the input array. Returns
141
- * the projected items unchanged when no layer registers the hook.
142
- */
143
- export declare function projectHistoryLayers({ layers, items, ctx, store, }: ProjectHistoryLayersParams): Promise<ReadonlyArray<Item>>;
144
- /**
145
- * Run items through the onItemAppend pipeline.
146
- * Each layer can filter, transform, or inject items.
147
- * Returns final items to append and any re-render requests.
148
- */
149
- export declare function runAppendPipeline({ layers, items, ctx, log, store, }: RunAppendPipelineParams): Promise<AppendPipelineResult>;
150
- /**
151
- * Execute re-render based on collected requests.
152
- * Determines which layers need re-recall based on scope and runs them.
153
- * Returns new recall results to merge into view.
154
- */
155
- export declare function executeRerender({ requests, layers, ctx, log, budgets, store, itemSchemas, query, depth, }: ExecuteRerenderParams): Promise<{
156
- layerId: string;
157
- items: Item[];
158
- tokenCount: number;
159
- }[]>;
160
- export {};