Skip to content

Commit d697a81

Browse files
author
hzq
committed
Add bounded array subscripts to OAA-Lang
Evaluate computed indices against own array elements without copying the source array. Preserve normal expression limits and dependency checks, and advertise the new syntax to clients.
1 parent 6a6e213 commit d697a81

9 files changed

Lines changed: 301 additions & 144 deletions

File tree

‎docs/language.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -314,6 +314,7 @@ agent "agent/step-block" {
314314
- A string containing `{{...}}` is a template, for example `"{{$input.prefix}}:{{doc.title}}"`; to write ordinary text that contains `{{`, use `literal("...")` (it accepts only a string).
315315
- An explicit JSON descriptor `{ "$ref": "doc#/text", "$default": "none" }` is kept as is and is no longer parsed as shorthand.
316316
- In `$(input.limit ?? 10)`, use 10 only when the field is missing or null. The operator returns the value itself, preserving 0, false and empty strings, and does not evaluate an unused default. Both operands are still checked at compile time. It binds below `||` and above `? :`; parenthesize mixed expressions for readability. Older runtimes need an upgrade before using this syntax.
317+
- `$(input.rows[input.pick] ?? "missing")` selects one array element using a computed zero-based index. Only non-negative safe integers are accepted; an invalid or out-of-range index, a missing element, or a non-array target yields `null`. It does not look up object properties or coerce numeric strings. Subscripts bind before arithmetic and can be chained for nested arrays. Require `graph-array-index-v1` in `GET /health` and upgrade any workers that install such bundles.
317318

318319
```oaa
319320
agent "agent/values" {

‎docs/zh-CN/language.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -314,6 +314,7 @@ agent "agent/step-block" {
314314
- 含 `{{...}}` 的字符串是模板,例如 `"{{$input.prefix}}:{{doc.title}}"`;要写含 `{{` 的普通文字用 `literal("...")`(只接受字符串)。
315315
- 显式的 JSON 描述符 `{ "$ref": "doc#/text", "$default": "无" }` 原样保留,不再按简写解析。
316316
- `$(input.limit ?? 10)` 只在字段缺失或为 `null` 时取 10;左侧为 0、`false`、空字符串时保留原值,且不计算右侧。两侧仍须通过编译期检查。它的优先级低于 `||`、高于 `? :`,混用时建议加括号。使用此语法前请升级旧版运行时。
317+
- `$(input.rows[input.pick] ?? "missing")` 用计算出来的零基下标读取一个数组元素。只接受非负安全整数;无效或越界的下标、缺失的元素、非数组目标都返回 `null`。不会读取对象属性,也不会把数字字符串强转为下标。下标优先于算术,可连续取嵌套数组。使用前检查 `GET /health` 中的 `graph-array-index-v1`,并升级安装这类能力包的 worker。
317318

318319
```oaa
319320
agent "agent/values" {

‎src/gateway/endpoints.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ export const GATEWAY_FEATURES = [
4444
'webhooks-v1',
4545
'workflow-output-v1',
4646
'foreach-where-v1',
47+
'graph-array-index-v1',
4748
].sort();
4849

4950
export const buildEndpointDirectory = (baseUrl: string) => {

‎src/lang/expression-builtins.ts‎

Lines changed: 144 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,144 @@
1+
import { Fault } from '../core/util.js';
2+
3+
export const SAFE_FUNCTIONS = new Set([
4+
'len',
5+
'includes',
6+
'startsWith',
7+
'endsWith',
8+
'lower',
9+
'upper',
10+
'trim',
11+
'min',
12+
'max',
13+
'round',
14+
'abs',
15+
'coalesce',
16+
'keys',
17+
'has',
18+
'join',
19+
'split',
20+
'slice',
21+
'pluck',
22+
'compact',
23+
'unique',
24+
'sum',
25+
'avg',
26+
'json',
27+
]);
28+
29+
export function evalBuiltinCall(name: string, args: unknown[]): unknown {
30+
switch (name) {
31+
case 'len': {
32+
const v = args[0];
33+
if (typeof v === 'string' || Array.isArray(v)) return v.length;
34+
if (v && typeof v === 'object') return Object.keys(v).length;
35+
return 0;
36+
}
37+
case 'includes': {
38+
const [haystack, needle] = args;
39+
if (typeof haystack === 'string') return haystack.includes(String(needle ?? ''));
40+
if (Array.isArray(haystack)) return haystack.includes(needle);
41+
return false;
42+
}
43+
case 'startsWith':
44+
return typeof args[0] === 'string' && args[0].startsWith(String(args[1] ?? ''));
45+
case 'endsWith':
46+
return typeof args[0] === 'string' && args[0].endsWith(String(args[1] ?? ''));
47+
case 'lower':
48+
return typeof args[0] === 'string' ? args[0].toLowerCase() : '';
49+
case 'upper':
50+
return typeof args[0] === 'string' ? args[0].toUpperCase() : '';
51+
case 'trim':
52+
return typeof args[0] === 'string' ? args[0].trim() : '';
53+
case 'min': {
54+
const nums = args.map(Number).filter((n) => !Number.isNaN(n));
55+
return nums.length ? Math.min(...nums) : null;
56+
}
57+
case 'max': {
58+
const nums = args.map(Number).filter((n) => !Number.isNaN(n));
59+
return nums.length ? Math.max(...nums) : null;
60+
}
61+
case 'round':
62+
return typeof args[0] === 'number' ? Math.round(args[0]) : Number.NaN;
63+
case 'abs':
64+
return typeof args[0] === 'number' ? Math.abs(args[0]) : Number.NaN;
65+
case 'coalesce':
66+
for (const item of args) {
67+
if (item !== null && item !== undefined) return item;
68+
}
69+
return null;
70+
case 'keys':
71+
return args[0] && typeof args[0] === 'object' && !Array.isArray(args[0])
72+
? Object.keys(args[0] as Record<string, unknown>)
73+
: [];
74+
case 'has':
75+
return (
76+
Boolean(args[0]) &&
77+
typeof args[0] === 'object' &&
78+
!Array.isArray(args[0]) &&
79+
typeof args[1] === 'string' &&
80+
!['__proto__', 'prototype', 'constructor'].includes(args[1]) &&
81+
Object.hasOwn(args[0] as object, args[1])
82+
);
83+
case 'join': {
84+
const [arr, sep] = args;
85+
if (!Array.isArray(arr)) return '';
86+
const out = arr
87+
.map((x) => (x === null || x === undefined ? '' : String(x)))
88+
.join(String(sep ?? ','));
89+
if (out.length > 65536) {
90+
throw new Fault('expression_budget_exceeded', 'Joined string exceeds 64 KiB.');
91+
}
92+
return out;
93+
}
94+
case 'split': {
95+
const [str, sep] = args;
96+
if (typeof str !== 'string') return [];
97+
return str.split(String(sep ?? ',')).slice(0, 256);
98+
}
99+
case 'slice': {
100+
const [target, start, end] = args;
101+
const s = Number(start ?? 0);
102+
const e = end === undefined ? undefined : Number(end);
103+
if (Array.isArray(target) || typeof target === 'string') {
104+
return target.slice(
105+
Number.isNaN(s) ? 0 : s,
106+
e !== undefined && !Number.isNaN(e) ? e : undefined,
107+
);
108+
}
109+
return [];
110+
}
111+
case 'pluck': {
112+
const [arr, key] = args;
113+
if (
114+
!Array.isArray(arr) ||
115+
typeof key !== 'string' ||
116+
['__proto__', 'prototype', 'constructor'].includes(key)
117+
)
118+
return [];
119+
return arr.map((item) =>
120+
item && typeof item === 'object' && Object.hasOwn(item as object, key)
121+
? (item as Record<string, unknown>)[key]
122+
: null,
123+
);
124+
}
125+
case 'compact':
126+
return Array.isArray(args[0])
127+
? args[0].filter((x) => x !== null && x !== undefined && x !== false && x !== '')
128+
: [];
129+
case 'unique':
130+
return Array.isArray(args[0]) ? [...new Set(args[0])] : [];
131+
case 'sum':
132+
return Array.isArray(args[0])
133+
? args[0].reduce((acc: number, v) => acc + (Number(v) || 0), 0)
134+
: 0;
135+
case 'avg':
136+
return Array.isArray(args[0]) && args[0].length > 0
137+
? args[0].reduce((acc: number, v) => acc + (Number(v) || 0), 0) / args[0].length
138+
: 0;
139+
case 'json':
140+
return JSON.stringify(args[0] ?? null);
141+
default:
142+
throw new Fault('invalid_expression', `Unknown safe function: ${name}`);
143+
}
144+
}

‎src/lang/graph.ts‎

Lines changed: 31 additions & 144 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import {
2323
collectSuspensions,
2424
} from '../core/suspension.js';
2525
import { JsonSchemas } from '../core/schemas.js';
26+
import { evalBuiltinCall, SAFE_FUNCTIONS } from './expression-builtins.js';
2627

2728
export function graphEffect(
2829
steps: readonly { tool?: unknown; fallback?: unknown }[],
@@ -112,32 +113,6 @@ interface ExprToken {
112113
value: string;
113114
}
114115

115-
const SAFE_FUNCTIONS = new Set([
116-
'len',
117-
'includes',
118-
'startsWith',
119-
'endsWith',
120-
'lower',
121-
'upper',
122-
'trim',
123-
'min',
124-
'max',
125-
'round',
126-
'abs',
127-
'coalesce',
128-
'keys',
129-
'has',
130-
'join',
131-
'split',
132-
'slice',
133-
'pluck',
134-
'compact',
135-
'unique',
136-
'sum',
137-
'avg',
138-
'json',
139-
]);
140-
141116
function tokenizeExpr(expr: string): ExprToken[] {
142117
if (expr.length > 8192) {
143118
throw new Fault('invalid_expression', 'Expression exceeds 8 KiB limit.');
@@ -293,6 +268,7 @@ type AstNode =
293268
| { kind: 'literal'; value: unknown }
294269
| { kind: 'array'; items: AstNode[] }
295270
| { kind: 'ref'; raw: string }
271+
| { kind: 'index'; target: AstNode; index: AstNode }
296272
| { kind: 'unary'; op: string; arg: AstNode }
297273
| { kind: 'binary'; op: string; left: AstNode; right: AstNode }
298274
| { kind: 'ternary'; cond: AstNode; consequent: AstNode; alternate: AstNode }
@@ -335,6 +311,14 @@ function parseExprAst(expr: string): AstNode {
335311
throw new Fault('invalid_expression', 'Expression nesting depth exceeds limit.');
336312
}
337313
let left = parsePrimary(depth + 1);
314+
let subscriptDepth = depth;
315+
while (peek().type === 'LBRACKET') {
316+
next();
317+
const index = parseExpression(0, ++subscriptDepth);
318+
if (next().type !== 'RBRACKET')
319+
throw new Fault('invalid_expression', "Expected closing ']' after an array index.");
320+
left = { kind: 'index', target: left, index };
321+
}
338322

339323
while (true) {
340324
const tok = peek();
@@ -441,128 +425,12 @@ function parseExprAst(expr: string): AstNode {
441425
return ast;
442426
}
443427

444-
function evalBuiltinCall(name: string, args: unknown[]): unknown {
445-
switch (name) {
446-
case 'len': {
447-
const v = args[0];
448-
if (typeof v === 'string' || Array.isArray(v)) return v.length;
449-
if (v && typeof v === 'object') return Object.keys(v).length;
450-
return 0;
451-
}
452-
case 'includes': {
453-
const [haystack, needle] = args;
454-
if (typeof haystack === 'string') return haystack.includes(String(needle ?? ''));
455-
if (Array.isArray(haystack)) return haystack.includes(needle);
456-
return false;
457-
}
458-
case 'startsWith':
459-
return typeof args[0] === 'string' && args[0].startsWith(String(args[1] ?? ''));
460-
case 'endsWith':
461-
return typeof args[0] === 'string' && args[0].endsWith(String(args[1] ?? ''));
462-
case 'lower':
463-
return typeof args[0] === 'string' ? args[0].toLowerCase() : '';
464-
case 'upper':
465-
return typeof args[0] === 'string' ? args[0].toUpperCase() : '';
466-
case 'trim':
467-
return typeof args[0] === 'string' ? args[0].trim() : '';
468-
case 'min': {
469-
const nums = args.map(Number).filter((n) => !Number.isNaN(n));
470-
return nums.length ? Math.min(...nums) : null;
471-
}
472-
case 'max': {
473-
const nums = args.map(Number).filter((n) => !Number.isNaN(n));
474-
return nums.length ? Math.max(...nums) : null;
475-
}
476-
case 'round':
477-
return typeof args[0] === 'number' ? Math.round(args[0]) : Number.NaN;
478-
case 'abs':
479-
return typeof args[0] === 'number' ? Math.abs(args[0]) : Number.NaN;
480-
case 'coalesce':
481-
for (const item of args) {
482-
if (item !== null && item !== undefined) return item;
483-
}
484-
return null;
485-
case 'keys':
486-
return args[0] && typeof args[0] === 'object' && !Array.isArray(args[0])
487-
? Object.keys(args[0] as Record<string, unknown>)
488-
: [];
489-
case 'has':
490-
return (
491-
Boolean(args[0]) &&
492-
typeof args[0] === 'object' &&
493-
!Array.isArray(args[0]) &&
494-
typeof args[1] === 'string' &&
495-
!['__proto__', 'prototype', 'constructor'].includes(args[1]) &&
496-
Object.hasOwn(args[0] as object, args[1])
497-
);
498-
case 'join': {
499-
const [arr, sep] = args;
500-
if (!Array.isArray(arr)) return '';
501-
const out = arr
502-
.map((x) => (x === null || x === undefined ? '' : String(x)))
503-
.join(String(sep ?? ','));
504-
if (out.length > 65536) {
505-
throw new Fault('expression_budget_exceeded', 'Joined string exceeds 64 KiB.');
506-
}
507-
return out;
508-
}
509-
case 'split': {
510-
const [str, sep] = args;
511-
if (typeof str !== 'string') return [];
512-
return str.split(String(sep ?? ',')).slice(0, 256);
513-
}
514-
case 'slice': {
515-
const [target, start, end] = args;
516-
const s = Number(start ?? 0);
517-
const e = end === undefined ? undefined : Number(end);
518-
if (Array.isArray(target) || typeof target === 'string') {
519-
return target.slice(
520-
Number.isNaN(s) ? 0 : s,
521-
e !== undefined && !Number.isNaN(e) ? e : undefined,
522-
);
523-
}
524-
return [];
525-
}
526-
case 'pluck': {
527-
const [arr, key] = args;
528-
if (
529-
!Array.isArray(arr) ||
530-
typeof key !== 'string' ||
531-
['__proto__', 'prototype', 'constructor'].includes(key)
532-
)
533-
return [];
534-
return arr.map((item) =>
535-
item && typeof item === 'object' && Object.hasOwn(item as object, key)
536-
? (item as Record<string, unknown>)[key]
537-
: null,
538-
);
539-
}
540-
case 'compact':
541-
return Array.isArray(args[0])
542-
? args[0].filter((x) => x !== null && x !== undefined && x !== false && x !== '')
543-
: [];
544-
case 'unique':
545-
return Array.isArray(args[0]) ? [...new Set(args[0])] : [];
546-
case 'sum':
547-
return Array.isArray(args[0])
548-
? args[0].reduce((acc: number, v) => acc + (Number(v) || 0), 0)
549-
: 0;
550-
case 'avg':
551-
return Array.isArray(args[0]) && args[0].length > 0
552-
? args[0].reduce((acc: number, v) => acc + (Number(v) || 0), 0) / args[0].length
553-
: 0;
554-
case 'json':
555-
return JSON.stringify(args[0] ?? null);
556-
default:
557-
throw new Fault('invalid_expression', `Unknown safe function: ${name}`);
558-
}
559-
}
560-
561428
function evalAstNode(
562429
node: AstNode,
563430
scope: Map<string, unknown>,
564431
budget: { steps: number },
565432
bareIdentAsLiteral = false,
433+
copySelected = true,
566434
): unknown {
567435
if (++budget.steps > 1024) {
568436
throw new Fault('expression_budget_exceeded', 'Expression evaluation exceeded step budget.');
@@ -579,7 +447,26 @@ function evalAstNode(
579447
return null;
580448
}
581449
try {
582-
return extractPointerValue(scope.get(name!), pointer);
450+
return (copySelected ? extractPointerValue : pointerTarget)(scope.get(name!), pointer);
451+
} catch {
452+
return null;
453+
}
454+
}
455+
case 'index': {
456+
// Select before cloning so one lookup does not copy the entire source array.
457+
const target = evalAstNode(node.target, scope, budget, bareIdentAsLiteral, false);
458+
const index = evalAstNode(node.index, scope, budget, bareIdentAsLiteral);
459+
if (
460+
!Array.isArray(target) ||
461+
typeof index !== 'number' ||
462+
!Number.isSafeInteger(index) ||
463+
index < 0 ||
464+
index >= target.length
465+
)
466+
return null;
467+
const selected: unknown = Object.getOwnPropertyDescriptor(target, index)?.value ?? null;
468+
try {
469+
return copySelected ? structuredClone(selected) : selected;
583470
} catch {
584471
return null;
585472
}

0 commit comments

Comments
 (0)