Skip to content

Commit b0a6dc3

Browse files
author
hzq
committed
Check foreach template text budgets during rendering
Bound text segments and JSON interpolation before concatenation. Use the remaining argument allowance without charging retained text twice, and bound predicate template expansion before dispatch.
1 parent d0c69cc commit b0a6dc3

6 files changed

Lines changed: 300 additions & 13 deletions

File tree

‎docs/language.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -274,6 +274,8 @@ The source length is checked **before** filtering. All predicates of one map are
274274

275275
Each `foreach` preflight shares a **1,048,576-item collection budget** across its source snapshot, predicates, and the arguments of selected items. Reference copies and template serialization count, and the per-expression limit still applies. All selected arguments are resolved before the first item is dispatched, and reused on retries. Prepared argument strings and keys may occupy up to **24 MiB of UTF-8 text** per loop. An invalid reference or excess work or text fails preflight before any item is dispatched. Unselected arguments and unused fallbacks are not evaluated, and tool-specific validation and authorization still apply at dispatch.
276276

277+
Preflight checks template expansion while it is being rendered, including interpolated JSON. Argument templates use the remaining prepared-text allowance, and predicate templates share a separate **24 MiB UTF-8 expansion budget** per loop. Exceeding either allowance stops rendering without dispatching an item.
278+
277279
`retry` and `timeout` are allowed only on read-only or `idempotent-write` tools; otherwise compilation reports `unsafe_graph_retry`. While waiting for approval, when the run is cancelled, or when the outcome of a side effect is unknown, there is no retry, and the failure is not hidden by a fallback value.
278280

279281
```oaa

‎docs/zh-CN/language.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -274,6 +274,8 @@ agent "agent/delegates" {
274274

275275
一次 `foreach` 的源列表快照、全部条件和选中项的参数共用 **1,048,576 项集合预算**。引用复制和模板序列化也计入,单个表达式原有上限仍然有效。第一项派发前会解析全部选中项的参数,重试复用解析结果。每个循环准备的参数字符串及键名最多占 **24 MiB UTF-8 文本**。引用无效或超出预算时,该循环不会派发任何一项。未选中项的参数和未触发的回退不解析;工具自己的参数校验和授权仍在派发时执行。
276276

277+
预检在模板拼接时检查文本额度,插值里的 JSON 也计入。参数模板使用尚未占用的预留文本额度;同一个循环的条件模板另共用 **24 MiB UTF-8 展开预算**。任一额度用尽时停止拼接,不派发循环项。
278+
277279
`retry` 与 `timeout` 只允许用在只读或 `idempotent-write` 的工具上,否则编译期报 `unsafe_graph_retry`。等待审批、运行取消、副作用结果未知时不会重试,也不会被回退值掩盖。
278280

279281
```oaa

‎src/lang/expression-budget.ts‎

Lines changed: 35 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -46,20 +46,47 @@ export class CollectionBudget {
4646
}
4747
}
4848

49+
export class TextBudget {
50+
constructor(
51+
private remaining: number,
52+
private readonly message: string,
53+
) {}
54+
55+
check(bytes: number): void {
56+
if (bytes > this.remaining) throw new Fault('expression_budget_exceeded', this.message);
57+
}
58+
59+
charge(bytes: number): void {
60+
this.check(bytes);
61+
this.remaining -= bytes;
62+
}
63+
64+
chargeText(text: string): void {
65+
this.check(text.length);
66+
this.charge(Buffer.byteLength(text));
67+
}
68+
69+
draft(message: string): TextBudget {
70+
return new TextBudget(this.remaining, message);
71+
}
72+
}
73+
4974
/** Limit the text retained for a prepared map in addition to its collection slots. */
5075
export class PreparedArgumentsBudget {
51-
private remaining: number = FOREACH_ARGUMENT_TEXT_BYTES;
76+
private readonly text = new TextBudget(
77+
FOREACH_ARGUMENT_TEXT_BYTES,
78+
'Foreach prepared argument text exceeded its byte budget.',
79+
);
5280

5381
constructor(private readonly collection: CollectionBudget) {}
5482

83+
templateDraft(): TextBudget {
84+
// Rendering gets a provisional allowance; reserve charges the complete argument only once.
85+
return this.text.draft('Foreach argument template expansion exceeded its byte budget.');
86+
}
87+
5588
reserve(value: Record<string, unknown>): void {
56-
this.collection.visitShape(value, true, (text) => {
57-
if (text.length > this.remaining || (this.remaining -= Buffer.byteLength(text)) < 0)
58-
throw new Fault(
59-
'expression_budget_exceeded',
60-
'Foreach prepared argument text exceeded its byte budget.',
61-
);
62-
});
89+
this.collection.visitShape(value, true, (text) => this.text.chargeText(text));
6390
}
6491
}
6592

