@almadar/evaluator 2.35.0 → 2.37.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.
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { TraitConfig, AgentContext, LlmContext, WorkspaceContext, SessionContext, MemoryContext, TraceContext, IntegrationContext, SExpr } from '@almadar/core';
|
|
1
|
+
import { UserContext, TraitConfig, AgentContext, LlmContext, WorkspaceContext, SessionContext, MemoryContext, TraceContext, IntegrationContext, SExpr } from '@almadar/core';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Evaluation Context
|
|
@@ -9,23 +9,6 @@ import { TraitConfig, AgentContext, LlmContext, WorkspaceContext, SessionContext
|
|
|
9
9
|
* @packageDocumentation
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
|
-
/**
|
|
13
|
-
* User context for @user bindings (role-based UI).
|
|
14
|
-
*/
|
|
15
|
-
interface UserContext {
|
|
16
|
-
/** User's unique ID */
|
|
17
|
-
id: string;
|
|
18
|
-
/** User's email */
|
|
19
|
-
email?: string;
|
|
20
|
-
/** User's display name */
|
|
21
|
-
name?: string;
|
|
22
|
-
/** User's role (for RBAC) */
|
|
23
|
-
role?: string;
|
|
24
|
-
/** User's permissions */
|
|
25
|
-
permissions?: string[];
|
|
26
|
-
/** Additional custom profile fields */
|
|
27
|
-
[key: string]: unknown;
|
|
28
|
-
}
|
|
29
12
|
/**
|
|
30
13
|
* Evaluation context for S-expression evaluation.
|
|
31
14
|
* Provides all bindings and effect handlers needed at runtime.
|
|
@@ -456,4 +439,4 @@ declare function evalWatch(args: SExpr[], evaluate: Evaluator, ctx: EvaluationCo
|
|
|
456
439
|
*/
|
|
457
440
|
declare function evalAtomic(args: SExpr[], evaluate: Evaluator, ctx: EvaluationContext): unknown;
|
|
458
441
|
|
|
459
|
-
export {
|
|
442
|
+
export { evalSetDynamic as $, evalGreaterThanOrEqual as A, evalIf as B, evalIncludes as C, evalIncrement as D, type EvaluationContext as E, evalLast as F, evalLessThan as G, evalLessThanOrEqual as H, evalLet as I, evalList as J, evalMap as K, evalMatches as L, evalMax as M, evalMin as N, evalModulo as O, evalMultiply as P, evalNavigate as Q, evalNot as R, evalNotEqual as S, evalNotify as T, evalNth as U, evalOr as V, evalPersist as W, evalRef as X, evalRenderUI as Y, evalRound as Z, evalSet as _, createEffectContext as a, evalSpawn as a0, evalSubtract as a1, evalSum as a2, evalSwap as a3, evalWatch as a4, evalWhen as a5, resolveBinding as a6, createMinimalContext as b, createChildContext as c, evalAdd as d, evalAbs as e, evalAnd as f, evalAtomic as g, evalCallService as h, evalCeil as i, evalClamp as j, evalConcat as k, evalCount as l, evalDecrement as m, evalDeref as n, evalDespawn as o, evalDivide as p, evalDo as q, evalEmit as r, evalEmpty as s, evalEqual as t, evalFilter as u, evalFind as v, evalFirst as w, evalFloor as x, evalFn as y, evalGreaterThan as z };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { SExpr } from '@almadar/core';
|
|
2
|
-
export { CORE_BINDINGS, CoreBinding, Expression, ExpressionSchema, ParsedBinding, SExpr, SExprAtom, SExprSchema, collectBindings, getArgs, getOperator, isBinding, isSExpr, isSExprAtom, isSExprCall, isValidBinding, parseBinding, sexpr, walkSExpr } from '@almadar/core';
|
|
3
|
-
import { E as EvaluationContext } from './index-
|
|
4
|
-
export {
|
|
1
|
+
import { SExpr, ListenPayloadEvaluator } from '@almadar/core';
|
|
2
|
+
export { CORE_BINDINGS, CoreBinding, Expression, ExpressionSchema, ParsedBinding, SExpr, SExprAtom, SExprSchema, UserContext, collectBindings, getArgs, getOperator, isBinding, isSExpr, isSExprAtom, isSExprCall, isValidBinding, parseBinding, sexpr, walkSExpr } from '@almadar/core';
|
|
3
|
+
import { E as EvaluationContext } from './index-dAA7DJ-s.js';
|
|
4
|
+
export { c as createChildContext, a as createEffectContext, b as createMinimalContext, e as evalAbs, d as evalAdd, f as evalAnd, g as evalAtomic, h as evalCallService, i as evalCeil, j as evalClamp, k as evalConcat, l as evalCount, m as evalDecrement, n as evalDeref, o as evalDespawn, p as evalDivide, q as evalDo, r as evalEmit, s as evalEmpty, t as evalEqual, u as evalFilter, v as evalFind, w as evalFirst, x as evalFloor, y as evalFn, z as evalGreaterThan, A as evalGreaterThanOrEqual, B as evalIf, C as evalIncludes, D as evalIncrement, F as evalLast, G as evalLessThan, H as evalLessThanOrEqual, I as evalLet, J as evalList, K as evalMap, L as evalMatches, M as evalMax, N as evalMin, O as evalModulo, P as evalMultiply, Q as evalNavigate, R as evalNot, S as evalNotEqual, T as evalNotify, U as evalNth, V as evalOr, W as evalPersist, X as evalRef, Y as evalRenderUI, Z as evalRound, _ as evalSet, $ as evalSetDynamic, a0 as evalSpawn, a1 as evalSubtract, a2 as evalSum, a3 as evalSwap, a4 as evalWatch, a5 as evalWhen, a6 as resolveBinding } from './index-dAA7DJ-s.js';
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
7
|
* S-Expression Evaluator
|
|
@@ -72,4 +72,24 @@ declare function evaluateGuard(expr: SExpr, ctx: EvaluationContext): boolean;
|
|
|
72
72
|
declare function executeEffect(expr: SExpr, ctx: EvaluationContext): void;
|
|
73
73
|
declare function executeEffects(effects: SExpr[], ctx: EvaluationContext): void;
|
|
74
74
|
|
|
75
|
-
|
|
75
|
+
/**
|
|
76
|
+
* The canonical evaluator for `listens { … with { field: <expr> } }` mapping
|
|
77
|
+
* values.
|
|
78
|
+
*
|
|
79
|
+
* `@almadar/core` owns the mapping contract (`applyListenPayloadMapping`) but
|
|
80
|
+
* sits upstream of this package and cannot evaluate. Every delivery path — the
|
|
81
|
+
* server runtime and the client cross-trait wiring — passes THIS function, so
|
|
82
|
+
* the two paths cannot drift into different `with{}` semantics.
|
|
83
|
+
*
|
|
84
|
+
* The binding context is payload-only, matching `orbital-core`'s listener
|
|
85
|
+
* fan-out (`runtime/listener.rs:107-109`, `runtime/kernel.rs:687-689`), which
|
|
86
|
+
* builds `BindingContextBuilder::new().payload(…).build()`. Binding `@entity`
|
|
87
|
+
* or `@config` here would let a mapping resolve on the JS path and silently
|
|
88
|
+
* yield nothing on the compiled one.
|
|
89
|
+
*
|
|
90
|
+
* @packageDocumentation
|
|
91
|
+
*/
|
|
92
|
+
|
|
93
|
+
declare const evaluateListenPayloadExpr: ListenPayloadEvaluator;
|
|
94
|
+
|
|
95
|
+
export { EvaluationContext, SExpressionEvaluator, evaluate, evaluateGuard, evaluateListenPayloadExpr, evaluator, executeEffect, executeEffects };
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { isSExpr, isBinding, getOperator, getArgs, isFieldValue, isEventPayloadValue, isSessionHistoryEntry, isPlanSnapshot, OrbitalZodSchema, safeParseOrbitalSchema } from '@almadar/core';
|
|
1
|
+
import { isSExpr, isBinding, getOperator, getArgs, isTensorValue, describeTensorMismatch, contractFieldName, validateContract, isFieldValue, isEventPayloadValue, isSessionHistoryEntry, isPlanSnapshot, tensorLastDimSize, mapTensorLastDim, OrbitalZodSchema, safeParseOrbitalSchema } from '@almadar/core';
|
|
2
2
|
export { CORE_BINDINGS, ExpressionSchema, SExprSchema, collectBindings, getArgs, getOperator, isBinding, isSExpr, isSExprAtom, isSExprCall, isValidBinding, parseBinding, sexpr, walkSExpr } from '@almadar/core';
|
|
3
3
|
import { assertOperatorArity } from '@almadar/std/registry';
|
|
4
4
|
|
|
@@ -1288,6 +1288,56 @@ function evalArrayDropLast(args, evaluate2, ctx) {
|
|
|
1288
1288
|
const n = evaluate2(args[1], ctx);
|
|
1289
1289
|
return (arr ?? []).slice(0, -n);
|
|
1290
1290
|
}
|
|
1291
|
+
function cosineSimilarity(a, b) {
|
|
1292
|
+
if (a.length !== b.length) {
|
|
1293
|
+
throw new Error(`array/cosine: vector length mismatch (${a.length} vs ${b.length})`);
|
|
1294
|
+
}
|
|
1295
|
+
if (a.length === 0) {
|
|
1296
|
+
throw new Error("array/cosine: empty vector has no defined similarity");
|
|
1297
|
+
}
|
|
1298
|
+
let dot = 0;
|
|
1299
|
+
let normA = 0;
|
|
1300
|
+
let normB = 0;
|
|
1301
|
+
for (let i = 0; i < a.length; i++) {
|
|
1302
|
+
const av = a[i];
|
|
1303
|
+
const bv = b[i];
|
|
1304
|
+
dot += av * bv;
|
|
1305
|
+
normA += av * av;
|
|
1306
|
+
normB += bv * bv;
|
|
1307
|
+
}
|
|
1308
|
+
if (normA === 0 || normB === 0) {
|
|
1309
|
+
throw new Error("array/cosine: zero-magnitude vector has no defined direction to compare");
|
|
1310
|
+
}
|
|
1311
|
+
return dot / (Math.sqrt(normA) * Math.sqrt(normB));
|
|
1312
|
+
}
|
|
1313
|
+
function evalArrayCosine(args, evaluate2, ctx) {
|
|
1314
|
+
const a = evaluate2(args[0], ctx);
|
|
1315
|
+
const b = evaluate2(args[1], ctx);
|
|
1316
|
+
return cosineSimilarity(a, b);
|
|
1317
|
+
}
|
|
1318
|
+
function evalArrayNearest(args, evaluate2, ctx) {
|
|
1319
|
+
const query = evaluate2(args[0], ctx);
|
|
1320
|
+
const candidates = evaluate2(args[1], ctx);
|
|
1321
|
+
if (candidates.length === 0) {
|
|
1322
|
+
throw new Error("array/nearest: candidates array is empty, no nearest match exists");
|
|
1323
|
+
}
|
|
1324
|
+
const scores = candidates.map((c) => cosineSimilarity(query, c));
|
|
1325
|
+
let bestIdx = 0;
|
|
1326
|
+
let bestScore = scores[0];
|
|
1327
|
+
for (let i = 1; i < scores.length; i++) {
|
|
1328
|
+
if (scores[i] > bestScore) {
|
|
1329
|
+
bestScore = scores[i];
|
|
1330
|
+
bestIdx = i;
|
|
1331
|
+
}
|
|
1332
|
+
}
|
|
1333
|
+
let secondBest = -Infinity;
|
|
1334
|
+
for (let i = 0; i < scores.length; i++) {
|
|
1335
|
+
if (i === bestIdx) continue;
|
|
1336
|
+
if (scores[i] > secondBest) secondBest = scores[i];
|
|
1337
|
+
}
|
|
1338
|
+
const margin = scores.length === 1 ? 0 : bestScore - secondBest;
|
|
1339
|
+
return { index: bestIdx, score: bestScore, margin };
|
|
1340
|
+
}
|
|
1291
1341
|
|
|
1292
1342
|
// std/object.ts
|
|
1293
1343
|
var FORBIDDEN_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
|
|
@@ -1778,11 +1828,11 @@ function evalTimeFormat(args, evaluate2, ctx) {
|
|
|
1778
1828
|
"December"
|
|
1779
1829
|
][date.getMonth()]
|
|
1780
1830
|
};
|
|
1781
|
-
|
|
1782
|
-
|
|
1783
|
-
|
|
1784
|
-
|
|
1785
|
-
return
|
|
1831
|
+
const pattern = new RegExp(
|
|
1832
|
+
Object.keys(tokens).sort((a, b) => b.length - a.length).join("|"),
|
|
1833
|
+
"g"
|
|
1834
|
+
);
|
|
1835
|
+
return format.replace(pattern, (token) => tokens[token]);
|
|
1786
1836
|
}
|
|
1787
1837
|
function evalTimeYear(args, evaluate2, ctx) {
|
|
1788
1838
|
const timestamp = evaluate2(args[0], ctx);
|
|
@@ -2537,6 +2587,407 @@ function evalOsDebounce(args, evaluate2, ctx) {
|
|
|
2537
2587
|
const eventType = evaluate2(args[1], ctx);
|
|
2538
2588
|
registerTrigger(ctx, "debounce", { ms, eventType });
|
|
2539
2589
|
}
|
|
2590
|
+
function clampContract(tensor, contract) {
|
|
2591
|
+
if (!isTensorValue(tensor)) {
|
|
2592
|
+
throw new Error(
|
|
2593
|
+
`contract/clamp-output: expected a tensor (a number, or nested arrays of numbers), received ${describeTensorMismatch(tensor)}. Validate with contract/validate-output before clamping.`
|
|
2594
|
+
);
|
|
2595
|
+
}
|
|
2596
|
+
const ranges = contract.ranges ?? {};
|
|
2597
|
+
const size = tensorLastDimSize(tensor);
|
|
2598
|
+
let result = tensor;
|
|
2599
|
+
for (const [dimStr, bounds] of Object.entries(ranges)) {
|
|
2600
|
+
const dim = Number(dimStr);
|
|
2601
|
+
if (dim >= size) continue;
|
|
2602
|
+
const min = bounds.min ?? -Infinity;
|
|
2603
|
+
const max = bounds.max ?? Infinity;
|
|
2604
|
+
result = mapTensorLastDim(result, dim, (v) => Math.min(Math.max(v, min), max));
|
|
2605
|
+
}
|
|
2606
|
+
return result;
|
|
2607
|
+
}
|
|
2608
|
+
function evalContractValidateInput(args, evaluate2, ctx) {
|
|
2609
|
+
const tensor = evaluate2(args[0], ctx);
|
|
2610
|
+
const contract = evaluate2(args[1], ctx);
|
|
2611
|
+
return validateContract(tensor, contract);
|
|
2612
|
+
}
|
|
2613
|
+
function evalContractValidateOutput(args, evaluate2, ctx) {
|
|
2614
|
+
return evalContractValidateInput(args, evaluate2, ctx);
|
|
2615
|
+
}
|
|
2616
|
+
function evalContractClampOutput(args, evaluate2, ctx) {
|
|
2617
|
+
const tensor = evaluate2(args[0], ctx);
|
|
2618
|
+
const contract = evaluate2(args[1], ctx);
|
|
2619
|
+
return clampContract(tensor, contract);
|
|
2620
|
+
}
|
|
2621
|
+
function evalContractViolations(args, evaluate2, ctx) {
|
|
2622
|
+
const tensor = evaluate2(args[0], ctx);
|
|
2623
|
+
const contract = evaluate2(args[1], ctx);
|
|
2624
|
+
return validateContract(tensor, contract).violations;
|
|
2625
|
+
}
|
|
2626
|
+
function evalContractEntityToTensor(args, evaluate2, ctx) {
|
|
2627
|
+
const entity = evaluate2(args[0], ctx);
|
|
2628
|
+
const contract = evaluate2(args[1], ctx);
|
|
2629
|
+
const fields = contract.fields ?? [];
|
|
2630
|
+
return fields.map((f) => {
|
|
2631
|
+
const val = entity[contractFieldName(f)];
|
|
2632
|
+
return typeof val === "number" ? val : 0;
|
|
2633
|
+
});
|
|
2634
|
+
}
|
|
2635
|
+
function evalContractTensorToPayload(args, evaluate2, ctx) {
|
|
2636
|
+
const tensor = evaluate2(args[0], ctx);
|
|
2637
|
+
if (!isTensorValue(tensor)) {
|
|
2638
|
+
throw new Error(
|
|
2639
|
+
`contract/tensor-to-payload: expected a tensor (a number, or nested arrays of numbers), received ${describeTensorMismatch(tensor)}.`
|
|
2640
|
+
);
|
|
2641
|
+
}
|
|
2642
|
+
const contract = evaluate2(args[1], ctx);
|
|
2643
|
+
const fields = contract.fields ?? [];
|
|
2644
|
+
const values = Array.isArray(tensor) ? tensor : [tensor];
|
|
2645
|
+
const result = {};
|
|
2646
|
+
fields.forEach((f, i) => {
|
|
2647
|
+
if (i < values.length) result[contractFieldName(f)] = values[i];
|
|
2648
|
+
});
|
|
2649
|
+
return result;
|
|
2650
|
+
}
|
|
2651
|
+
|
|
2652
|
+
// std/graph.ts
|
|
2653
|
+
function tensorShape(t) {
|
|
2654
|
+
if (typeof t === "number") return [];
|
|
2655
|
+
if (t.length === 0) return [0];
|
|
2656
|
+
const first = t[0];
|
|
2657
|
+
if (typeof first === "number") return [t.length];
|
|
2658
|
+
return [t.length, ...tensorShape(first)];
|
|
2659
|
+
}
|
|
2660
|
+
function numNodes(g) {
|
|
2661
|
+
return g.x.length;
|
|
2662
|
+
}
|
|
2663
|
+
function subgraphData(g, mask) {
|
|
2664
|
+
const nodeMap = new Array(numNodes(g)).fill(-1);
|
|
2665
|
+
const x = [];
|
|
2666
|
+
let next = 0;
|
|
2667
|
+
for (let i = 0; i < numNodes(g); i++) {
|
|
2668
|
+
if (mask[i]) {
|
|
2669
|
+
nodeMap[i] = next++;
|
|
2670
|
+
x.push(g.x[i]);
|
|
2671
|
+
}
|
|
2672
|
+
}
|
|
2673
|
+
const [srcAll, dstAll] = g.edgeIndex;
|
|
2674
|
+
const src = [];
|
|
2675
|
+
const dst = [];
|
|
2676
|
+
for (let k = 0; k < srcAll.length; k++) {
|
|
2677
|
+
const s = srcAll[k];
|
|
2678
|
+
const d = dstAll[k];
|
|
2679
|
+
if (mask[s] && mask[d]) {
|
|
2680
|
+
src.push(nodeMap[s]);
|
|
2681
|
+
dst.push(nodeMap[d]);
|
|
2682
|
+
}
|
|
2683
|
+
}
|
|
2684
|
+
return { x, edgeIndex: [src, dst] };
|
|
2685
|
+
}
|
|
2686
|
+
function evalGraphFromEntities(args, evaluate2, ctx) {
|
|
2687
|
+
const entities = evaluate2(args[0], ctx);
|
|
2688
|
+
if (entities.length === 0) {
|
|
2689
|
+
return { x: [], edgeIndex: [[], []] };
|
|
2690
|
+
}
|
|
2691
|
+
const features = entities.map((e) => {
|
|
2692
|
+
const row = Object.values(e).filter((v) => typeof v === "number" || typeof v === "boolean").map((v) => typeof v === "boolean" ? v ? 1 : 0 : v);
|
|
2693
|
+
return row.length > 0 ? row : [0];
|
|
2694
|
+
});
|
|
2695
|
+
const maxLen = Math.max(...features.map((r) => r.length));
|
|
2696
|
+
const x = features.map((r) => [...r, ...new Array(maxLen - r.length).fill(0)]);
|
|
2697
|
+
return { x, edgeIndex: [[], []] };
|
|
2698
|
+
}
|
|
2699
|
+
function evalGraphFromAdjacency(args, evaluate2, ctx) {
|
|
2700
|
+
const adjacency = evaluate2(args[0], ctx);
|
|
2701
|
+
const features = evaluate2(args[1], ctx);
|
|
2702
|
+
const src = [];
|
|
2703
|
+
const dst = [];
|
|
2704
|
+
for (let i = 0; i < adjacency.length; i++) {
|
|
2705
|
+
const row = adjacency[i];
|
|
2706
|
+
for (let j = 0; j < row.length; j++) {
|
|
2707
|
+
if (row[j] !== 0) {
|
|
2708
|
+
src.push(i);
|
|
2709
|
+
dst.push(j);
|
|
2710
|
+
}
|
|
2711
|
+
}
|
|
2712
|
+
}
|
|
2713
|
+
return { x: features, edgeIndex: [src, dst] };
|
|
2714
|
+
}
|
|
2715
|
+
function evalGraphFromEdgeList(args, evaluate2, ctx) {
|
|
2716
|
+
const edges = evaluate2(args[0], ctx);
|
|
2717
|
+
const features = evaluate2(args[1], ctx);
|
|
2718
|
+
const shape = tensorShape(edges);
|
|
2719
|
+
let edgeIndex;
|
|
2720
|
+
if (shape.length === 2 && shape[1] === 2) {
|
|
2721
|
+
const rows = edges;
|
|
2722
|
+
edgeIndex = [rows.map((r) => r[0]), rows.map((r) => r[1])];
|
|
2723
|
+
} else {
|
|
2724
|
+
const pair = edges;
|
|
2725
|
+
edgeIndex = [pair[0] ?? [], pair[1] ?? []];
|
|
2726
|
+
}
|
|
2727
|
+
return { x: features, edgeIndex };
|
|
2728
|
+
}
|
|
2729
|
+
function evalGraphAddSelfLoops(args, evaluate2, ctx) {
|
|
2730
|
+
const g = evaluate2(args[0], ctx);
|
|
2731
|
+
const n = numNodes(g);
|
|
2732
|
+
const loop = Array.from({ length: n }, (_, i) => i);
|
|
2733
|
+
const [src, dst] = g.edgeIndex;
|
|
2734
|
+
return { x: g.x, edgeIndex: [[...src, ...loop], [...dst, ...loop]], edgeAttr: g.edgeAttr };
|
|
2735
|
+
}
|
|
2736
|
+
function evalGraphToUndirected(args, evaluate2, ctx) {
|
|
2737
|
+
const g = evaluate2(args[0], ctx);
|
|
2738
|
+
const [src, dst] = g.edgeIndex;
|
|
2739
|
+
return { x: g.x, edgeIndex: [[...src, ...dst], [...dst, ...src]], edgeAttr: g.edgeAttr };
|
|
2740
|
+
}
|
|
2741
|
+
function evalGraphSubgraph(args, evaluate2, ctx) {
|
|
2742
|
+
const g = evaluate2(args[0], ctx);
|
|
2743
|
+
const mask = evaluate2(args[1], ctx);
|
|
2744
|
+
return subgraphData(g, mask);
|
|
2745
|
+
}
|
|
2746
|
+
function evalGraphKHop(args, evaluate2, ctx) {
|
|
2747
|
+
const g = evaluate2(args[0], ctx);
|
|
2748
|
+
const node = evaluate2(args[1], ctx);
|
|
2749
|
+
const k = evaluate2(args[2], ctx);
|
|
2750
|
+
const [src, dst] = g.edgeIndex;
|
|
2751
|
+
const visited = /* @__PURE__ */ new Set([node]);
|
|
2752
|
+
let frontier = /* @__PURE__ */ new Set([node]);
|
|
2753
|
+
for (let hop = 0; hop < k; hop++) {
|
|
2754
|
+
const next = /* @__PURE__ */ new Set();
|
|
2755
|
+
for (const n of frontier) {
|
|
2756
|
+
for (let e = 0; e < src.length; e++) {
|
|
2757
|
+
if (src[e] === n && !visited.has(dst[e])) next.add(dst[e]);
|
|
2758
|
+
if (dst[e] === n && !visited.has(src[e])) next.add(src[e]);
|
|
2759
|
+
}
|
|
2760
|
+
}
|
|
2761
|
+
for (const v of next) visited.add(v);
|
|
2762
|
+
frontier = next;
|
|
2763
|
+
}
|
|
2764
|
+
const mask = new Array(numNodes(g)).fill(false);
|
|
2765
|
+
for (const n of visited) mask[n] = true;
|
|
2766
|
+
return subgraphData(g, mask);
|
|
2767
|
+
}
|
|
2768
|
+
function evalGraphNodeFeatures(args, evaluate2, ctx) {
|
|
2769
|
+
return evaluate2(args[0], ctx).x;
|
|
2770
|
+
}
|
|
2771
|
+
function evalGraphEdgeIndex(args, evaluate2, ctx) {
|
|
2772
|
+
return evaluate2(args[0], ctx).edgeIndex;
|
|
2773
|
+
}
|
|
2774
|
+
function evalGraphEdgeFeatures(args, evaluate2, ctx) {
|
|
2775
|
+
return evaluate2(args[0], ctx).edgeAttr;
|
|
2776
|
+
}
|
|
2777
|
+
function evalGraphNumNodes(args, evaluate2, ctx) {
|
|
2778
|
+
return numNodes(evaluate2(args[0], ctx));
|
|
2779
|
+
}
|
|
2780
|
+
function evalGraphNumEdges(args, evaluate2, ctx) {
|
|
2781
|
+
return evaluate2(args[0], ctx).edgeIndex[0].length;
|
|
2782
|
+
}
|
|
2783
|
+
function evalGraphDegree(args, evaluate2, ctx) {
|
|
2784
|
+
const g = evaluate2(args[0], ctx);
|
|
2785
|
+
const deg = new Array(numNodes(g)).fill(0);
|
|
2786
|
+
for (const s of g.edgeIndex[0]) deg[s]++;
|
|
2787
|
+
return deg;
|
|
2788
|
+
}
|
|
2789
|
+
function evalGraphBatch(args, evaluate2, ctx) {
|
|
2790
|
+
const graphs = evaluate2(args[0], ctx);
|
|
2791
|
+
if (graphs.length === 0) return { x: [], edgeIndex: [[], []] };
|
|
2792
|
+
const x = [];
|
|
2793
|
+
const src = [];
|
|
2794
|
+
const dst = [];
|
|
2795
|
+
let offset = 0;
|
|
2796
|
+
for (const g of graphs) {
|
|
2797
|
+
x.push(...g.x);
|
|
2798
|
+
src.push(...g.edgeIndex[0].map((s) => s + offset));
|
|
2799
|
+
dst.push(...g.edgeIndex[1].map((d) => d + offset));
|
|
2800
|
+
offset += numNodes(g);
|
|
2801
|
+
}
|
|
2802
|
+
return { x, edgeIndex: [src, dst] };
|
|
2803
|
+
}
|
|
2804
|
+
|
|
2805
|
+
// std/data.ts
|
|
2806
|
+
function isPlainRecord(v) {
|
|
2807
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
2808
|
+
}
|
|
2809
|
+
function datasetGetItem(dataset, idx) {
|
|
2810
|
+
const item = dataset.data[idx];
|
|
2811
|
+
if (isPlainRecord(item)) {
|
|
2812
|
+
const x = item.input ?? item.observation ?? [];
|
|
2813
|
+
const y = item.target ?? item.output ?? [];
|
|
2814
|
+
return [x, y];
|
|
2815
|
+
}
|
|
2816
|
+
if (Array.isArray(item)) {
|
|
2817
|
+
return [item, item];
|
|
2818
|
+
}
|
|
2819
|
+
return [item, item];
|
|
2820
|
+
}
|
|
2821
|
+
function seededRandom(ctx) {
|
|
2822
|
+
if (ctx._probSeed) {
|
|
2823
|
+
const seed = ctx._probSeed;
|
|
2824
|
+
let t = seed.state += 1831565813;
|
|
2825
|
+
t = Math.imul(t ^ t >>> 15, t | 1);
|
|
2826
|
+
t ^= t + Math.imul(t ^ t >>> 7, t | 61);
|
|
2827
|
+
return ((t ^ t >>> 14) >>> 0) / 4294967296;
|
|
2828
|
+
}
|
|
2829
|
+
return Math.random();
|
|
2830
|
+
}
|
|
2831
|
+
function seededGaussian(ctx) {
|
|
2832
|
+
const u1 = seededRandom(ctx);
|
|
2833
|
+
const u2 = seededRandom(ctx);
|
|
2834
|
+
return Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2);
|
|
2835
|
+
}
|
|
2836
|
+
function shuffleInPlace(arr, ctx) {
|
|
2837
|
+
for (let i = arr.length - 1; i > 0; i--) {
|
|
2838
|
+
const j = Math.floor(seededRandom(ctx) * (i + 1));
|
|
2839
|
+
const tmp = arr[i];
|
|
2840
|
+
arr[i] = arr[j];
|
|
2841
|
+
arr[j] = tmp;
|
|
2842
|
+
}
|
|
2843
|
+
}
|
|
2844
|
+
function tensorShape2(t) {
|
|
2845
|
+
if (typeof t === "number") return [];
|
|
2846
|
+
if (t.length === 0) return [0];
|
|
2847
|
+
const first = t[0];
|
|
2848
|
+
if (typeof first === "number") return [t.length];
|
|
2849
|
+
return [t.length, ...tensorShape2(first)];
|
|
2850
|
+
}
|
|
2851
|
+
function rank(t) {
|
|
2852
|
+
return tensorShape2(t).length;
|
|
2853
|
+
}
|
|
2854
|
+
function sampleMean(vals) {
|
|
2855
|
+
return vals.reduce((s, v) => s + v, 0) / vals.length;
|
|
2856
|
+
}
|
|
2857
|
+
function sampleStd(vals, mean) {
|
|
2858
|
+
if (vals.length <= 1) return 0;
|
|
2859
|
+
const variance = vals.reduce((s, v) => s + (v - mean) ** 2, 0) / (vals.length - 1);
|
|
2860
|
+
return Math.sqrt(variance);
|
|
2861
|
+
}
|
|
2862
|
+
function normalizeZScore(t) {
|
|
2863
|
+
if (rank(t) <= 1) {
|
|
2864
|
+
const vals = t;
|
|
2865
|
+
const mean = sampleMean(vals);
|
|
2866
|
+
const std = Math.max(sampleStd(vals, mean), 1e-8);
|
|
2867
|
+
return vals.map((v) => (v - mean) / std);
|
|
2868
|
+
}
|
|
2869
|
+
const rows = t;
|
|
2870
|
+
const cols = rows[0].length;
|
|
2871
|
+
const means = [];
|
|
2872
|
+
const stds = [];
|
|
2873
|
+
for (let c = 0; c < cols; c++) {
|
|
2874
|
+
const col = rows.map((r) => r[c]);
|
|
2875
|
+
const m = sampleMean(col);
|
|
2876
|
+
means.push(m);
|
|
2877
|
+
stds.push(Math.max(sampleStd(col, m), 1e-8));
|
|
2878
|
+
}
|
|
2879
|
+
return rows.map((r) => r.map((v, c) => (v - means[c]) / stds[c]));
|
|
2880
|
+
}
|
|
2881
|
+
function normalizeMinMax(t) {
|
|
2882
|
+
if (rank(t) <= 1) {
|
|
2883
|
+
const vals = t;
|
|
2884
|
+
const mn = Math.min(...vals);
|
|
2885
|
+
const mx = Math.max(...vals);
|
|
2886
|
+
const denom = Math.max(mx - mn, 1e-8);
|
|
2887
|
+
return vals.map((v) => (v - mn) / denom);
|
|
2888
|
+
}
|
|
2889
|
+
const rows = t;
|
|
2890
|
+
const cols = rows[0].length;
|
|
2891
|
+
const mins = [];
|
|
2892
|
+
const maxs = [];
|
|
2893
|
+
for (let c = 0; c < cols; c++) {
|
|
2894
|
+
const col = rows.map((r) => r[c]);
|
|
2895
|
+
mins.push(Math.min(...col));
|
|
2896
|
+
maxs.push(Math.max(...col));
|
|
2897
|
+
}
|
|
2898
|
+
return rows.map((r) => r.map((v, c) => (v - mins[c]) / Math.max(maxs[c] - mins[c], 1e-8)));
|
|
2899
|
+
}
|
|
2900
|
+
function mapTensor(t, fn) {
|
|
2901
|
+
if (typeof t === "number") return fn(t);
|
|
2902
|
+
return t.map((sub) => mapTensor(sub, fn));
|
|
2903
|
+
}
|
|
2904
|
+
function padOrTruncateLastDim(t, targetLen, padValue) {
|
|
2905
|
+
if (typeof t === "number") return t;
|
|
2906
|
+
if (t.length === 0 || typeof t[0] === "number") {
|
|
2907
|
+
const row = t;
|
|
2908
|
+
if (row.length < targetLen) {
|
|
2909
|
+
return [...row, ...new Array(targetLen - row.length).fill(padValue)];
|
|
2910
|
+
}
|
|
2911
|
+
return row.slice(0, targetLen);
|
|
2912
|
+
}
|
|
2913
|
+
return t.map((sub) => padOrTruncateLastDim(sub, targetLen, padValue));
|
|
2914
|
+
}
|
|
2915
|
+
function evalDataDataset(args, evaluate2, ctx) {
|
|
2916
|
+
const data = evaluate2(args[0], ctx);
|
|
2917
|
+
const config = evaluate2(args[1], ctx);
|
|
2918
|
+
return { data: Array.isArray(data) ? data : [], config };
|
|
2919
|
+
}
|
|
2920
|
+
function evalDataDataloader(args, evaluate2, ctx) {
|
|
2921
|
+
const dataset = evaluate2(args[0], ctx);
|
|
2922
|
+
const config = evaluate2(args[1], ctx);
|
|
2923
|
+
const batchSize = config.batchSize ?? config.batch_size ?? 32;
|
|
2924
|
+
const shuffle = config.shuffle ?? true;
|
|
2925
|
+
const indices = Array.from({ length: dataset.data.length }, (_, i) => i);
|
|
2926
|
+
if (shuffle) shuffleInPlace(indices, ctx);
|
|
2927
|
+
const batches = [];
|
|
2928
|
+
for (let i = 0; i < indices.length; i += batchSize) {
|
|
2929
|
+
const chunk = indices.slice(i, i + batchSize);
|
|
2930
|
+
const x = [];
|
|
2931
|
+
const y = [];
|
|
2932
|
+
for (const idx of chunk) {
|
|
2933
|
+
const [xi, yi] = datasetGetItem(dataset, idx);
|
|
2934
|
+
x.push(xi);
|
|
2935
|
+
y.push(yi);
|
|
2936
|
+
}
|
|
2937
|
+
batches.push({ x, y });
|
|
2938
|
+
}
|
|
2939
|
+
return { batches, batchSize, numBatches: batches.length };
|
|
2940
|
+
}
|
|
2941
|
+
function evalDataSplit(args, evaluate2, ctx) {
|
|
2942
|
+
const dataset = evaluate2(args[0], ctx);
|
|
2943
|
+
const config = evaluate2(args[1], ctx);
|
|
2944
|
+
const ratio = config.trainRatio ?? config.train_ratio ?? 0.8;
|
|
2945
|
+
const trainSize = Math.trunc(dataset.data.length * ratio);
|
|
2946
|
+
const indices = Array.from({ length: dataset.data.length }, (_, i) => i);
|
|
2947
|
+
shuffleInPlace(indices, ctx);
|
|
2948
|
+
const trainIdx = indices.slice(0, trainSize);
|
|
2949
|
+
const testIdx = indices.slice(trainSize);
|
|
2950
|
+
return [
|
|
2951
|
+
{ data: trainIdx.map((i) => dataset.data[i]), config: dataset.config },
|
|
2952
|
+
{ data: testIdx.map((i) => dataset.data[i]), config: dataset.config }
|
|
2953
|
+
];
|
|
2954
|
+
}
|
|
2955
|
+
function evalDataNormalize(args, evaluate2, ctx) {
|
|
2956
|
+
const data = evaluate2(args[0], ctx);
|
|
2957
|
+
const config = evaluate2(args[1], ctx);
|
|
2958
|
+
const method = config.method ?? "zscore";
|
|
2959
|
+
if (method === "zscore") return normalizeZScore(data);
|
|
2960
|
+
if (method === "minmax") return normalizeMinMax(data);
|
|
2961
|
+
return data;
|
|
2962
|
+
}
|
|
2963
|
+
function evalDataAugment(args, evaluate2, ctx) {
|
|
2964
|
+
const data = evaluate2(args[0], ctx);
|
|
2965
|
+
const config = evaluate2(args[1], ctx);
|
|
2966
|
+
const noiseScale = config.noiseScale ?? config.noise_scale ?? 0.01;
|
|
2967
|
+
return mapTensor(data, (v) => v + seededGaussian(ctx) * noiseScale);
|
|
2968
|
+
}
|
|
2969
|
+
function evalDataTokenize(args, evaluate2, ctx) {
|
|
2970
|
+
const text = evaluate2(args[0], ctx);
|
|
2971
|
+
const config = evaluate2(args[1], ctx);
|
|
2972
|
+
const mode = config.mode ?? "char";
|
|
2973
|
+
const textStr = String(text);
|
|
2974
|
+
if (mode === "word") {
|
|
2975
|
+
const vocab = config.vocab ?? {};
|
|
2976
|
+
return textStr.split(/\s+/).filter((w) => w.length > 0).map((w) => vocab[w] ?? 0);
|
|
2977
|
+
}
|
|
2978
|
+
return Array.from(textStr).map((c) => c.codePointAt(0) ?? 0);
|
|
2979
|
+
}
|
|
2980
|
+
function evalDataPad(args, evaluate2, ctx) {
|
|
2981
|
+
const data = evaluate2(args[0], ctx);
|
|
2982
|
+
const config = evaluate2(args[1], ctx);
|
|
2983
|
+
const currentLen = (() => {
|
|
2984
|
+
const shape = tensorShape2(data);
|
|
2985
|
+
return shape.length === 0 ? 0 : shape[shape.length - 1];
|
|
2986
|
+
})();
|
|
2987
|
+
const targetLen = config.length ?? config.targetLength ?? currentLen;
|
|
2988
|
+
const padValue = config.padValue ?? config.pad_value ?? 0;
|
|
2989
|
+
return padOrTruncateLastDim(data, targetLen, padValue);
|
|
2990
|
+
}
|
|
2540
2991
|
|
|
2541
2992
|
// std/llm.ts
|
|
2542
2993
|
function evalLlmGenerate(args, evaluate2, ctx) {
|
|
@@ -4255,6 +4706,10 @@ var SExpressionEvaluator = class {
|
|
|
4255
4706
|
return evalArrayTakeLast(args, evaluate2, ctx);
|
|
4256
4707
|
case "array/dropLast":
|
|
4257
4708
|
return evalArrayDropLast(args, evaluate2, ctx);
|
|
4709
|
+
case "array/cosine":
|
|
4710
|
+
return evalArrayCosine(args, evaluate2, ctx);
|
|
4711
|
+
case "array/nearest":
|
|
4712
|
+
return evalArrayNearest(args, evaluate2, ctx);
|
|
4258
4713
|
// ===============================
|
|
4259
4714
|
// Standard Library: object/*
|
|
4260
4715
|
// ===============================
|
|
@@ -4593,6 +5048,69 @@ var SExpressionEvaluator = class {
|
|
|
4593
5048
|
return evalIntegrationGithubGetRepo(args, evaluate2, ctx);
|
|
4594
5049
|
case "integration/github-create-issue":
|
|
4595
5050
|
return evalIntegrationGithubCreateIssue(args, evaluate2, ctx);
|
|
5051
|
+
// ===============================
|
|
5052
|
+
// Standard Library: contract/*
|
|
5053
|
+
// ===============================
|
|
5054
|
+
case "contract/validate-input":
|
|
5055
|
+
return evalContractValidateInput(args, evaluate2, ctx);
|
|
5056
|
+
case "contract/validate-output":
|
|
5057
|
+
return evalContractValidateOutput(args, evaluate2, ctx);
|
|
5058
|
+
case "contract/clamp-output":
|
|
5059
|
+
return evalContractClampOutput(args, evaluate2, ctx);
|
|
5060
|
+
case "contract/violations":
|
|
5061
|
+
return evalContractViolations(args, evaluate2, ctx);
|
|
5062
|
+
case "contract/entity-to-tensor":
|
|
5063
|
+
return evalContractEntityToTensor(args, evaluate2, ctx);
|
|
5064
|
+
case "contract/tensor-to-payload":
|
|
5065
|
+
return evalContractTensorToPayload(args, evaluate2, ctx);
|
|
5066
|
+
// ===============================
|
|
5067
|
+
// Standard Library: graph/*
|
|
5068
|
+
// ===============================
|
|
5069
|
+
case "graph/from-entities":
|
|
5070
|
+
return evalGraphFromEntities(args, evaluate2, ctx);
|
|
5071
|
+
case "graph/from-adjacency":
|
|
5072
|
+
return evalGraphFromAdjacency(args, evaluate2, ctx);
|
|
5073
|
+
case "graph/from-edge-list":
|
|
5074
|
+
return evalGraphFromEdgeList(args, evaluate2, ctx);
|
|
5075
|
+
case "graph/add-self-loops":
|
|
5076
|
+
return evalGraphAddSelfLoops(args, evaluate2, ctx);
|
|
5077
|
+
case "graph/to-undirected":
|
|
5078
|
+
return evalGraphToUndirected(args, evaluate2, ctx);
|
|
5079
|
+
case "graph/subgraph":
|
|
5080
|
+
return evalGraphSubgraph(args, evaluate2, ctx);
|
|
5081
|
+
case "graph/k-hop":
|
|
5082
|
+
return evalGraphKHop(args, evaluate2, ctx);
|
|
5083
|
+
case "graph/node-features":
|
|
5084
|
+
return evalGraphNodeFeatures(args, evaluate2, ctx);
|
|
5085
|
+
case "graph/edge-index":
|
|
5086
|
+
return evalGraphEdgeIndex(args, evaluate2, ctx);
|
|
5087
|
+
case "graph/edge-features":
|
|
5088
|
+
return evalGraphEdgeFeatures(args, evaluate2, ctx);
|
|
5089
|
+
case "graph/num-nodes":
|
|
5090
|
+
return evalGraphNumNodes(args, evaluate2, ctx);
|
|
5091
|
+
case "graph/num-edges":
|
|
5092
|
+
return evalGraphNumEdges(args, evaluate2, ctx);
|
|
5093
|
+
case "graph/degree":
|
|
5094
|
+
return evalGraphDegree(args, evaluate2, ctx);
|
|
5095
|
+
case "graph/batch":
|
|
5096
|
+
return evalGraphBatch(args, evaluate2, ctx);
|
|
5097
|
+
// ===============================
|
|
5098
|
+
// Standard Library: data/*
|
|
5099
|
+
// ===============================
|
|
5100
|
+
case "data/dataset":
|
|
5101
|
+
return evalDataDataset(args, evaluate2, ctx);
|
|
5102
|
+
case "data/dataloader":
|
|
5103
|
+
return evalDataDataloader(args, evaluate2, ctx);
|
|
5104
|
+
case "data/split":
|
|
5105
|
+
return evalDataSplit(args, evaluate2, ctx);
|
|
5106
|
+
case "data/normalize":
|
|
5107
|
+
return evalDataNormalize(args, evaluate2, ctx);
|
|
5108
|
+
case "data/augment":
|
|
5109
|
+
return evalDataAugment(args, evaluate2, ctx);
|
|
5110
|
+
case "data/tokenize":
|
|
5111
|
+
return evalDataTokenize(args, evaluate2, ctx);
|
|
5112
|
+
case "data/pad":
|
|
5113
|
+
return evalDataPad(args, evaluate2, ctx);
|
|
4596
5114
|
default:
|
|
4597
5115
|
return UNKNOWN_OPERATOR;
|
|
4598
5116
|
}
|
|
@@ -4612,6 +5130,9 @@ function executeEffects(effects, ctx) {
|
|
|
4612
5130
|
evaluator.executeEffects(effects, ctx);
|
|
4613
5131
|
}
|
|
4614
5132
|
|
|
4615
|
-
|
|
5133
|
+
// listen-payload.ts
|
|
5134
|
+
var evaluateListenPayloadExpr = (expr, payload) => evaluate(expr, createMinimalContext({}, payload));
|
|
5135
|
+
|
|
5136
|
+
export { SExpressionEvaluator, createChildContext, createEffectContext, createMinimalContext, evalAbs, evalAdd, evalAnd, evalAtomic, evalCallService, evalCeil, evalClamp, evalConcat, evalCount, evalDecrement, evalDeref, evalDespawn, evalDivide, evalDo, evalEmit, evalEmpty, evalEqual, evalFilter, evalFind, evalFirst, evalFloor, evalFn, evalGreaterThan, evalGreaterThanOrEqual, evalIf, evalIncludes, evalIncrement, evalLast, evalLessThan, evalLessThanOrEqual, evalLet, evalList, evalMap, evalMatches, evalMax, evalMin, evalModulo, evalMultiply, evalNavigate, evalNot, evalNotEqual, evalNotify, evalNth, evalOr, evalPersist, evalRef, evalRenderUI, evalRound, evalSet, evalSetDynamic, evalSpawn, evalSubtract, evalSum, evalSwap, evalWatch, evalWhen, evaluate, evaluateGuard, evaluateListenPayloadExpr, evaluator, executeEffect, executeEffects, resolveBinding };
|
|
4616
5137
|
//# sourceMappingURL=index.js.map
|
|
4617
5138
|
//# sourceMappingURL=index.js.map
|