Skip to content

Commit 1ca1ce9

Browse files
author
hzq
committed
Enforce bundle budgets while collecting assets
Share decoded bytes and file slots across declared assets and imported skills. Stop on a confirmed overflow without opening later inputs, preserve individual file errors, and verify received bundles within the same limits. Improvement-Round: 7/10 after v0.0.74
1 parent aff9a2b commit 1ca1ce9

8 files changed

Lines changed: 374 additions & 23 deletions

File tree

‎docs/cli.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,8 @@ evidence in [evidence.md](evidence.md)), which keeps its own command line.
185185

186186
With `--skill DIR`, the name, description, packaged entry and its SHA-256 come from one read of the root `SKILL.md` (up to 200,000 bytes). If the entry is missing or no longer a regular file when the directory is listed, the build fails. Other files are read separately: finish multi-file edits before building, then use `publish-bundle` to publish the bytes you reviewed.
187187

188+
Explicit assets and imported skill files share a maximum of 500 files and 8 MiB of decoded content. The builder stops opening assets as soon as it confirms either limit would be exceeded. At exactly 8 MiB, empty files still fit if file slots remain. The complete compact JSON bundle, including metadata and base64, has a separate 12 MiB limit.
189+
188190
## Call agents and read results
189191

190192
| Command | What it does | Example |

‎docs/zh-CN/cli.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,8 @@
139139

140140
`--skill DIR` 只读取一次根目录的 `SKILL.md`(上限 200,000 字节),技能名称、描述、包内入口文件及其 SHA-256 都来自这次读取。列出目录时,如果入口已消失或不再是普通文件,构建会失败。其他文件单独读取:涉及多个文件的修改请先保存,再构建;要发布已审阅的内容,请用 `publish-bundle`。
141141

142+
显式选中的资源与所有导入的技能文件合计最多 500 个,解码后总计不超过 8 MiB。构建器一旦确认其中一项超限,就不再打开后续资源。恰好 8 MiB 时,只要文件数量还有余量,仍可包含空文件。整个包的紧凑 JSON 表示(含元数据和 base64)另有 12 MiB 上限。
143+
142144
## 调用智能体并读取结果
143145

144146
| 命令 | 作用 | 示例 |

‎src/core/contracts.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { z } from 'zod';
2-
import { GRAPH_LIMITS, PROVIDER_STATE_LIMITS } from './limits.js';
2+
import { BUNDLE_LIMITS, GRAPH_LIMITS, PROVIDER_STATE_LIMITS } from './limits.js';
33
import { modelPolicySchema, modelRouteSchema, isRoutingModeId } from './model-catalog.js';
44
import { MAX_AGENT_MODELS } from './model-catalog.js';
55
import { agentAccessSchema, type ConnectionDefaults, type ToolBoundary } from './agent-access.js';
@@ -224,7 +224,7 @@ export const bundleSchema = z
224224
})
225225
.strict(),
226226
)
227-
.max(500),
227+
.max(BUNDLE_LIMITS.files),
228228
digest: z.string().regex(/^[a-f0-9]{64}$/),
229229
})
230230
.strict();

‎src/core/limits.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,13 @@ export const ACTION_PREVIEW_BYTES = 8000;
99
export const TOOL_RESULT_JSON_BYTES = 1_048_576;
1010
/** Native replay state for one provider turn, including its JSON envelope. */
1111
export const PROVIDER_STATE_LIMITS = { bytes: 2_000_000, items: 4096 } as const;
12+
/** The default for one local file is independent of the budget for a whole bundle. */
13+
export const DEFAULT_LOCAL_FILE_BYTES = 8 * 1024 * 1024;
14+
export const BUNDLE_LIMITS = {
15+
files: 500,
16+
decodedBytes: 8 * 1024 * 1024,
17+
serializedBytes: 12 * 1024 * 1024,
18+
} as const;
1219