‎src/lang/graph.ts‎

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,12 @@ import {
2424
import {
2525
CollectionBudget,
2626
ExpressionBudget,
27+
FOREACH_ARGUMENT_TEXT_BYTES,
2728
FOREACH_COLLECTION_LIMIT,
2829
PreparedArgumentsBudget,
30+
TextBudget,
2931
} from './expression-budget.js';
32+
import { renderBoundedTemplate, templateReferences } from './template-text.js';
3033

3134
export function graphEffect(
3235
steps: readonly { tool?: unknown; fallback?: unknown }[],
@@ -971,10 +974,11 @@ export function resolveReferences(
971974
value: unknown,
972975
results: Map<string, unknown>,
973976
shared?: CollectionBudget,
977+
templateBudget?: TextBudget,
974978
): unknown {
975979
if (Array.isArray(value)) {
976980
shared?.scan(value.length);
977-
return value.map((v) => resolveReferences(v, results, shared));
981+
return value.map((v) => resolveReferences(v, results, shared, templateBudget));
978982
}
979983
if (!value || typeof value !== 'object') return value;
980984
const o = value as Record<string, unknown>;
@@ -993,12 +997,17 @@ export function resolveReferences(
993997
}
994998
}
995999
if ('$template' in o && typeof o.$template === 'string') {
996-
return o.$template.replaceAll(/\{\{(\$?[A-Za-z0-9_-]+(?:#[^}]*)?)\}\}/g, (_match, ref) => {
997-
const [name, pointer] = (ref as string).split('#');
1000+
const lookup = (ref: string) => {
1001+
const [name, pointer] = ref.split('#');
9981002
if (!results.has(name!))
9991003
throw new Fault('invalid_reference', 'Referenced step has not completed.');
10001004
const val = copyResolvedValue(pointerTarget(results.get(name!), pointer), shared);
10011005
shared?.visitShape(val);
1006+
return val;
1007+
};
1008+
if (templateBudget) return renderBoundedTemplate(o.$template, lookup, templateBudget);
1009+
return o.$template.replaceAll(templateReferences, (_match, ref: string) => {
1010+
const val = lookup(ref);
10021011
return typeof val === 'object' && val !== null ? JSON.stringify(val) : String(val ?? '');
10031012
});
10041013
}
@@ -1007,7 +1016,9 @@ export function resolveReferences(
10071016
}
10081017
const entries = Object.entries(o);
10091018
shared?.scan(entries.length);
1010-
return Object.fromEntries(entries.map(([k, v]) => [k, resolveReferences(v, results, shared)]));
1019+
return Object.fromEntries(
1020+
entries.map(([k, v]) => [k, resolveReferences(v, results, shared, templateBudget)]),
1021+
);
10111022
}
10121023

10131024
async function runSingleInvocation(
@@ -1192,6 +1203,10 @@ export async function executeGraph(
11921203
state.items = copyResolvedValue(items, preflight) as unknown[];
11931204
if (step.foreach.where !== undefined) {
11941205
// Validate all predicates before dispatching any side effect of this map.
1206+
const predicateText = new TextBudget(
1207+
FOREACH_ARGUMENT_TEXT_BYTES,
1208+
'Foreach predicate template expansion exceeded its byte budget.',
1209+
);
11951210
state.selected = [];
11961211
for (const [index, item] of state.items.entries()) {
11971212
// Even an all-false graph must let cancellation and active siblings run.
@@ -1203,6 +1218,7 @@ export async function executeGraph(
12031218
step.foreach.where,
12041219
itemScope(step.foreach.as, item, index),
12051220
preflight,
1221+
predicateText,
12061222
)
12071223
)
12081224
state.selected.push(index);
@@ -1222,7 +1238,12 @@ export async function executeGraph(
12221238
if (stopping) break;
12231239
const index = state.selected?.[slot] ?? slot;
12241240
const scope = itemScope(step.foreach.as, state.items[index], index);
1225-
const args = resolveReferences(step.arguments, scope, preflight);
1241+
const args = resolveReferences(
1242+
step.arguments,
1243+
scope,
1244+
preflight,
1245+
argumentBudget.templateDraft(),
1246+
);
12261247
if (!args || typeof args !== 'object' || Array.isArray(args))
12271248
throw new Fault(
12281249
'invalid_tool_arguments',

‎src/lang/template-text.ts‎

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
import type { TextBudget } from './expression-budget.js';
2+
3+
const high = (code: number) => code >= 0xd800 && code <= 0xdbff;
4+
const low = (code: number) => code >= 0xdc00 && code <= 0xdfff;
5+
6+
export const templateReferences = /\{\{(\$?[A-Za-z0-9_-]+(?:#[^}]*)?)\}\}/g;
7+
8+
function chargeQuoted(text: string, budget: TextBudget): void {
9+
budget.check(text.length + 2);
10+
budget.charge(2);
11+
for (let from = 0; from < text.length;) {
12+
let to = Math.min(text.length, from + 4096);
13+
if (to < text.length && high(text.charCodeAt(to - 1)) && low(text.charCodeAt(to))) to--;
14+
budget.charge(Buffer.byteLength(JSON.stringify(text.slice(from, to))) - 2);
15+
from = to;
16+
}
17+
}
18+
19+
function unbox(value: unknown): unknown {
20+
if (value instanceof String) return String.prototype.valueOf.call(value);
21+
if (value instanceof Number) return Number.prototype.valueOf.call(value);
22+
if (value instanceof Boolean) return Boolean.prototype.valueOf.call(value);
23+
return value;
24+
}
25+
26+
function stringifyBounded(value: object, budget: TextBudget): string | undefined {
27+
const emitted = new WeakSet<object>();
28+
let root = true;
29+
// The replacer charges the native serializer before it emits each property or element.
30+
return JSON.stringify(value, function (this: object, key, member: unknown) {
31+
const parentIsArray = Array.isArray(this);
32+
const omitted =
33+
member === undefined || typeof member === 'symbol' || typeof member === 'function';
34+
const isRoot = root;
35+
root = false;
36+
if (omitted && !parentIsArray) return member;
37+
if (!isRoot) {
38+
if (emitted.has(this)) budget.charge(1);
39+
emitted.add(this);
40+
if (!parentIsArray) {
41+
chargeQuoted(key, budget);
42+
budget.charge(1);
43+
}
44+
}
45+
const scalar = unbox(member);
46+
if (omitted)
47+
budget.charge(4); // Empty array slots serialize as null.
48+
else if (typeof scalar === 'string') chargeQuoted(scalar, budget);
49+
else if (scalar && typeof scalar === 'object') {
50+
budget.charge(2);
51+
emitted.delete(scalar); // A reused object has its own comma count each time it is visited.
52+
} else budget.charge(JSON.stringify(scalar).length);
53+
return member;
54+
});
55+
}
56+
57+
/** Check before concatenating segments, including JSON values expanded into the template. */
58+
export function renderBoundedTemplate(
59+
template: string,
60+
resolve: (ref: string) => unknown,
61+
budget: TextBudget,
62+
): string {
63+
const parts: string[] = [];
64+
let leadingSurrogate = '';
65+
const push = (text: string) => {
66+
budget.chargeText(text);
67+
parts.push(text);
68+
};
69+
const flush = () => {
70+
if (leadingSurrogate) push(leadingSurrogate);
71+
leadingSurrogate = '';
72+
};
73+
const append = (text: string) => {
74+
if (!text.length) return;
75+
// Two segments can together form one UTF-8 code point, even across an empty substitution.
76+
if (leadingSurrogate && low(text.charCodeAt(0))) {
77+
push(leadingSurrogate + text[0]);
78+
leadingSurrogate = '';
79+
text = text.slice(1);
80+
} else flush();
81+
if (high(text.charCodeAt(text.length - 1))) {
82+
leadingSurrogate = text.at(-1)!;
83+
text = text.slice(0, -1);
84+
}
85+
if (text.length) push(text);
86+
};
87+
let from = 0;
88+
for (const match of template.matchAll(templateReferences)) {
89+
append(template.slice(from, match.index));
90+
const value = resolve(match[1]!);
91+
if (value && typeof value === 'object') {
92+
flush();
93+
const serialized = stringifyBounded(value, budget);
94+
if (serialized === undefined) append('undefined');
95+
else parts.push(serialized);
96+
} else append(String(value ?? ''));
97+
from = match.index + match[0].length;
98+
}
99+
append(template.slice(from));
100+
flush();
101+
return parts.join('');
102+
}

0 commit comments

Comments
 (0)