@telorun/kernel 0.60.0 → 0.61.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.
- package/dist/controllers/resource-definition/resource-inherited-controller.d.ts.map +1 -1
- package/dist/controllers/resource-definition/resource-inherited-controller.js +57 -10
- package/dist/controllers/resource-definition/resource-inherited-controller.js.map +1 -1
- package/dist/controllers/type/json-schema-controller.d.ts +8 -0
- package/dist/controllers/type/json-schema-controller.d.ts.map +1 -0
- package/dist/controllers/type/json-schema-controller.js +91 -0
- package/dist/controllers/type/json-schema-controller.js.map +1 -0
- package/dist/evaluation-context.d.ts +5 -0
- package/dist/evaluation-context.d.ts.map +1 -1
- package/dist/evaluation-context.js +63 -33
- package/dist/evaluation-context.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/init-failure-diagnostics.d.ts +61 -0
- package/dist/init-failure-diagnostics.d.ts.map +1 -0
- package/dist/init-failure-diagnostics.js +141 -0
- package/dist/init-failure-diagnostics.js.map +1 -0
- package/dist/invocation-contract-binding.d.ts +105 -0
- package/dist/invocation-contract-binding.d.ts.map +1 -0
- package/dist/invocation-contract-binding.js +296 -0
- package/dist/invocation-contract-binding.js.map +1 -0
- package/dist/kernel.d.ts +17 -0
- package/dist/kernel.d.ts.map +1 -1
- package/dist/kernel.js +62 -5
- package/dist/kernel.js.map +1 -1
- package/dist/module-context.d.ts.map +1 -1
- package/dist/module-context.js +21 -0
- package/dist/module-context.js.map +1 -1
- package/dist/resource-context.d.ts +45 -0
- package/dist/resource-context.d.ts.map +1 -1
- package/dist/resource-context.js +79 -0
- package/dist/resource-context.js.map +1 -1
- package/dist/schema-compiled-values.d.ts +9 -1
- package/dist/schema-compiled-values.d.ts.map +1 -1
- package/dist/schema-compiled-values.js +55 -16
- package/dist/schema-compiled-values.js.map +1 -1
- package/dist/schema-validator.d.ts.map +1 -1
- package/dist/schema-validator.js +15 -1
- package/dist/schema-validator.js.map +1 -1
- package/package.json +3 -3
- package/src/controllers/resource-definition/resource-inherited-controller.ts +69 -10
- package/src/controllers/type/json-schema-controller.ts +114 -0
- package/src/evaluation-context.ts +81 -32
- package/src/index.ts +1 -0
- package/src/init-failure-diagnostics.ts +169 -0
- package/src/invocation-contract-binding.ts +392 -0
- package/src/kernel.ts +83 -6
- package/src/module-context.ts +27 -0
- package/src/resource-context.ts +81 -0
- package/src/schema-compiled-values.ts +55 -15
- package/src/schema-validator.ts +15 -1
|
@@ -0,0 +1,392 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type ContractDirection,
|
|
3
|
+
defaultBearingPaths,
|
|
4
|
+
effectiveContractField,
|
|
5
|
+
type DefResolver,
|
|
6
|
+
withStreamPropertiesSkipped,
|
|
7
|
+
} from "@telorun/analyzer";
|
|
8
|
+
import type { ResourceDefinition, ResourceInstance, ResourceManifest } from "@telorun/sdk";
|
|
9
|
+
import {
|
|
10
|
+
ERR_CONTRACT_UNRESOLVABLE,
|
|
11
|
+
ERR_INPUT_INVALID,
|
|
12
|
+
ERR_OUTPUT_INVALID,
|
|
13
|
+
InvokeError,
|
|
14
|
+
} from "@telorun/sdk";
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Binds a resource's resolved invocation contract to its dispatch entry points,
|
|
18
|
+
* at the moment the kernel produces the instance.
|
|
19
|
+
*
|
|
20
|
+
* A contract is only a guarantee if it cannot be dispatched around, and most
|
|
21
|
+
* consumers never reach the kernel's dispatch chokepoint: Phase-5 injection puts
|
|
22
|
+
* the live instance straight into a consumer's config object, so `Ai.Agent`
|
|
23
|
+
* reads `this.resource.model` and calls `model.invoke(...)` in hand. Enforcing at
|
|
24
|
+
* a handoff would mean enforcing at every handoff — Phase-5 injection,
|
|
25
|
+
* `ctx.resolveRef`, scope-handle resolution, the template controller's direct
|
|
26
|
+
* dispatch, `ctx.invoke`'s target lookup — and one forgotten site silently
|
|
27
|
+
* reopens the hole.
|
|
28
|
+
*
|
|
29
|
+
* So the kernel binds instead, at `_createInstance`: its single production site.
|
|
30
|
+
* Every consumer, on every path, then holds an instance whose dispatch already
|
|
31
|
+
* enforces. Binding rather than wrapping is also what keeps the rest a
|
|
32
|
+
* non-problem — there is one object, so controller-specific members are
|
|
33
|
+
* genuinely its own, the prototype chain (and `instanceof` across the SDK realm
|
|
34
|
+
* boundary) is untouched, and `stripCompiledValues` / `detachSnapshotValue` see
|
|
35
|
+
* exactly the object they always saw. It is the same in-place technique the
|
|
36
|
+
* kernel already uses to fold detached-task draining into `teardown()` and
|
|
37
|
+
* runtime CEL expansion into `invoke()`.
|
|
38
|
+
*
|
|
39
|
+
* Consequence, stated rather than left to be discovered: the bound `invoke`
|
|
40
|
+
* shadows the controller's, so a controller calling `this.invoke()` internally
|
|
41
|
+
* goes through its own contract.
|
|
42
|
+
*/
|
|
43
|
+
|
|
44
|
+
/** Compiles a JSON Schema to a validator. The kernel's `SchemaValidator` runs
|
|
45
|
+
* with `useDefaults`, so validating also fills declared defaults. */
|
|
46
|
+
export interface ContractValidatorFactory {
|
|
47
|
+
(typeRef: unknown): { validate(value: unknown): void };
|
|
48
|
+
/** Resolves a type field to its JSON Schema, for the schema-level decisions
|
|
49
|
+
* (stream skipping, default paths) a compiled validator can't answer. */
|
|
50
|
+
schemaOf(typeRef: unknown): Record<string, any> | undefined;
|
|
51
|
+
/** Resolves a `$ref` to the registered schema it names, so the schema walks
|
|
52
|
+
* can see through the reference form the compiled validator keeps intact. */
|
|
53
|
+
resolveRef(ref: string): Record<string, any> | undefined;
|
|
54
|
+
/** Compiles an adjusted schema while keeping the CEL `rules:` registered under
|
|
55
|
+
* a named type — the one path that survives stripping a stream property from
|
|
56
|
+
* a named contract without abandoning its invariants. */
|
|
57
|
+
withRules(name: string | undefined, schema: Record<string, any>): { validate(value: unknown): void };
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export interface BoundContract {
|
|
61
|
+
direction: ContractDirection;
|
|
62
|
+
validate(value: unknown): void;
|
|
63
|
+
/** Paths a default can be written to — how far the caller's value must be
|
|
64
|
+
* copied before validation runs. Empty when the contract declares none. */
|
|
65
|
+
defaultPaths(): string[][];
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const CONTRACT_ERROR: Record<ContractDirection, string> = {
|
|
69
|
+
inputType: ERR_INPUT_INVALID,
|
|
70
|
+
outputType: ERR_OUTPUT_INVALID,
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Resolve one direction of a resource's contract to a bound validator.
|
|
75
|
+
*
|
|
76
|
+
* The declaration is layered instance-manifest → nearest along `extends` (see
|
|
77
|
+
* `effectiveContractField` — nearest wins, contracts never merge), then compiled.
|
|
78
|
+
*
|
|
79
|
+
* A NAMED reference (`inputType: RequestShape`, or a `!ref` to a type) is
|
|
80
|
+
* compiled by name so it keeps the CEL `rules:` registered alongside it, which a
|
|
81
|
+
* plain schema copy would drop. Everything else is compiled from the resolved
|
|
82
|
+
* schema — inline `{kind, schema}` and raw forms carry no rules, and resolving
|
|
83
|
+
* first is what lets a `{ $ref: "telo://Self/X" }` contract compile at all
|
|
84
|
+
* (`resolveTypeSchema` follows it through the kernel's registry, which AJV
|
|
85
|
+
* cannot).
|
|
86
|
+
*
|
|
87
|
+
* The resolved schema is stripped of `x-telo-stream` properties first: a live
|
|
88
|
+
* `Stream` in a declared slot is not data to be traversed, the same defect as
|
|
89
|
+
* `stripCompiledValues` walking a live instance in a ref slot. Streams travel in
|
|
90
|
+
* both directions (`Codec.Encoder` marks `input` on its `inputType` and requires
|
|
91
|
+
* it), so the skip is not one-directional.
|
|
92
|
+
*
|
|
93
|
+
* WHICH declaration applies is decided here, at create time — that is a fact
|
|
94
|
+
* about the manifest. COMPILING it is deferred to first dispatch and memoized: a
|
|
95
|
+
* contract may reference a named `telo#Type` whose `Type.JsonSchema` resource
|
|
96
|
+
* initializes later in the same multi-pass loop, and resolving it eagerly would
|
|
97
|
+
* make every contract-declaring kind depend on type-registration order. Nothing
|
|
98
|
+
* can dispatch before the loop finishes, so first-use is always late enough.
|
|
99
|
+
*/
|
|
100
|
+
/** True when a type field names a registered `telo#Type` — a bare name, or the
|
|
101
|
+
* `{kind, name}` object a `!ref` normalizes to. Only these carry CEL `rules:`,
|
|
102
|
+
* so only these are worth compiling by name rather than from their schema. */
|
|
103
|
+
function isNamedTypeReference(declared: unknown): boolean {
|
|
104
|
+
if (typeof declared === "string") return true;
|
|
105
|
+
if (!declared || typeof declared !== "object") return false;
|
|
106
|
+
const ref = declared as Record<string, unknown>;
|
|
107
|
+
return typeof ref.name === "string" && !(ref.schema && typeof ref.schema === "object");
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export function resolveBoundContract(
|
|
111
|
+
direction: ContractDirection,
|
|
112
|
+
manifest: ResourceManifest,
|
|
113
|
+
definition: ResourceDefinition | undefined,
|
|
114
|
+
resolveDef: DefResolver,
|
|
115
|
+
factory: ContractValidatorFactory,
|
|
116
|
+
): BoundContract | undefined {
|
|
117
|
+
const own = (manifest as unknown as Record<string, unknown>)[direction];
|
|
118
|
+
const declared =
|
|
119
|
+
own !== undefined && own !== null
|
|
120
|
+
? own
|
|
121
|
+
: effectiveContractField(definition, resolveDef, direction);
|
|
122
|
+
if (declared === undefined || declared === null) return undefined;
|
|
123
|
+
|
|
124
|
+
let compiled: { validate(value: unknown): void } | undefined;
|
|
125
|
+
let paths: string[][] | undefined;
|
|
126
|
+
|
|
127
|
+
const resolve = (): { validate(value: unknown): void } => {
|
|
128
|
+
if (compiled !== undefined) return compiled;
|
|
129
|
+
const schema = factory.schemaOf(declared);
|
|
130
|
+
if (!schema) {
|
|
131
|
+
// A declared contract that resolves to nothing is a manifest fault — a
|
|
132
|
+
// named type that never registered — and it MUST NOT degrade to
|
|
133
|
+
// "unvalidated". Silently disabling enforcement is the failure mode
|
|
134
|
+
// nobody notices: every later call passes because nothing is checking.
|
|
135
|
+
throw new InvokeError(
|
|
136
|
+
ERR_CONTRACT_UNRESOLVABLE,
|
|
137
|
+
`declared \`${direction}\` could not be resolved to a schema: ${describeDeclaration(declared)}. ` +
|
|
138
|
+
`The type is not registered, so the contract cannot be enforced.`,
|
|
139
|
+
);
|
|
140
|
+
}
|
|
141
|
+
const stripped = withStreamPropertiesSkipped(schema, factory.resolveRef);
|
|
142
|
+
paths = defaultBearingPaths(stripped, factory.resolveRef);
|
|
143
|
+
// Compile by NAME whenever the declaration is one, so the type's CEL
|
|
144
|
+
// `rules:` are composed in — including when a stream had to be stripped, in
|
|
145
|
+
// which case the stream-bearing properties are dropped from the schema the
|
|
146
|
+
// named validator sees rather than the reference being abandoned.
|
|
147
|
+
compiled = !isNamedTypeReference(declared)
|
|
148
|
+
? factory(stripped)
|
|
149
|
+
: stripped === schema
|
|
150
|
+
? factory(declared)
|
|
151
|
+
: factory.withRules(nameOf(declared), stripped);
|
|
152
|
+
return compiled;
|
|
153
|
+
};
|
|
154
|
+
|
|
155
|
+
return {
|
|
156
|
+
direction,
|
|
157
|
+
validate: (value: unknown) => resolve().validate(value),
|
|
158
|
+
defaultPaths: () => {
|
|
159
|
+
resolve();
|
|
160
|
+
return paths ?? [];
|
|
161
|
+
},
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
const nameOf = (declared: unknown): string | undefined =>
|
|
166
|
+
typeof declared === "string"
|
|
167
|
+
? declared
|
|
168
|
+
: ((declared as Record<string, unknown> | null)?.name as string | undefined);
|
|
169
|
+
|
|
170
|
+
const describeDeclaration = (declared: unknown): string =>
|
|
171
|
+
typeof declared === "string" ? `'${declared}'` : JSON.stringify(declared);
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* A copy of `value` deep along exactly the paths a default can be written to and
|
|
175
|
+
* shared everywhere else.
|
|
176
|
+
*
|
|
177
|
+
* A flat shallow copy would not do: AJV's `useDefaults` writes at every level it
|
|
178
|
+
* finds a default, so a nested default would mutate the structure the caller
|
|
179
|
+
* still holds. Bounded by the schema's defaults rather than by the size of the
|
|
180
|
+
* payload — a contract declaring no defaults copies one level and nothing more.
|
|
181
|
+
*/
|
|
182
|
+
export function copyForDefaults(value: unknown, paths: readonly string[][]): unknown {
|
|
183
|
+
if (!value || typeof value !== "object") return value;
|
|
184
|
+
let out = shallowCopy(value);
|
|
185
|
+
for (const path of paths) {
|
|
186
|
+
// The leaf is what gets written; every CONTAINER above it is what must not
|
|
187
|
+
// be shared. An `[]` segment fans out: the default lands in each element, so
|
|
188
|
+
// the array and every element on the path have to be copied too — bailing
|
|
189
|
+
// there would leave `rows[0]` shared and let a fill mutate the caller's data.
|
|
190
|
+
out = copyAlong(out, path.slice(0, -1));
|
|
191
|
+
}
|
|
192
|
+
return out;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
const shallowCopy = (value: object): any =>
|
|
196
|
+
Array.isArray(value) ? [...value] : { ...(value as Record<string, unknown>) };
|
|
197
|
+
|
|
198
|
+
function copyAlong(node: unknown, segments: readonly string[]): unknown {
|
|
199
|
+
if (!node || typeof node !== "object") return node;
|
|
200
|
+
if (segments.length === 0) return node;
|
|
201
|
+
const [head, ...rest] = segments;
|
|
202
|
+
|
|
203
|
+
if (head === "[]") {
|
|
204
|
+
if (!Array.isArray(node)) return node;
|
|
205
|
+
return node.map((item) =>
|
|
206
|
+
item && typeof item === "object" ? copyAlong(shallowCopy(item), rest) : item,
|
|
207
|
+
);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
const container = node as Record<string, unknown>;
|
|
211
|
+
const child = container[head!];
|
|
212
|
+
if (!child || typeof child !== "object") return node;
|
|
213
|
+
container[head!] = copyAlong(shallowCopy(child), rest);
|
|
214
|
+
return node;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* Raise a contract violation as a structured {@link InvokeError}.
|
|
219
|
+
*
|
|
220
|
+
* Structured rather than a plain error because the run engine assigns
|
|
221
|
+
* `INTERNAL_ERROR` to anything that is not an `InvokeError` — a contract
|
|
222
|
+
* violation would then reach a `catch` block indistinguishable from a crash, and
|
|
223
|
+
* an author could neither match it nor rethrow it faithfully. These are ambient
|
|
224
|
+
* kernel codes: catchable by name, and never counted against a kind's own
|
|
225
|
+
* `throws:` union.
|
|
226
|
+
*
|
|
227
|
+
* The message names the target, the direction, and the offending detail, because
|
|
228
|
+
* a caller several steps away otherwise cannot tell which boundary rejected the
|
|
229
|
+
* value or which side supplied it.
|
|
230
|
+
*/
|
|
231
|
+
export function contractViolation(
|
|
232
|
+
direction: ContractDirection,
|
|
233
|
+
describeTarget: () => string,
|
|
234
|
+
cause: unknown,
|
|
235
|
+
): Error {
|
|
236
|
+
// A type's CEL `rules:` raise the author's OWN code — that is the whole point
|
|
237
|
+
// of declaring one, and `modules/type` documents rule codes as catchable.
|
|
238
|
+
// Only a structural schema failure is the ambient contract violation.
|
|
239
|
+
//
|
|
240
|
+
// Re-raised as a STRUCTURED error carrying that code: the rule itself throws a
|
|
241
|
+
// `RuntimeError`, which has a code but not the marker a catch block matches
|
|
242
|
+
// on, so it used to reach `catch` as the generic plain-failure code — the
|
|
243
|
+
// documented behaviour never actually worked. Wrapping preserves the code and
|
|
244
|
+
// makes it match.
|
|
245
|
+
const ruleCode = ruleViolationCode(cause);
|
|
246
|
+
if (ruleCode) {
|
|
247
|
+
return new InvokeError(ruleCode, (cause as Error).message, undefined, { cause });
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
const side = direction === "inputType" ? "inputs" : "result";
|
|
251
|
+
const detail = cause instanceof Error ? cause.message : String(cause);
|
|
252
|
+
return new InvokeError(
|
|
253
|
+
CONTRACT_ERROR[direction],
|
|
254
|
+
`${describeTarget()}: ${side} do not satisfy the declared ${direction}: ${detail}`,
|
|
255
|
+
undefined,
|
|
256
|
+
{ cause },
|
|
257
|
+
);
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** Codes the validator itself raises for a STRUCTURAL failure. Anything else
|
|
261
|
+
* carrying a code came from a declared rule and belongs to its author. */
|
|
262
|
+
const STRUCTURAL_VALIDATION_CODES = new Set([
|
|
263
|
+
"ERR_RESOURCE_SCHEMA_VALIDATION_FAILED",
|
|
264
|
+
"ERR_TYPE_NOT_FOUND",
|
|
265
|
+
]);
|
|
266
|
+
|
|
267
|
+
function ruleViolationCode(cause: unknown): string | undefined {
|
|
268
|
+
const code = (cause as { code?: unknown } | null)?.code;
|
|
269
|
+
if (typeof code !== "string" || code.length === 0) return undefined;
|
|
270
|
+
return STRUCTURAL_VALIDATION_CODES.has(code) ? undefined : code;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
export interface ContractBinding {
|
|
274
|
+
input?: BoundContract;
|
|
275
|
+
output?: BoundContract;
|
|
276
|
+
/** Names the resource in a violation message — the target, so a caller several
|
|
277
|
+
* steps away can tell which boundary rejected the value. */
|
|
278
|
+
describeTarget(): string;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* Bind `invoke()` and `provide()` in place.
|
|
283
|
+
*
|
|
284
|
+
* `provide()` takes no caller arguments, so it has no input side, but it returns
|
|
285
|
+
* a value against a declared `outputType` and that result is validated exactly as
|
|
286
|
+
* an invocable's is — same path, same stream skip, same ambient error code.
|
|
287
|
+
* `run()` is bound to nothing: parameterless and void, there is nothing to fill
|
|
288
|
+
* defaults into and no result to validate, so it is guarded statically instead.
|
|
289
|
+
*/
|
|
290
|
+
export function bindContract(instance: ResourceInstance, binding: ContractBinding): void {
|
|
291
|
+
const { input, output, describeTarget } = binding;
|
|
292
|
+
if (!input && !output) return;
|
|
293
|
+
|
|
294
|
+
if (typeof instance.invoke === "function") {
|
|
295
|
+
const original = instance.invoke.bind(instance) as (
|
|
296
|
+
inputs: any,
|
|
297
|
+
...rest: unknown[]
|
|
298
|
+
) => Promise<unknown>;
|
|
299
|
+
// EVERY argument is forwarded, not just `inputs`. `invoke(inputs, ctx)`
|
|
300
|
+
// carries the InvokeContext — cancellation, tracing — as its second
|
|
301
|
+
// parameter, and a wrapper that takes only `inputs` silently drops it: a
|
|
302
|
+
// detached body would then never see its cancellation token and a lease
|
|
303
|
+
// holding across it would never be released. The contract only concerns the
|
|
304
|
+
// first argument; the rest belong to the caller and the callee.
|
|
305
|
+
instance.invoke = async (inputs: any, ...rest: unknown[]) => {
|
|
306
|
+
let effective = inputs;
|
|
307
|
+
if (input) {
|
|
308
|
+
effective = copyForDefaults(inputs, input.defaultPaths());
|
|
309
|
+
// Validate a BIGINT-NORMALIZED view, not the values themselves. CEL
|
|
310
|
+
// evaluates an integer literal to a BigInt, which a JSON Schema
|
|
311
|
+
// validator does not recognise as `integer` — so every computed integer
|
|
312
|
+
// reaching a declared integer input would be rejected for a reason the
|
|
313
|
+
// author cannot act on. The dispatched values keep their BigInts, since
|
|
314
|
+
// a controller may need the full 64-bit range.
|
|
315
|
+
const view = withBigIntsAsNumbers(effective);
|
|
316
|
+
try {
|
|
317
|
+
input.validate(view);
|
|
318
|
+
} catch (error) {
|
|
319
|
+
throw contractViolation("inputType", describeTarget, error);
|
|
320
|
+
}
|
|
321
|
+
// Defaults are additive, so anything the validator filled into the view
|
|
322
|
+
// is a key the caller omitted — copy exactly those back.
|
|
323
|
+
effective = mergeFilledDefaults(effective, view);
|
|
324
|
+
}
|
|
325
|
+
const result = await original(effective, ...rest);
|
|
326
|
+
if (output) {
|
|
327
|
+
try {
|
|
328
|
+
output.validate(withBigIntsAsNumbers(result));
|
|
329
|
+
} catch (error) {
|
|
330
|
+
throw contractViolation("outputType", describeTarget, error);
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
return result;
|
|
334
|
+
};
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
if (output && typeof instance.provide === "function") {
|
|
338
|
+
const original = instance.provide.bind(instance) as (...args: unknown[]) => Promise<unknown>;
|
|
339
|
+
instance.provide = async (...args: unknown[]) => {
|
|
340
|
+
const result = await original(...args);
|
|
341
|
+
try {
|
|
342
|
+
output.validate(withBigIntsAsNumbers(result));
|
|
343
|
+
} catch (error) {
|
|
344
|
+
throw contractViolation("outputType", describeTarget, error);
|
|
345
|
+
}
|
|
346
|
+
return result;
|
|
347
|
+
};
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/** A structural copy with every BigInt rendered as a Number, for validation
|
|
352
|
+
* only. A value beyond the safe-integer range loses precision in the VIEW,
|
|
353
|
+
* which can only affect a bound check at the extremes; the dispatched value is
|
|
354
|
+
* untouched. Non-plain objects (a live `Stream`, a resource instance) pass
|
|
355
|
+
* through by reference — they are not data to be walked. */
|
|
356
|
+
export function withBigIntsAsNumbers(value: unknown): unknown {
|
|
357
|
+
if (typeof value === "bigint") return Number(value);
|
|
358
|
+
if (Array.isArray(value)) {
|
|
359
|
+
let changed = false;
|
|
360
|
+
const items = value.map((item) => {
|
|
361
|
+
const next = withBigIntsAsNumbers(item);
|
|
362
|
+
if (next !== item) changed = true;
|
|
363
|
+
return next;
|
|
364
|
+
});
|
|
365
|
+
return changed ? items : value;
|
|
366
|
+
}
|
|
367
|
+
if (!value || typeof value !== "object") return value;
|
|
368
|
+
if (Object.getPrototypeOf(value) !== Object.prototype) return value;
|
|
369
|
+
let changed = false;
|
|
370
|
+
const out: Record<string, unknown> = {};
|
|
371
|
+
for (const [key, item] of Object.entries(value as Record<string, unknown>)) {
|
|
372
|
+
const next = withBigIntsAsNumbers(item);
|
|
373
|
+
if (next !== item) changed = true;
|
|
374
|
+
out[key] = next;
|
|
375
|
+
}
|
|
376
|
+
return changed ? out : value;
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/** Copy keys the validator's default-fill added to `view` back onto `target`.
|
|
380
|
+
* Only ADDITIONS are taken: a key already present came from the caller and its
|
|
381
|
+
* original (possibly BigInt) value is the one to dispatch. */
|
|
382
|
+
function mergeFilledDefaults(target: unknown, view: unknown): unknown {
|
|
383
|
+
if (target === view) return target;
|
|
384
|
+
if (!target || typeof target !== "object" || Array.isArray(target)) return target;
|
|
385
|
+
if (!view || typeof view !== "object" || Array.isArray(view)) return target;
|
|
386
|
+
const out = target as Record<string, unknown>;
|
|
387
|
+
for (const [key, filled] of Object.entries(view as Record<string, unknown>)) {
|
|
388
|
+
if (!(key in out)) out[key] = filled;
|
|
389
|
+
else out[key] = mergeFilledDefaults(out[key], filled);
|
|
390
|
+
}
|
|
391
|
+
return out;
|
|
392
|
+
}
|
package/src/kernel.ts
CHANGED
|
@@ -6,9 +6,15 @@ import {
|
|
|
6
6
|
isModuleKind,
|
|
7
7
|
Loader,
|
|
8
8
|
StaticAnalyzer,
|
|
9
|
+
type DefResolver,
|
|
9
10
|
type LoadedGraph,
|
|
10
11
|
type ManifestSource,
|
|
11
12
|
} from "@telorun/analyzer";
|
|
13
|
+
import {
|
|
14
|
+
bindContract,
|
|
15
|
+
type ContractValidatorFactory,
|
|
16
|
+
resolveBoundContract,
|
|
17
|
+
} from "./invocation-contract-binding.js";
|
|
12
18
|
import {
|
|
13
19
|
ControllerContext,
|
|
14
20
|
ControllerPolicy,
|
|
@@ -348,6 +354,13 @@ export class Kernel implements IKernel {
|
|
|
348
354
|
"Telo.FileSink",
|
|
349
355
|
await import("./controllers/logging/file-sink-controller.js"),
|
|
350
356
|
);
|
|
357
|
+
// Data shapes are a kernel concern for the same reason: every kind with an
|
|
358
|
+
// invocation contract declares one, so `inputType:` must be writable without
|
|
359
|
+
// first importing a module.
|
|
360
|
+
this.controllers.registerController(
|
|
361
|
+
"Telo.JsonSchema",
|
|
362
|
+
await import("./controllers/type/json-schema-controller.js"),
|
|
363
|
+
);
|
|
351
364
|
}
|
|
352
365
|
|
|
353
366
|
/**
|
|
@@ -405,8 +418,8 @@ export class Kernel implements IKernel {
|
|
|
405
418
|
await this.loadBuiltinDefinitions();
|
|
406
419
|
|
|
407
420
|
// Phase 5: attach injection hook — fires between create() and init() for every resource
|
|
408
|
-
this.rootContext.preInitHook = (resource, getInstance, isPending) =>
|
|
409
|
-
this._injectDependencies(resource, getInstance, isPending);
|
|
421
|
+
this.rootContext.preInitHook = (resource, getInstance, isPending, owner) =>
|
|
422
|
+
this._injectDependencies(resource, getInstance, isPending, owner);
|
|
410
423
|
|
|
411
424
|
// Expose definition lookup so invoke()/invokeResolved() can check thrown
|
|
412
425
|
// InvokeError.code against the declared throw union (rule 9). Propagates
|
|
@@ -1264,6 +1277,19 @@ export class Kernel implements IKernel {
|
|
|
1264
1277
|
const instance = await controller.create(processedResource, ctx);
|
|
1265
1278
|
if (!instance) return null;
|
|
1266
1279
|
|
|
1280
|
+
// Bind the resolved invocation contract to the instance, here at the kernel's
|
|
1281
|
+
// single instance-production site — so every consumer holds an already
|
|
1282
|
+
// enforcing instance, including the majority that read a Phase-5-injected ref
|
|
1283
|
+
// straight off their own config and never reach a dispatch chokepoint.
|
|
1284
|
+
//
|
|
1285
|
+
// For a `base:` child this composes without a special case: the parent's
|
|
1286
|
+
// instance was produced by a nested `_createInstance` (so it is already bound
|
|
1287
|
+
// to the parent's contract), the inherited controller bound the `inputs:` /
|
|
1288
|
+
// `result:` mapping onto it, and this call binds the child's own contract
|
|
1289
|
+
// outermost. One dispatch then checks, in order: child inputs → mapping →
|
|
1290
|
+
// parent inputs → controller → parent result → mapping → child result.
|
|
1291
|
+
this.bindInvocationContract(instance, processedResource, resolvedKind, ctx);
|
|
1292
|
+
|
|
1267
1293
|
// Fold the resource's fire-and-forget drain into its own teardown: tearing
|
|
1268
1294
|
// the resource down drains the background tasks it spawned (the kernel just
|
|
1269
1295
|
// calls teardown() — it tracks no tasks itself). A drain with no pending
|
|
@@ -1282,14 +1308,58 @@ export class Kernel implements IKernel {
|
|
|
1282
1308
|
// init() on the wrapper would be invisible to the original invoke(), which still
|
|
1283
1309
|
// runs with `this === instance`. Mutating in place also preserves the prototype
|
|
1284
1310
|
// chain — class-declared methods remain reachable.
|
|
1311
|
+
// Every argument is forwarded: `invoke(inputs, ctx)` carries the
|
|
1312
|
+
// InvokeContext (cancellation, tracing) as its second parameter, and a
|
|
1313
|
+
// wrapper that declares only `inputs` silently drops it.
|
|
1285
1314
|
const originalInvoke = instance.invoke!.bind(instance);
|
|
1286
|
-
instance.invoke = async (inputs: any) => {
|
|
1315
|
+
instance.invoke = async (inputs: any, ...rest: unknown[]) => {
|
|
1287
1316
|
const expanded = evalContext.expandPaths(inputs as Record<string, unknown>, runtime);
|
|
1288
|
-
return originalInvoke(expanded);
|
|
1317
|
+
return (originalInvoke as (i: any, ...r: unknown[]) => Promise<unknown>)(expanded, ...rest);
|
|
1289
1318
|
};
|
|
1290
1319
|
return { instance, ctx, resource: processedResource };
|
|
1291
1320
|
}
|
|
1292
1321
|
|
|
1322
|
+
/**
|
|
1323
|
+
* Resolve and bind both directions of a resource's invocation contract.
|
|
1324
|
+
*
|
|
1325
|
+
* The declaration is layered instance-manifest → nearest along `extends`;
|
|
1326
|
+
* contracts never merge (a call signature is not additive the way construction
|
|
1327
|
+
* config is), so a definition that declares one fully replaces its ancestor's.
|
|
1328
|
+
* Resolution runs in the scope that DECLARED each definition — an `extends`
|
|
1329
|
+
* alias is lexical, and a `telo#Type` reference goes through import aliases, so
|
|
1330
|
+
* a chain crossing module boundaries re-scopes at every hop.
|
|
1331
|
+
*/
|
|
1332
|
+
private bindInvocationContract(
|
|
1333
|
+
instance: ResourceInstance,
|
|
1334
|
+
resource: ResourceManifest,
|
|
1335
|
+
resolvedKind: string,
|
|
1336
|
+
ctx: ResourceContext,
|
|
1337
|
+
): void {
|
|
1338
|
+
const definition = this.controllers.getDefinition(resolvedKind);
|
|
1339
|
+
if (!definition) return;
|
|
1340
|
+
|
|
1341
|
+
const impl = ctx as ResourceContextImpl;
|
|
1342
|
+
const factory = Object.assign((typeRef: unknown) => impl.createTypeValidator(typeRef as any), {
|
|
1343
|
+
schemaOf: (typeRef: unknown) => impl.resolveTypeSchema(typeRef),
|
|
1344
|
+
resolveRef: (ref: string) => impl.lookupSchema(ref) as Record<string, any> | undefined,
|
|
1345
|
+
withRules: (name: string | undefined, schema: Record<string, any>) =>
|
|
1346
|
+
impl.createTypeValidatorWithRules(name, schema),
|
|
1347
|
+
}) as ContractValidatorFactory;
|
|
1348
|
+
|
|
1349
|
+
const resolveDef: DefResolver = (kind, from) =>
|
|
1350
|
+
this.registry.resolveDefinitionIn(kind, from?.metadata?.module);
|
|
1351
|
+
|
|
1352
|
+
const input = resolveBoundContract("inputType", resource, definition, resolveDef, factory);
|
|
1353
|
+
const output = resolveBoundContract("outputType", resource, definition, resolveDef, factory);
|
|
1354
|
+
if (!input && !output) return;
|
|
1355
|
+
|
|
1356
|
+
bindContract(instance, {
|
|
1357
|
+
input,
|
|
1358
|
+
output,
|
|
1359
|
+
describeTarget: () => `${resolvedKind}/${resource.metadata?.name ?? "<unnamed>"}`,
|
|
1360
|
+
});
|
|
1361
|
+
}
|
|
1362
|
+
|
|
1293
1363
|
/**
|
|
1294
1364
|
* Create phase for an inherited (concrete-`extends`) definition's parent: runs
|
|
1295
1365
|
* the ordinary create pipeline (controller resolution + lazy load, schema
|
|
@@ -1314,11 +1384,18 @@ export class Kernel implements IKernel {
|
|
|
1314
1384
|
* field map and replaces each {kind, name} reference value (outside scope visibility
|
|
1315
1385
|
* paths) with the live ResourceInstance returned by getInstance(name). Fields within
|
|
1316
1386
|
* scope paths are left as {kind, name} — the controller resolves them at runtime.
|
|
1387
|
+
*
|
|
1388
|
+
* `owner` is the context the resource belongs to, and the scope handle built for an
|
|
1389
|
+
* `x-telo-scope` field hangs off it rather than off the root: a `with:` block's inline
|
|
1390
|
+
* declarations name their kinds through the import aliases of the module that DECLARED
|
|
1391
|
+
* the resource, so a library's scoped `kind: OAuth.RedirectListener` resolves against
|
|
1392
|
+
* that library's imports — the root has never heard of the alias.
|
|
1317
1393
|
*/
|
|
1318
1394
|
private _injectDependencies(
|
|
1319
1395
|
resource: ResourceManifest,
|
|
1320
1396
|
getInstance: (name: string, alias?: string) => ResourceInstance | undefined,
|
|
1321
|
-
isPending
|
|
1397
|
+
isPending: ((name: string) => boolean) | undefined,
|
|
1398
|
+
owner: IEvaluationContext,
|
|
1322
1399
|
): void {
|
|
1323
1400
|
this.registry.iterateFieldEntries(
|
|
1324
1401
|
resource,
|
|
@@ -1349,7 +1426,7 @@ export class Kernel implements IKernel {
|
|
|
1349
1426
|
);
|
|
1350
1427
|
}
|
|
1351
1428
|
}
|
|
1352
|
-
(resource as Record<string, unknown>)[fieldPath] =
|
|
1429
|
+
(resource as Record<string, unknown>)[fieldPath] = owner.createScopeHandle(
|
|
1353
1430
|
val as ResourceManifest[],
|
|
1354
1431
|
);
|
|
1355
1432
|
}
|
package/src/module-context.ts
CHANGED
|
@@ -404,6 +404,33 @@ export class ModuleContext extends EvaluationContext implements IModuleContext {
|
|
|
404
404
|
getInstance(name: string): unknown {
|
|
405
405
|
const entry = this.resourceInstances.get(name);
|
|
406
406
|
if (!entry) {
|
|
407
|
+
// A name this module DID declare but that has no instance is never an
|
|
408
|
+
// unknown name — reporting it as "not found ... available resources:
|
|
409
|
+
// <imports>" reads as a typo in a name declared right there. Which of the
|
|
410
|
+
// two real situations it is depends on whether this context is still
|
|
411
|
+
// initializing:
|
|
412
|
+
//
|
|
413
|
+
// - mid-init: a dependency-ordering deferral. Defer exactly as Phase-5
|
|
414
|
+
// injection does, so the multi-pass loop retries and the failure is
|
|
415
|
+
// attributed to the dependency.
|
|
416
|
+
// - after init: no later pass is coming (a resource registered into the
|
|
417
|
+
// module after the loop drained its queue stays pending forever), so
|
|
418
|
+
// promising one would send the developer after a retry that will never
|
|
419
|
+
// happen. Say what is actually true.
|
|
420
|
+
if (this.hasManifest(name)) {
|
|
421
|
+
if (this.state !== "Initialized") {
|
|
422
|
+
throw new RuntimeError(
|
|
423
|
+
"ERR_LOCAL_REF_PENDING",
|
|
424
|
+
`Local reference '${name}' is registered but not initialized yet (deferring to a later init pass)`,
|
|
425
|
+
);
|
|
426
|
+
}
|
|
427
|
+
throw new RuntimeError(
|
|
428
|
+
"ERR_RESOURCE_NOT_FOUND",
|
|
429
|
+
`Resource '${name}' is declared in this module but was never initialized, so it cannot be dispatched. ` +
|
|
430
|
+
`A resource registered after the module's init loop finished is never created — declare it at module scope, ` +
|
|
431
|
+
`or inside the '${name}'-owning scope's own resource list.`,
|
|
432
|
+
);
|
|
433
|
+
}
|
|
407
434
|
throw new Error(
|
|
408
435
|
`Resource '${name}' not found in module context. Available resources: ${[...this.resourceInstances.keys()].join(", ")}`,
|
|
409
436
|
);
|
package/src/resource-context.ts
CHANGED
|
@@ -174,6 +174,87 @@ export class ResourceContextImpl implements ResourceContext {
|
|
|
174
174
|
return this.validator.getTypeRules(name);
|
|
175
175
|
}
|
|
176
176
|
|
|
177
|
+
/** The JSON Schema behind a type field, resolved the same four ways
|
|
178
|
+
* {@link createTypeValidator} resolves it (named ref, `{kind, name}` ref
|
|
179
|
+
* object, inline `{kind, schema}`, raw schema), and then followed through a
|
|
180
|
+
* bare `telo://<module>/<Type>` `$ref` to the schema that type registered.
|
|
181
|
+
*
|
|
182
|
+
* Following the `$ref` matters because AJV resolves cross-schema references
|
|
183
|
+
* against its own registry at compile time, while the kernel's registry is
|
|
184
|
+
* what actually holds these — a `Type.JsonSchema` registers under the
|
|
185
|
+
* canonical URI as a *key*, which AJV does not treat as a resolvable id. A
|
|
186
|
+
* definition whose whole contract is `{ $ref: "telo://Self/TokenSet" }` (the
|
|
187
|
+
* sanctioned way to declare a shape once and reference it from several kinds)
|
|
188
|
+
* would otherwise be uncompilable at dispatch. Resolving here means AJV is
|
|
189
|
+
* handed the real schema and never has to resolve the reference at all.
|
|
190
|
+
*
|
|
191
|
+
* Contract binding needs the schema rather than just a compiled validator
|
|
192
|
+
* anyway, for the decisions a validator cannot answer: which properties carry
|
|
193
|
+
* `x-telo-stream` and must be exempt from the walk, and which paths a
|
|
194
|
+
* `default:` can be written to. Returns undefined when the reference resolves
|
|
195
|
+
* to nothing. */
|
|
196
|
+
resolveTypeSchema(typeRef: unknown): Record<string, any> | undefined {
|
|
197
|
+
return this.followTypeAlias(this.readTypeSchema(typeRef), new Set());
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
private readTypeSchema(typeRef: unknown): Record<string, any> | undefined {
|
|
201
|
+
if (!typeRef) return undefined;
|
|
202
|
+
if (typeof typeRef === "string") return this.validator.getSchema(typeRef) as any;
|
|
203
|
+
if (typeof typeRef !== "object") return undefined;
|
|
204
|
+
const ref = typeRef as Record<string, any>;
|
|
205
|
+
if (ref.schema && typeof ref.schema === "object") return ref.schema;
|
|
206
|
+
if (typeof ref.name === "string") return this.validator.getSchema(ref.name) as any;
|
|
207
|
+
if (ref.type || ref.properties || ref.$ref) return ref;
|
|
208
|
+
return undefined;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* Follow a schema that is nothing but a `$ref` to a registered type, so the
|
|
213
|
+
* schema-level questions (which properties are streams, which paths carry a
|
|
214
|
+
* default) are asked of the real shape rather than of an alias.
|
|
215
|
+
*
|
|
216
|
+
* Only the whole-document alias form is followed, and only to READ it — the
|
|
217
|
+
* schema handed to AJV keeps its `$ref`s intact, because AJV resolves them
|
|
218
|
+
* itself against the registered ids and each type stays its own document with
|
|
219
|
+
* its own `$defs`. Inlining instead would move a `$ref: "#/$defs/X"` out of the
|
|
220
|
+
* document that defines `$defs.X`.
|
|
221
|
+
*
|
|
222
|
+
* `seen` guards a cycle two mutually-referencing types would otherwise spin on.
|
|
223
|
+
* A `$ref` alongside other keywords is left alone: that is a composition, not
|
|
224
|
+
* an alias.
|
|
225
|
+
*/
|
|
226
|
+
private followTypeAlias(
|
|
227
|
+
schema: Record<string, any> | undefined,
|
|
228
|
+
seen: Set<string>,
|
|
229
|
+
): Record<string, any> | undefined {
|
|
230
|
+
let current = schema;
|
|
231
|
+
while (
|
|
232
|
+
current &&
|
|
233
|
+
typeof current.$ref === "string" &&
|
|
234
|
+
Object.keys(current).length === 1 &&
|
|
235
|
+
!seen.has(current.$ref)
|
|
236
|
+
) {
|
|
237
|
+
seen.add(current.$ref);
|
|
238
|
+
const target = this.validator.getSchema(current.$ref) as Record<string, any> | undefined;
|
|
239
|
+
if (!target) return current;
|
|
240
|
+
current = target;
|
|
241
|
+
}
|
|
242
|
+
return current;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/** Compile `schema` but compose the CEL `rules:` registered under `name`.
|
|
246
|
+
*
|
|
247
|
+
* A named type's rules are its business invariants, and they are reachable
|
|
248
|
+
* only through the name. {@link createTypeValidator} composes them when it is
|
|
249
|
+
* handed a bare name, but a caller that must adjust the schema first — the
|
|
250
|
+
* contract binding, which strips `x-telo-stream` properties before validating
|
|
251
|
+
* — would otherwise have to choose between the adjustment and the rules. */
|
|
252
|
+
createTypeValidatorWithRules(name: string | undefined, schema: Record<string, any>) {
|
|
253
|
+
const base = this.validator.compile(schema);
|
|
254
|
+
const rules = name ? this.validator.getTypeRules(name) : undefined;
|
|
255
|
+
return rules && rules.length > 0 ? this.validator.composeWithRules(base, name!, rules) : base;
|
|
256
|
+
}
|
|
257
|
+
|
|
177
258
|
createTypeValidator(typeRef: string | Record<string, any> | undefined) {
|
|
178
259
|
if (!typeRef) return new NoopValidator();
|
|
179
260
|
|