1320
export const LIMITS = {
1421
/** 每个 owner 同时未完成的请求数(kernel:超出报 concurrency_limit)。 */

‎src/core/local-file-bytes.ts‎

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,21 @@ import { LIMITS } from './limits.js';
55
const READ_WINDOW = 1024 * 1024;
66
const MAX_INITIAL_HINT = 8 * READ_WINDOW;
77

8+
export type FileSizeErrorFactory = (bytesAtLeast: number) => Error | undefined;
9+
10+
function refuseSize(observed: number, budget: number, sizeError?: FileSizeErrorFactory): undefined {
11+
const error = observed > budget ? sizeError?.(observed) : undefined;
12+
if (error) throw error;
13+
return undefined;
14+
}
15+
816
/** Return bytes only at EOF. A non-regular file, inadmissible size or the first byte over
9-
* budget refuses the whole read. The caller owns and closes the descriptor. */
17+
* budget refuses the whole read. Only a confirmed byte overflow can select a different
18+
* size error. The caller owns and closes the descriptor. */
1019
export async function readLocalFileBytes(
1120
file: FileHandle,
1221
budget: number,
22+
sizeError?: FileSizeErrorFactory,
1323
): Promise<Buffer | undefined> {
1424
const maximum = Math.min(budget, bufferLimits.MAX_LENGTH);
1525
const stat = await file.stat(),
@@ -19,10 +29,10 @@ export async function readLocalFileBytes(
1929
!Number.isSafeInteger(budget) ||
2030
budget < 0 ||
2131
!Number.isSafeInteger(size) ||
22-
size < 0 ||
23-
size > maximum
32+
size < 0
2433
)
2534
return undefined;
35+
if (size > maximum) return refuseSize(size, budget, sizeError);
2636
let block = Buffer.allocUnsafeSlow(size <= MAX_INITIAL_HINT ? size : 64 * 1024);
2737
let largeHint = size > MAX_INITIAL_HINT && size <= LIMITS.maxArtifactExportBytes ? size : 0;
2838
let full: Buffer[] | undefined;
@@ -46,7 +56,7 @@ export async function readLocalFileBytes(
4656

4757
// Reaching the reported size, even zero or the exact limit, is not EOF.
4858
if (!(await file.read(probe, 0, 1, null)).bytesRead) break;
49-
if (total === maximum) return undefined;
59+
if (total === maximum) return refuseSize(total + 1, budget, sizeError);
5060
const hint = largeHint;
5161
largeHint = 0;
5262
if (hint && (await file.stat()).size === hint) {

‎src/core/util.ts‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
import { createHash, randomUUID, timingSafeEqual } from 'node:crypto';
2-
import { TOOL_RESULT_JSON_BYTES } from './limits.js';
2+
import { DEFAULT_LOCAL_FILE_BYTES, TOOL_RESULT_JSON_BYTES } from './limits.js';
33
import { resolveWindowsCommand } from './which.js';
44
import { restrictToOwner } from './win-acl.js';
55
import { windowsUnsafeSegment } from './win-path.js';
6-
import { readLocalFileBytes } from './local-file-bytes.js';
6+
import { readLocalFileBytes, type FileSizeErrorFactory } from './local-file-bytes.js';
77
import { constants, accessSync, statSync } from 'node:fs';
88
import { mkdir, lstat, realpath, readFile, open } from 'node:fs/promises';
99
import path from 'node:path';
@@ -256,7 +256,8 @@ export async function writePrivate(
256256
export async function readBounded(
257257
root: string,
258258
name: string,
259-
max = 8 * 1024 * 1024,
259+
max = DEFAULT_LOCAL_FILE_BYTES,
260+
sizeError?: FileSizeErrorFactory,
260261
): Promise<Buffer> {
261262
if (!Number.isSafeInteger(max) || max < 0)
262263
throw new Fault('invalid_file', 'File byte limit must be a non-negative safe integer.', 400);
@@ -266,7 +267,7 @@ export async function readBounded(
266267
constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0),
267268
);
268269
try {
269-
const bytes = await readLocalFileBytes(handle, max);
270+
const bytes = await readLocalFileBytes(handle, max, sizeError);
270271
if (bytes === undefined) throw invalidFile();
271272
return bytes;
272273
} finally {

‎src/lang/bundle.ts‎

Lines changed: 49 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ import {
1010
} from '../core/contracts.js';
1111
import { canonical, Fault, readBounded, relativeName, sha, writePrivate } from '../core/util.js';
1212
import { JsonSchemas } from '../core/schemas.js';
13+
import { BUNDLE_LIMITS, DEFAULT_LOCAL_FILE_BYTES } from '../core/limits.js';
14+
import { chargeJson, JsonByteBudget } from '../core/bounded-json.js';
1315
import { SKILL_ENTRY_FILE } from '../core/skill-files.js';
1416
import { compileOaaLang } from './lang.js';
1517
import { validateWorkflows } from './graph.js';
@@ -19,6 +21,9 @@ import { builtin, builtinNames, type BuiltinToolName } from '../core/builtins.js
1921
export { builtin } from '../core/builtins.js';
2022

2123
const schemas = new JsonSchemas();
24+
const decodedLimit = () => new Fault('bundle_too_large', 'Decoded bundle exceeds 8 MiB.', 413);
25+
const serializedLimit = () => new Fault('bundle_too_large', 'Bundle exceeds 12 MiB.', 413);
26+
const fileCountLimit = () => new Fault('bundle_too_large', 'Too many selected files.');
2227

2328
const forbiddenName =
2429
/(^|\/)(?:\.env(?:\..*)?|\.git|node_modules|auth\.json|credentials[^/]*|[^/]*\.(?:pem|key|p12|pfx)|id_rsa|id_ed25519)(\/|$)/i;
@@ -66,24 +71,29 @@ export function assertPublishableMetadata(value: unknown): void {
6671
export function validateBundle(raw: unknown): AgentBundle {
6772
const bundle = bundleSchema.parse(raw);
6873
assertPublishableMetadata(bundle.agent);
69-
if (Buffer.byteLength(JSON.stringify(bundle)) > 12 * 1024 * 1024)
70-
throw new Fault('bundle_too_large', 'Bundle exceeds 12 MiB.', 413);
74+
chargeJson(bundle, new JsonByteBudget(BUNDLE_LIMITS.serializedBytes, serializedLimit));
7175
const paths = new Set<string>();
72-
let bytes = 0;
76+
let remaining = BUNDLE_LIMITS.decodedBytes;
7377
for (const file of bundle.files) {
7478
relativeName(file.path);
7579
if (forbiddenName.test(file.path) || paths.has(file.path))
7680
throw new Fault('unsafe_bundle', `Forbidden or duplicate bundle path: ${file.path}`);
7781
paths.add(file.path);
78-
const contents = Buffer.from(file.content, 'base64');
79-
if (contents.toString('base64') !== file.content || sha(contents) !== file.sha256)
82+
// One four-character group proves overflow at the boundary. A prefix alone can
83+
// refuse a file, never certify its encoding, checksum or content.
84+
const prefix = file.content.slice(0, 4 * (Math.floor(remaining / 3) + 1));
85+
const contents = Buffer.from(prefix, 'base64');
86+
if (contents.byteLength > remaining) throw decodedLimit();
87+
if (
88+
prefix.length !== file.content.length ||
89+
contents.toString('base64') !== file.content ||
90+
sha(contents) !== file.sha256
91+
)
8092
throw new Fault('bundle_integrity', `Invalid content digest: ${file.path}`);
8193
if (secretPattern.test(contents.toString('utf8')))
8294
throw new Fault('secret_in_bundle', `Possible secret in ${file.path}; publication refused.`);
83-
bytes += contents.byteLength;
95+
remaining -= contents.byteLength;
8496
}
85-
if (bytes > 8 * 1024 * 1024)
86-
throw new Fault('bundle_too_large', 'Decoded bundle exceeds 8 MiB.', 413);
8797
for (const s of bundle.agent.skills)
8898
if (!paths.has(s.path)) throw new Fault('missing_skill', `Missing skill: ${s.path}`);
8999
for (const t of bundle.agent.tools)
@@ -131,6 +141,30 @@ function importedSkillHeader(bytes: Buffer): { name: string; description: string
131141
return { name: meta.name, description: meta.description };
132142
}
133143

144+
function bundleInputs(requiredFiles: number) {
145+
let extraSlots = BUNDLE_LIMITS.files - requiredFiles;
146+
if (extraSlots < 0) throw fileCountLimit();
147+
let remaining = BUNDLE_LIMITS.decodedBytes;
148+
async function read(root: string, name: string, fileLimit = DEFAULT_LOCAL_FILE_BYTES) {
149+
// A known breach of the individual limit retains the local reader's own error.
150+
const bytes = await readBounded(root, name, Math.min(remaining, fileLimit), (observed) =>
151+
observed > fileLimit ? undefined : decodedLimit(),
152+
);
153+
// Charge on capture, not on traversal or encoding: a skill's root can be listed last.
154+
remaining -= bytes.byteLength;
155+
return bytes;
156+
}
157+
return {
158+
declared: read,
159+
discovered(root: string, name: string) {
160+
// Directory assets cannot spend a slot reserved for another requested skill entry.
161+
if (!extraSlots) throw fileCountLimit();
162+
extraSlots--;
163+
return read(root, name);
164+
},
165+
};
166+
}
167+
134168
export async function buildBundle(
135169
definitionPath: string,
136170
skills: string[] = [],
@@ -158,19 +192,21 @@ export async function buildBundle(
158192
}
159193
if (!Array.isArray(selected) || selected.some((x) => typeof x !== 'string'))
160194
throw new Fault('invalid_manifest', 'files must be an explicit list of relative paths.');
195+
const inputs = bundleInputs(selected.length + skills.length);
196+
const skillDirs = [...skills];
161197
for (const selected of bindings) {
162198
const absolute = path.resolve(selected);
163199
const contents = await readBounded(path.dirname(absolute), path.basename(absolute), 1_000_000);
164200
agent.tools.push(bindingSchema.parse(JSON.parse(contents.toString('utf8'))));
165201
}
166202
const files: AgentBundle['files'] = [];
167203
for (const name of selected as string[]) {
168-
const bytes = await readBounded(root, relativeName(name));
204+
const bytes = await inputs.declared(root, relativeName(name));
169205
files.push({ path: name, content: bytes.toString('base64'), sha256: sha(bytes) });
170206
}
171-
for (const dir of skills) {
207+
for (const dir of skillDirs) {
172208
const skillRoot = await realpath(dir);
173-
const entryBytes = await readBounded(skillRoot, SKILL_ENTRY_FILE, 200_000);
209+
const entryBytes = await inputs.declared(skillRoot, SKILL_ENTRY_FILE, 200_000);
174210
const meta = importedSkillHeader(entryBytes);
175211
const prefix = `skills/${meta.name}`,
176212
entryPath = `${prefix}/${SKILL_ENTRY_FILE}`;
@@ -192,13 +228,13 @@ export async function buildBundle(
192228
throw new Fault('unsafe_bundle', `Forbidden skill file: ${name}`);
193229
if (entry.isDirectory()) await walk(name);
194230
else if (entry.isFile()) {
195-
const data = name === SKILL_ENTRY_FILE ? entryBytes : await readBounded(skillRoot, name);
231+
const data =
232+
name === SKILL_ENTRY_FILE ? entryBytes : await inputs.discovered(skillRoot, name);
196233
files.push({
197234
path: `${prefix}/${name}`,
198235
content: data.toString('base64'),
199236
sha256: sha(data),
200237
});
201-
if (files.length > 500) throw new Fault('bundle_too_large', 'Too many selected files.');
202238
} else throw new Fault('unsafe_bundle', 'Only regular files are publishable.');
203239
}
204240
}

0 commit comments

Comments
 (0)