@nexum-hub/agent 0.0.0-stage → 0.0.1
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/README.md +129 -2
- package/contracts/v2/common.schema.json +262 -0
- package/contracts/v2/fixtures/inputs.json +244 -0
- package/contracts/v2/fixtures/wire.json +6493 -0
- package/contracts/v2/model/agent.close.input.schema.json +14 -0
- package/contracts/v2/model/agent.close.output.schema.json +101 -0
- package/contracts/v2/model/agent.list.input.schema.json +57 -0
- package/contracts/v2/model/agent.list.output.schema.json +220 -0
- package/contracts/v2/model/agent.open.input.schema.json +35 -0
- package/contracts/v2/model/agent.open.output.schema.json +41 -0
- package/contracts/v2/model/agent.run.cancel.input.schema.json +18 -0
- package/contracts/v2/model/agent.run.cancel.output.schema.json +100 -0
- package/contracts/v2/model/agent.run.get.input.schema.json +41 -0
- package/contracts/v2/model/agent.run.get.output.schema.json +100 -0
- package/contracts/v2/model/agent.run.input.input.schema.json +30 -0
- package/contracts/v2/model/agent.run.input.output.schema.json +100 -0
- package/contracts/v2/model/agent.run.list.input.schema.json +47 -0
- package/contracts/v2/model/agent.run.list.output.schema.json +41 -0
- package/contracts/v2/model/agent.run.start.input.schema.json +73 -0
- package/contracts/v2/model/agent.run.start.output.schema.json +100 -0
- package/contracts/v2/wire/bodies.schema.json +383 -0
- package/contracts/v2/wire/envelope.schema.json +2280 -0
- package/contracts/v2/wire/events.schema.json +242 -0
- package/contracts/v2/wire/maintenance.schema.json +308 -0
- package/contracts/v2/wire/operations.schema.json +1791 -0
- package/contracts/v2/wire/stream.schema.json +74 -0
- package/contracts/v2/wire/types.schema.json +2616 -0
- package/dist/adapters/mcp-http.d.ts +22 -0
- package/dist/adapters/mcp-http.js +472 -0
- package/dist/adapters/mcp-http.js.map +1 -0
- package/dist/adapters/mcp-oauth.d.ts +29 -0
- package/dist/adapters/mcp-oauth.js +653 -0
- package/dist/adapters/mcp-oauth.js.map +1 -0
- package/dist/adapters/mcp-wire.d.ts +21 -0
- package/dist/adapters/mcp-wire.js +307 -0
- package/dist/adapters/mcp-wire.js.map +1 -0
- package/dist/adapters/mcp.d.ts +56 -0
- package/dist/adapters/mcp.js +1989 -0
- package/dist/adapters/mcp.js.map +1 -0
- package/dist/adapters/openapi-http.d.ts +29 -0
- package/dist/adapters/openapi-http.js +504 -0
- package/dist/adapters/openapi-http.js.map +1 -0
- package/dist/adapters/openapi-request.d.ts +26 -0
- package/dist/adapters/openapi-request.js +597 -0
- package/dist/adapters/openapi-request.js.map +1 -0
- package/dist/adapters/openapi-schema.d.ts +22 -0
- package/dist/adapters/openapi-schema.js +471 -0
- package/dist/adapters/openapi-schema.js.map +1 -0
- package/dist/adapters/openapi-typegen.d.ts +11 -0
- package/dist/adapters/openapi-typegen.js +185 -0
- package/dist/adapters/openapi-typegen.js.map +1 -0
- package/dist/adapters/openapi-types.d.ts +99 -0
- package/dist/adapters/openapi-types.js +2 -0
- package/dist/adapters/openapi-types.js.map +1 -0
- package/dist/adapters/openapi.d.ts +7 -0
- package/dist/adapters/openapi.js +768 -0
- package/dist/adapters/openapi.js.map +1 -0
- package/dist/application/activation.d.ts +28 -0
- package/dist/application/activation.js +289 -0
- package/dist/application/activation.js.map +1 -0
- package/dist/application/attachments.d.ts +24 -0
- package/dist/application/attachments.js +87 -0
- package/dist/application/attachments.js.map +1 -0
- package/dist/application/authority.d.ts +32 -0
- package/dist/application/authority.js +213 -0
- package/dist/application/authority.js.map +1 -0
- package/dist/application/catalog.d.ts +11 -0
- package/dist/application/catalog.js +177 -0
- package/dist/application/catalog.js.map +1 -0
- package/dist/application/config.d.ts +24 -0
- package/dist/application/config.js +140 -0
- package/dist/application/config.js.map +1 -0
- package/dist/application/connection.d.ts +35 -0
- package/dist/application/connection.js +465 -0
- package/dist/application/connection.js.map +1 -0
- package/dist/application/data-plane.d.ts +35 -0
- package/dist/application/data-plane.js +437 -0
- package/dist/application/data-plane.js.map +1 -0
- package/dist/application/diagnostics.d.ts +4 -0
- package/dist/application/diagnostics.js +65 -0
- package/dist/application/diagnostics.js.map +1 -0
- package/dist/application/dispatcher.d.ts +4 -0
- package/dist/application/dispatcher.js +16 -0
- package/dist/application/dispatcher.js.map +1 -0
- package/dist/application/main.d.ts +12 -0
- package/dist/application/main.js +167 -0
- package/dist/application/main.js.map +1 -0
- package/dist/application/maintenance.d.ts +27 -0
- package/dist/application/maintenance.js +244 -0
- package/dist/application/maintenance.js.map +1 -0
- package/dist/application/packages.d.ts +25 -0
- package/dist/application/packages.js +208 -0
- package/dist/application/packages.js.map +1 -0
- package/dist/application/processes.d.ts +49 -0
- package/dist/application/processes.js +180 -0
- package/dist/application/processes.js.map +1 -0
- package/dist/application/run-view.d.ts +17 -0
- package/dist/application/run-view.js +286 -0
- package/dist/application/run-view.js.map +1 -0
- package/dist/application/runtime.d.ts +78 -0
- package/dist/application/runtime.js +1747 -0
- package/dist/application/runtime.js.map +1 -0
- package/dist/application/tasks.d.ts +38 -0
- package/dist/application/tasks.js +23 -0
- package/dist/application/tasks.js.map +1 -0
- package/dist/application/user-state.d.ts +20 -0
- package/dist/application/user-state.js +52 -0
- package/dist/application/user-state.js.map +1 -0
- package/dist/application/work-git.d.ts +14 -0
- package/dist/application/work-git.js +67 -0
- package/dist/application/work-git.js.map +1 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +40 -0
- package/dist/cli.js.map +1 -0
- package/dist/contracts/caller.d.ts +51 -0
- package/dist/contracts/caller.js +95 -0
- package/dist/contracts/caller.js.map +1 -0
- package/dist/contracts/error-data.d.ts +6 -0
- package/dist/contracts/error-data.js +51 -0
- package/dist/contracts/error-data.js.map +1 -0
- package/dist/contracts/errors.d.ts +10 -0
- package/dist/contracts/errors.js +28 -0
- package/dist/contracts/errors.js.map +1 -0
- package/dist/contracts/json.d.ts +9 -0
- package/dist/contracts/json.js +104 -0
- package/dist/contracts/json.js.map +1 -0
- package/dist/contracts/types.d.ts +122 -0
- package/dist/contracts/types.js +19 -0
- package/dist/contracts/types.js.map +1 -0
- package/dist/contracts/validation.d.ts +4 -0
- package/dist/contracts/validation.js +157 -0
- package/dist/contracts/validation.js.map +1 -0
- package/dist/contracts/wire-validation.d.ts +9 -0
- package/dist/contracts/wire-validation.js +399 -0
- package/dist/contracts/wire-validation.js.map +1 -0
- package/dist/contracts/wire.d.ts +1083 -0
- package/dist/contracts/wire.js +62 -0
- package/dist/contracts/wire.js.map +1 -0
- package/dist/extension-api.d.ts +12 -0
- package/dist/extension-api.js +2 -0
- package/dist/extension-api.js.map +1 -0
- package/dist/extensions/api.d.ts +72 -0
- package/dist/extensions/api.js +2 -0
- package/dist/extensions/api.js.map +1 -0
- package/dist/extensions/host-requests.d.ts +23 -0
- package/dist/extensions/host-requests.js +60 -0
- package/dist/extensions/host-requests.js.map +1 -0
- package/dist/extensions/materials.d.ts +37 -0
- package/dist/extensions/materials.js +691 -0
- package/dist/extensions/materials.js.map +1 -0
- package/dist/extensions/package-loader.d.ts +28 -0
- package/dist/extensions/package-loader.js +177 -0
- package/dist/extensions/package-loader.js.map +1 -0
- package/dist/extensions/packages.d.ts +73 -0
- package/dist/extensions/packages.js +441 -0
- package/dist/extensions/packages.js.map +1 -0
- package/dist/extensions/registry.d.ts +92 -0
- package/dist/extensions/registry.js +1540 -0
- package/dist/extensions/registry.js.map +1 -0
- package/dist/extensions/resources.d.ts +105 -0
- package/dist/extensions/resources.js +595 -0
- package/dist/extensions/resources.js.map +1 -0
- package/dist/extensions/state.d.ts +25 -0
- package/dist/extensions/state.js +10 -0
- package/dist/extensions/state.js.map +1 -0
- package/dist/extensions/transfer.d.ts +81 -0
- package/dist/extensions/transfer.js +16 -0
- package/dist/extensions/transfer.js.map +1 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +25 -0
- package/dist/index.js.map +1 -0
- package/dist/maintenance/configuration.d.ts +79 -0
- package/dist/maintenance/configuration.js +1503 -0
- package/dist/maintenance/configuration.js.map +1 -0
- package/dist/maintenance/credentials.d.ts +23 -0
- package/dist/maintenance/credentials.js +177 -0
- package/dist/maintenance/credentials.js.map +1 -0
- package/dist/maintenance/files.d.ts +2 -0
- package/dist/maintenance/files.js +40 -0
- package/dist/maintenance/files.js.map +1 -0
- package/dist/maintenance/npm.d.ts +71 -0
- package/dist/maintenance/npm.js +1013 -0
- package/dist/maintenance/npm.js.map +1 -0
- package/dist/maintenance/oauth.d.ts +45 -0
- package/dist/maintenance/oauth.js +686 -0
- package/dist/maintenance/oauth.js.map +1 -0
- package/dist/maintenance/requests.d.ts +347 -0
- package/dist/maintenance/requests.js +959 -0
- package/dist/maintenance/requests.js.map +1 -0
- package/dist/maintenance/work-git.d.ts +29 -0
- package/dist/maintenance/work-git.js +776 -0
- package/dist/maintenance/work-git.js.map +1 -0
- package/dist/process/backend.d.ts +54 -0
- package/dist/process/backend.js +39 -0
- package/dist/process/backend.js.map +1 -0
- package/dist/process/environment-windows.d.ts +15 -0
- package/dist/process/environment-windows.js +151 -0
- package/dist/process/environment-windows.js.map +1 -0
- package/dist/process/environment.d.ts +28 -0
- package/dist/process/environment.js +410 -0
- package/dist/process/environment.js.map +1 -0
- package/dist/process/launch.d.ts +31 -0
- package/dist/process/launch.js +281 -0
- package/dist/process/launch.js.map +1 -0
- package/dist/process/managed.d.ts +36 -0
- package/dist/process/managed.js +459 -0
- package/dist/process/managed.js.map +1 -0
- package/dist/process/output-log.d.ts +50 -0
- package/dist/process/output-log.js +552 -0
- package/dist/process/output-log.js.map +1 -0
- package/dist/process/pipes.d.ts +16 -0
- package/dist/process/pipes.js +588 -0
- package/dist/process/pipes.js.map +1 -0
- package/dist/process/pty.d.ts +22 -0
- package/dist/process/pty.js +512 -0
- package/dist/process/pty.js.map +1 -0
- package/dist/process/windows-conout-worker.d.ts +1 -0
- package/dist/process/windows-conout-worker.js +90 -0
- package/dist/process/windows-conout-worker.js.map +1 -0
- package/dist/process/windows-conout.d.ts +46 -0
- package/dist/process/windows-conout.js +140 -0
- package/dist/process/windows-conout.js.map +1 -0
- package/dist/process/windows-helper.d.ts +43 -0
- package/dist/process/windows-helper.js +255 -0
- package/dist/process/windows-helper.js.map +1 -0
- package/dist/process/windows-job.d.ts +39 -0
- package/dist/process/windows-job.js +224 -0
- package/dist/process/windows-job.js.map +1 -0
- package/dist/process/windows-pipes.d.ts +16 -0
- package/dist/process/windows-pipes.js +475 -0
- package/dist/process/windows-pipes.js.map +1 -0
- package/dist/results/artifacts.d.ts +118 -0
- package/dist/results/artifacts.js +873 -0
- package/dist/results/artifacts.js.map +1 -0
- package/dist/results/encoder.d.ts +57 -0
- package/dist/results/encoder.js +1179 -0
- package/dist/results/encoder.js.map +1 -0
- package/dist/results/mcp.d.ts +95 -0
- package/dist/results/mcp.js +656 -0
- package/dist/results/mcp.js.map +1 -0
- package/dist/results/media.d.ts +19 -0
- package/dist/results/media.js +301 -0
- package/dist/results/media.js.map +1 -0
- package/dist/results/normalize.d.ts +29 -0
- package/dist/results/normalize.js +464 -0
- package/dist/results/normalize.js.map +1 -0
- package/dist/runtime/control-scripts.d.ts +23 -0
- package/dist/runtime/control-scripts.js +242 -0
- package/dist/runtime/control-scripts.js.map +1 -0
- package/dist/runtime/engine.d.ts +177 -0
- package/dist/runtime/engine.js +1159 -0
- package/dist/runtime/engine.js.map +1 -0
- package/dist/runtime/globals.d.ts +1 -0
- package/dist/runtime/globals.js +31 -0
- package/dist/runtime/globals.js.map +1 -0
- package/dist/runtime/material-retention.d.ts +34 -0
- package/dist/runtime/material-retention.js +671 -0
- package/dist/runtime/material-retention.js.map +1 -0
- package/dist/runtime/modules.d.ts +50 -0
- package/dist/runtime/modules.js +320 -0
- package/dist/runtime/modules.js.map +1 -0
- package/dist/runtime/names.d.ts +2 -0
- package/dist/runtime/names.js +22 -0
- package/dist/runtime/names.js.map +1 -0
- package/dist/runtime/operations.d.ts +20 -0
- package/dist/runtime/operations.js +137 -0
- package/dist/runtime/operations.js.map +1 -0
- package/dist/runtime/paths.d.ts +3 -0
- package/dist/runtime/paths.js +38 -0
- package/dist/runtime/paths.js.map +1 -0
- package/dist/runtime/promises.d.ts +9 -0
- package/dist/runtime/promises.js +78 -0
- package/dist/runtime/promises.js.map +1 -0
- package/dist/runtime/retention.d.ts +88 -0
- package/dist/runtime/retention.js +735 -0
- package/dist/runtime/retention.js.map +1 -0
- package/dist/runtime/run-log.d.ts +30 -0
- package/dist/runtime/run-log.js +207 -0
- package/dist/runtime/run-log.js.map +1 -0
- package/dist/runtime/scripts.d.ts +84 -0
- package/dist/runtime/scripts.js +387 -0
- package/dist/runtime/scripts.js.map +1 -0
- package/dist/runtime/tasks.d.ts +54 -0
- package/dist/runtime/tasks.js +290 -0
- package/dist/runtime/tasks.js.map +1 -0
- package/dist/sdk/maintenance.d.ts +3 -0
- package/dist/sdk/maintenance.js +80 -0
- package/dist/sdk/maintenance.js.map +1 -0
- package/dist/sdk/output-extension.d.ts +3 -0
- package/dist/sdk/output-extension.js +44 -0
- package/dist/sdk/output-extension.js.map +1 -0
- package/dist/sdk/output.d.ts +52 -0
- package/dist/sdk/output.js +350 -0
- package/dist/sdk/output.js.map +1 -0
- package/dist/sdk/runtime.d.ts +3 -0
- package/dist/sdk/runtime.js +26 -0
- package/dist/sdk/runtime.js.map +1 -0
- package/dist/sdk/sh.d.ts +3 -0
- package/dist/sdk/sh.js +384 -0
- package/dist/sdk/sh.js.map +1 -0
- package/dist/sdk/state.d.ts +2 -0
- package/dist/sdk/state.js +69 -0
- package/dist/sdk/state.js.map +1 -0
- package/dist/sdk/transfer.d.ts +3 -0
- package/dist/sdk/transfer.js +141 -0
- package/dist/sdk/transfer.js.map +1 -0
- package/dist/services/extensions.d.ts +19 -0
- package/dist/services/extensions.js +183 -0
- package/dist/services/extensions.js.map +1 -0
- package/dist/services/state.d.ts +37 -0
- package/dist/services/state.js +125 -0
- package/dist/services/state.js.map +1 -0
- package/dist/services/transfer.d.ts +86 -0
- package/dist/services/transfer.js +948 -0
- package/dist/services/transfer.js.map +1 -0
- package/dist/storage/schema.d.ts +8 -0
- package/dist/storage/schema.js +241 -0
- package/dist/storage/schema.js.map +1 -0
- package/dist/storage/sqlite.d.ts +241 -0
- package/dist/storage/sqlite.js +1855 -0
- package/dist/storage/sqlite.js.map +1 -0
- package/dist/storage/transfers.d.ts +90 -0
- package/dist/storage/transfers.js +2 -0
- package/dist/storage/transfers.js.map +1 -0
- package/dist/transfer/io.d.ts +74 -0
- package/dist/transfer/io.js +425 -0
- package/dist/transfer/io.js.map +1 -0
- package/dist/transfer/offers.d.ts +72 -0
- package/dist/transfer/offers.js +380 -0
- package/dist/transfer/offers.js.map +1 -0
- package/dist/transfer/stream-slots.d.ts +12 -0
- package/dist/transfer/stream-slots.js +28 -0
- package/dist/transfer/stream-slots.js.map +1 -0
- package/dist/work/catalog.d.ts +43 -0
- package/dist/work/catalog.js +198 -0
- package/dist/work/catalog.js.map +1 -0
- package/dist/work/discovery.d.ts +70 -0
- package/dist/work/discovery.js +465 -0
- package/dist/work/discovery.js.map +1 -0
- package/dist/work/service.d.ts +83 -0
- package/dist/work/service.js +703 -0
- package/dist/work/service.js.map +1 -0
- package/package.json +66 -4
|
@@ -0,0 +1,1179 @@
|
|
|
1
|
+
import { open } from "node:fs/promises";
|
|
2
|
+
import { constants } from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { types, MIMEType } from "node:util";
|
|
5
|
+
import { fileTypeFromBuffer } from "file-type";
|
|
6
|
+
import { AgentError, requireCondition } from "../contracts/errors.js";
|
|
7
|
+
import { authorizeCall } from "../contracts/caller.js";
|
|
8
|
+
import { canonicalJson } from "../contracts/json.js";
|
|
9
|
+
import { createOutput, outputIntent, } from "../sdk/output.js";
|
|
10
|
+
import { contentValue, normalizeData } from "./normalize.js";
|
|
11
|
+
import { validateMedia } from "./media.js";
|
|
12
|
+
import { transferOffer, transferReference, issuedTransferSnapshot, } from "../transfer/offers.js";
|
|
13
|
+
import { parseArtifactUri } from "./artifacts.js";
|
|
14
|
+
import { mcpResult, mcpSource, copyMcpJSON, mcpMetaSize, } from "./mcp.js";
|
|
15
|
+
const KiB = 1024, MiB = KiB * KiB;
|
|
16
|
+
const textTypes = {
|
|
17
|
+
".txt": "text/plain",
|
|
18
|
+
".md": "text/markdown",
|
|
19
|
+
".json": "application/json",
|
|
20
|
+
".xml": "application/xml",
|
|
21
|
+
".html": "text/html",
|
|
22
|
+
".css": "text/css",
|
|
23
|
+
".js": "text/javascript",
|
|
24
|
+
".ts": "text/typescript",
|
|
25
|
+
".csv": "text/csv",
|
|
26
|
+
".yaml": "application/yaml",
|
|
27
|
+
".yml": "application/yaml",
|
|
28
|
+
};
|
|
29
|
+
const textMime = (value) => {
|
|
30
|
+
const type = new MIMEType(value).essence;
|
|
31
|
+
return (type.startsWith("text/") ||
|
|
32
|
+
[
|
|
33
|
+
"application/json",
|
|
34
|
+
"application/xml",
|
|
35
|
+
"application/javascript",
|
|
36
|
+
"application/yaml",
|
|
37
|
+
"application/x-yaml",
|
|
38
|
+
].includes(type) ||
|
|
39
|
+
/\+(?:json|xml)$/.test(type));
|
|
40
|
+
};
|
|
41
|
+
const asJson = (value) => JSON.parse(canonicalJson(value, 1024 * 1024));
|
|
42
|
+
function options(value) {
|
|
43
|
+
return asJson({
|
|
44
|
+
...(value.name === undefined ? {} : { name: value.name }),
|
|
45
|
+
...(value.description === undefined
|
|
46
|
+
? {}
|
|
47
|
+
: { description: value.description }),
|
|
48
|
+
...(value.annotations === undefined
|
|
49
|
+
? {}
|
|
50
|
+
: { annotations: value.annotations }),
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
async function snapshotBytes(filename, maxBytes, signal) {
|
|
54
|
+
signal?.throwIfAborted();
|
|
55
|
+
const file = await open(filename, constants.O_RDONLY |
|
|
56
|
+
(constants.O_NOFOLLOW ?? 0) |
|
|
57
|
+
(constants.O_NONBLOCK ?? 0));
|
|
58
|
+
try {
|
|
59
|
+
const stats = await file.stat();
|
|
60
|
+
requireCondition(stats.isFile() && stats.size <= maxBytes, "inline_media_too_large", "The fixed resource exceeds this inline content budget.");
|
|
61
|
+
const chunks = [];
|
|
62
|
+
let size = 0;
|
|
63
|
+
while (true) {
|
|
64
|
+
signal?.throwIfAborted();
|
|
65
|
+
const buffer = Buffer.allocUnsafe(Math.min(65536, maxBytes - size + 1));
|
|
66
|
+
const { bytesRead } = await file.read(buffer, 0, buffer.length, null);
|
|
67
|
+
if (!bytesRead)
|
|
68
|
+
break;
|
|
69
|
+
size += bytesRead;
|
|
70
|
+
requireCondition(size <= maxBytes, "inline_media_too_large", "The fixed resource exceeds this inline content budget.");
|
|
71
|
+
chunks.push(buffer.subarray(0, bytesRead));
|
|
72
|
+
}
|
|
73
|
+
return Buffer.concat(chunks, size);
|
|
74
|
+
}
|
|
75
|
+
finally {
|
|
76
|
+
await file.close();
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
function encodedBytes(value, maximum) {
|
|
80
|
+
requireCondition(value.length <= Math.ceil(maximum / 3) * 4 && value.length % 4 === 0, "invalid_media_encoding", "Encoded media must use bounded canonical base64.");
|
|
81
|
+
const padding = value.endsWith("==") ? 2 : value.endsWith("=") ? 1 : 0;
|
|
82
|
+
const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
83
|
+
for (let i = 0; i < value.length - padding; i++)
|
|
84
|
+
requireCondition(alphabet.includes(value[i]), "invalid_media_encoding", "Encoded media contains invalid base64 characters.");
|
|
85
|
+
const last = padding
|
|
86
|
+
? alphabet.indexOf(value[value.length - padding - 1] ?? "")
|
|
87
|
+
: 0;
|
|
88
|
+
requireCondition((value.length / 4) * 3 - padding <= maximum &&
|
|
89
|
+
(!padding || (last >= 0 && last % (padding === 2 ? 16 : 4) === 0)), "invalid_media_encoding", "Encoded media is invalid or exceeds its content budget.");
|
|
90
|
+
return Buffer.from(value, "base64");
|
|
91
|
+
}
|
|
92
|
+
const recordJson = (value) => asJson(value);
|
|
93
|
+
function record(value) {
|
|
94
|
+
requireCondition(value && !Array.isArray(value) && typeof value === "object", "invalid_saved_result", "Saved content must identify its fixed resource.");
|
|
95
|
+
return value;
|
|
96
|
+
}
|
|
97
|
+
/** Stores identities and JSON only. MCP bytes are materialized on the later authorized delivery path. */
|
|
98
|
+
export class ResultEncoder {
|
|
99
|
+
artifacts;
|
|
100
|
+
offers;
|
|
101
|
+
mcp;
|
|
102
|
+
limits;
|
|
103
|
+
constructor(artifacts, limits = {}, offers, mcp) {
|
|
104
|
+
this.artifacts = artifacts;
|
|
105
|
+
this.offers = offers;
|
|
106
|
+
this.mcp = mcp;
|
|
107
|
+
requireCondition(!offers ||
|
|
108
|
+
(offers.agentId === artifacts.agentId &&
|
|
109
|
+
offers.profileRoot === artifacts.root), "result_profile_mismatch", "Transfer delivery must belong to this actual Agent/profile artifact store.");
|
|
110
|
+
requireCondition(!mcp ||
|
|
111
|
+
(mcp.agentId === artifacts.agentId &&
|
|
112
|
+
mcp.profileRoot === artifacts.root), "result_profile_mismatch", "Remote result routing must belong to this actual Agent/profile.");
|
|
113
|
+
this.limits = Object.freeze({
|
|
114
|
+
textBytes: limits.textBytes ?? 64 * KiB,
|
|
115
|
+
imageBytes: limits.imageBytes ?? 10 * MiB,
|
|
116
|
+
audioBytes: limits.audioBytes ?? 32 * MiB,
|
|
117
|
+
inlineBytes: limits.inlineBytes ?? 64 * MiB,
|
|
118
|
+
responseBytes: limits.responseBytes ?? 128 * MiB,
|
|
119
|
+
maxDataBytes: limits.maxDataBytes ?? Math.min(artifacts.maxFileBytes, 256 * MiB),
|
|
120
|
+
metaBytes: limits.metaBytes ?? 16 * MiB,
|
|
121
|
+
});
|
|
122
|
+
requireCondition(Object.values(this.limits).every((value) => Number.isSafeInteger(value) && value > 0) &&
|
|
123
|
+
this.limits.textBytes <= 16 * MiB &&
|
|
124
|
+
this.limits.imageBytes <= artifacts.maxReadBytes &&
|
|
125
|
+
this.limits.audioBytes <= artifacts.maxReadBytes &&
|
|
126
|
+
this.limits.inlineBytes <= 128 * MiB &&
|
|
127
|
+
this.limits.responseBytes <= 512 * MiB &&
|
|
128
|
+
this.limits.maxDataBytes <= artifacts.maxFileBytes &&
|
|
129
|
+
this.limits.maxDataBytes <= 256 * MiB, "invalid_result_options", "Result budgets must fit the actual Agent resource and response policy.");
|
|
130
|
+
requireCondition(this.limits.metaBytes <= 128 * MiB, "invalid_result_options", "Host-only metadata requires a bounded encoded budget.");
|
|
131
|
+
}
|
|
132
|
+
async encode(value, scope) {
|
|
133
|
+
scope.assertCurrent();
|
|
134
|
+
scope.signal?.throwIfAborted();
|
|
135
|
+
const result = { content: [] };
|
|
136
|
+
const remoteResults = [], remoteSeen = new WeakMap();
|
|
137
|
+
let remoteMetaBytes = 2;
|
|
138
|
+
const transfers = new Map(), transferLinks = new Set();
|
|
139
|
+
let transferBytes = 2;
|
|
140
|
+
let inlineBytes = 0, textBytes = 0;
|
|
141
|
+
const paths = new Map(), identities = new WeakMap();
|
|
142
|
+
const reserve = (size) => {
|
|
143
|
+
inlineBytes += size;
|
|
144
|
+
requireCondition(inlineBytes <= this.limits.inlineBytes, "inline_content_too_large", "The result exceeds its aggregate inline byte budget.");
|
|
145
|
+
};
|
|
146
|
+
const fixed = async (source, kind) => {
|
|
147
|
+
const textual = kind === "resource" &&
|
|
148
|
+
((typeof source.mimeType === "string" && textMime(source.mimeType)) ||
|
|
149
|
+
(typeof source.path === "string" &&
|
|
150
|
+
!!textTypes[path.extname(source.path).toLowerCase()]));
|
|
151
|
+
const individual = kind === "image"
|
|
152
|
+
? this.limits.imageBytes
|
|
153
|
+
: kind === "audio"
|
|
154
|
+
? this.limits.audioBytes
|
|
155
|
+
: kind === "resource"
|
|
156
|
+
? textual
|
|
157
|
+
? this.limits.textBytes
|
|
158
|
+
: this.limits.inlineBytes
|
|
159
|
+
: this.artifacts.maxFileBytes;
|
|
160
|
+
const aggregate = kind === "image" ||
|
|
161
|
+
kind === "audio" ||
|
|
162
|
+
(kind === "resource" && !textual);
|
|
163
|
+
const cap = Math.min(individual, aggregate
|
|
164
|
+
? Math.max(1, this.limits.inlineBytes - inlineBytes)
|
|
165
|
+
: individual, this.artifacts.maxFileBytes);
|
|
166
|
+
if (typeof source.uri === "string") {
|
|
167
|
+
const resource = await this.artifacts.metadata(source.uri, scope);
|
|
168
|
+
if (kind === "image" || kind === "audio") {
|
|
169
|
+
const data = await this.artifacts.read(resource.uri, scope, {
|
|
170
|
+
maxBytes: cap,
|
|
171
|
+
});
|
|
172
|
+
await validateMedia(data.data, kind, typeof source.mimeType === "string"
|
|
173
|
+
? source.mimeType
|
|
174
|
+
: resource.mimeType === "application/octet-stream"
|
|
175
|
+
? undefined
|
|
176
|
+
: resource.mimeType, { signal: scope.signal, maxBytes: cap });
|
|
177
|
+
}
|
|
178
|
+
return resource;
|
|
179
|
+
}
|
|
180
|
+
const proposed = {
|
|
181
|
+
...(typeof source.path === "string"
|
|
182
|
+
? { path: source.path }
|
|
183
|
+
: {
|
|
184
|
+
data: typeof source.data === "string"
|
|
185
|
+
? encodedBytes(source.data, cap)
|
|
186
|
+
: source.data,
|
|
187
|
+
}),
|
|
188
|
+
...(typeof source.name === "string" ? { name: source.name } : {}),
|
|
189
|
+
...(typeof source.mimeType === "string"
|
|
190
|
+
? { mimeType: source.mimeType }
|
|
191
|
+
: {}),
|
|
192
|
+
};
|
|
193
|
+
const cacheKey = proposed.path;
|
|
194
|
+
const objectKey = proposed.data && typeof proposed.data === "object"
|
|
195
|
+
? proposed.data
|
|
196
|
+
: undefined;
|
|
197
|
+
let pending = cacheKey
|
|
198
|
+
? paths.get(cacheKey)
|
|
199
|
+
: objectKey
|
|
200
|
+
? identities.get(objectKey)
|
|
201
|
+
: undefined;
|
|
202
|
+
if (!pending) {
|
|
203
|
+
pending = this.artifacts
|
|
204
|
+
.register(proposed, scope, async (snapshot) => {
|
|
205
|
+
scope.assertCurrent();
|
|
206
|
+
if (kind === "image" || kind === "audio") {
|
|
207
|
+
const bytes = await snapshotBytes(snapshot.path, cap, scope.signal);
|
|
208
|
+
const metadata = await validateMedia(bytes, kind, proposed.mimeType, { signal: scope.signal, maxBytes: cap });
|
|
209
|
+
return { mimeType: metadata.mimeType };
|
|
210
|
+
}
|
|
211
|
+
if (!proposed.mimeType) {
|
|
212
|
+
const file = await open(snapshot.path, constants.O_RDONLY |
|
|
213
|
+
(constants.O_NOFOLLOW ?? 0) |
|
|
214
|
+
(constants.O_NONBLOCK ?? 0));
|
|
215
|
+
try {
|
|
216
|
+
const stats = await file.stat();
|
|
217
|
+
requireCondition(stats.isFile() && stats.size === snapshot.size, "resource_source_changed", "The fixed resource changed before format inspection.");
|
|
218
|
+
const head = Buffer.alloc(Math.min(snapshot.size, 65536));
|
|
219
|
+
const read = await file.read(head, 0, head.length, 0);
|
|
220
|
+
let detected;
|
|
221
|
+
try {
|
|
222
|
+
detected = await fileTypeFromBuffer(head.subarray(0, read.bytesRead), { signal: scope.signal });
|
|
223
|
+
}
|
|
224
|
+
catch (cause) {
|
|
225
|
+
scope.signal?.throwIfAborted();
|
|
226
|
+
}
|
|
227
|
+
if (detected)
|
|
228
|
+
return { mimeType: detected.mime };
|
|
229
|
+
const textType = textTypes[path.extname(snapshot.name).toLowerCase()];
|
|
230
|
+
if (textType)
|
|
231
|
+
return { mimeType: textType };
|
|
232
|
+
}
|
|
233
|
+
finally {
|
|
234
|
+
await file.close();
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
return {};
|
|
238
|
+
}, { maxBytes: cap })
|
|
239
|
+
.catch((cause) => {
|
|
240
|
+
if (cause instanceof AgentError &&
|
|
241
|
+
cause.code === "resource_too_large" &&
|
|
242
|
+
kind !== "resource_link")
|
|
243
|
+
throw new AgentError(aggregate && cap < individual
|
|
244
|
+
? "inline_content_too_large"
|
|
245
|
+
: kind === "image" || kind === "audio"
|
|
246
|
+
? "inline_media_too_large"
|
|
247
|
+
: "resource_read_too_large", "The requested inline content exceeds its configured budget; choose a resource link.");
|
|
248
|
+
throw cause;
|
|
249
|
+
});
|
|
250
|
+
if (cacheKey)
|
|
251
|
+
paths.set(cacheKey, pending);
|
|
252
|
+
else if (objectKey)
|
|
253
|
+
identities.set(objectKey, pending);
|
|
254
|
+
}
|
|
255
|
+
return await pending;
|
|
256
|
+
};
|
|
257
|
+
const resolveOffer = async (value) => {
|
|
258
|
+
const known = transferOffer(value);
|
|
259
|
+
requireCondition(known &&
|
|
260
|
+
known.binding.ownerKey === scope.ownerKey &&
|
|
261
|
+
known.binding.grantId === scope.grantId &&
|
|
262
|
+
known.binding.agentId === this.artifacts.agentId &&
|
|
263
|
+
known.binding.profileRoot === this.artifacts.root, "transfer_offer_binding_mismatch", "The issued Offer does not belong to this current result binding.");
|
|
264
|
+
if (!transfers.has(known.reference.transferId)) {
|
|
265
|
+
const saved = { reference: known.reference, snapshot: known.snapshot };
|
|
266
|
+
transferBytes += Buffer.byteLength(canonicalJson(saved, 32768)) + 1;
|
|
267
|
+
requireCondition(transfers.size < 1024 &&
|
|
268
|
+
transferBytes <= Math.min(this.limits.textBytes, 65536), "result_transfer_too_large", "The result exceeds its safe transfer-reference budget.");
|
|
269
|
+
transfers.set(known.reference.transferId, saved);
|
|
270
|
+
const resource = known.snapshot.resource;
|
|
271
|
+
if (known.snapshot.direction === "download" &&
|
|
272
|
+
resource &&
|
|
273
|
+
!Array.isArray(resource) &&
|
|
274
|
+
typeof resource === "object") {
|
|
275
|
+
const uri = resource.uri;
|
|
276
|
+
requireCondition(typeof uri === "string" &&
|
|
277
|
+
parseArtifactUri(uri).agentId === this.artifacts.agentId, "invalid_transfer_resource", "A download Offer must reference this Agent's registered resource.");
|
|
278
|
+
if (!transferLinks.has(uri)) {
|
|
279
|
+
await append(createOutput(scope.pwd, () => scope.assertCurrent()).file({
|
|
280
|
+
uri,
|
|
281
|
+
}));
|
|
282
|
+
transferLinks.add(uri);
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
return known.snapshot;
|
|
287
|
+
};
|
|
288
|
+
const append = async (input) => {
|
|
289
|
+
scope.assertCurrent();
|
|
290
|
+
scope.signal?.throwIfAborted();
|
|
291
|
+
if (mcpResult(input))
|
|
292
|
+
return await resolveMcp(input, true);
|
|
293
|
+
if (transferOffer(input))
|
|
294
|
+
return await resolveOffer(input);
|
|
295
|
+
const intent = outputIntent(input);
|
|
296
|
+
if (intent?.kind === "collection") {
|
|
297
|
+
const refs = [];
|
|
298
|
+
for (const item of intent.value)
|
|
299
|
+
refs.push(await append(item));
|
|
300
|
+
return { content: refs };
|
|
301
|
+
}
|
|
302
|
+
requireCondition(!intent || !["result", "json"].includes(intent.kind), "invalid_result_content", "Nested full results and JSON wrappers belong in structured data.");
|
|
303
|
+
let kind, source, meta;
|
|
304
|
+
if (intent) {
|
|
305
|
+
kind = intent.kind;
|
|
306
|
+
meta = options(intent.options);
|
|
307
|
+
source =
|
|
308
|
+
kind === "text"
|
|
309
|
+
? { text: intent.value }
|
|
310
|
+
: {
|
|
311
|
+
...intent.value,
|
|
312
|
+
...(intent.options.name ? { name: intent.options.name } : {}),
|
|
313
|
+
...(intent.options.mimeType
|
|
314
|
+
? { mimeType: intent.options.mimeType }
|
|
315
|
+
: {}),
|
|
316
|
+
};
|
|
317
|
+
}
|
|
318
|
+
else {
|
|
319
|
+
const content = contentValue(input, scope.pwd);
|
|
320
|
+
if (content && !outputIntent(content)) {
|
|
321
|
+
source = content;
|
|
322
|
+
kind = source.type;
|
|
323
|
+
meta = options(source);
|
|
324
|
+
}
|
|
325
|
+
else if (types.isArrayBufferView(input) ||
|
|
326
|
+
types.isAnyArrayBuffer(input) ||
|
|
327
|
+
(input && typeof input === "object")) {
|
|
328
|
+
kind = "resource_link";
|
|
329
|
+
source = { data: input };
|
|
330
|
+
meta = {};
|
|
331
|
+
}
|
|
332
|
+
else
|
|
333
|
+
throw new AgentError("invalid_result_content", "A result content item is not a valid content or binary source.");
|
|
334
|
+
}
|
|
335
|
+
const index = result.content.length;
|
|
336
|
+
requireCondition(index < 10000, "result_content_too_large", "The result exceeds its content-item budget.");
|
|
337
|
+
if (kind === "text") {
|
|
338
|
+
requireCondition(typeof source.text === "string", "invalid_result_content", "Text content must have a string body.");
|
|
339
|
+
textBytes += Buffer.byteLength(source.text);
|
|
340
|
+
requireCondition(textBytes <= this.limits.maxDataBytes, "result_data_too_large", "Result text exceeds the bounded full-result storage budget.");
|
|
341
|
+
result.content.push({
|
|
342
|
+
type: "text",
|
|
343
|
+
text: source.text,
|
|
344
|
+
...(meta.annotations ? { annotations: meta.annotations } : {}),
|
|
345
|
+
});
|
|
346
|
+
return { contentIndex: index };
|
|
347
|
+
}
|
|
348
|
+
let resource, encoding = "blob", inlineTextBytes = 0;
|
|
349
|
+
if (kind === "resource" && source.resource) {
|
|
350
|
+
const embedded = source.resource;
|
|
351
|
+
encoding = typeof embedded.text === "string" ? "text" : "blob";
|
|
352
|
+
if (encoding === "text")
|
|
353
|
+
requireCondition(Buffer.byteLength(embedded.text) <= this.limits.textBytes, "resource_read_too_large", "Embedded text exceeds its inline context budget; choose a resource link.");
|
|
354
|
+
const bytes = encoding === "text"
|
|
355
|
+
? Buffer.from(embedded.text)
|
|
356
|
+
: typeof embedded.blob === "string"
|
|
357
|
+
? encodedBytes(embedded.blob, this.limits.inlineBytes)
|
|
358
|
+
: embedded.blob;
|
|
359
|
+
resource = await fixed({
|
|
360
|
+
data: bytes,
|
|
361
|
+
...(embedded.mimeType
|
|
362
|
+
? { mimeType: embedded.mimeType }
|
|
363
|
+
: encoding === "text"
|
|
364
|
+
? { mimeType: "text/plain; charset=utf-8" }
|
|
365
|
+
: {}),
|
|
366
|
+
}, kind);
|
|
367
|
+
}
|
|
368
|
+
else
|
|
369
|
+
resource = await fixed(source, kind);
|
|
370
|
+
let mimeType = resource.mimeType;
|
|
371
|
+
if (kind === "image" || kind === "audio") {
|
|
372
|
+
const cap = kind === "image" ? this.limits.imageBytes : this.limits.audioBytes;
|
|
373
|
+
requireCondition(resource.size <= cap, "inline_media_too_large", "The media exceeds its individual inline byte budget.", { uri: resource.uri });
|
|
374
|
+
const bytes = await this.artifacts.read(resource.uri, scope, {
|
|
375
|
+
maxBytes: cap,
|
|
376
|
+
});
|
|
377
|
+
const hint = typeof source.mimeType === "string"
|
|
378
|
+
? source.mimeType
|
|
379
|
+
: resource.mimeType === "application/octet-stream"
|
|
380
|
+
? undefined
|
|
381
|
+
: resource.mimeType;
|
|
382
|
+
mimeType = (await validateMedia(bytes.data, kind, hint, {
|
|
383
|
+
signal: scope.signal,
|
|
384
|
+
maxBytes: cap,
|
|
385
|
+
})).mimeType;
|
|
386
|
+
// A generic-file cache entry is never evidence that its declared media
|
|
387
|
+
// type is true. Validate both the current request and retained metadata.
|
|
388
|
+
if (resource.mimeType !== "application/octet-stream" &&
|
|
389
|
+
resource.mimeType !== hint)
|
|
390
|
+
await validateMedia(bytes.data, kind, resource.mimeType, {
|
|
391
|
+
signal: scope.signal,
|
|
392
|
+
maxBytes: cap,
|
|
393
|
+
});
|
|
394
|
+
reserve(resource.size);
|
|
395
|
+
}
|
|
396
|
+
else if (kind === "resource") {
|
|
397
|
+
if (!source.resource)
|
|
398
|
+
encoding = textMime(mimeType) ? "text" : "blob";
|
|
399
|
+
if (encoding === "blob")
|
|
400
|
+
reserve(resource.size);
|
|
401
|
+
else {
|
|
402
|
+
const data = await this.artifacts.read(resource.uri, scope, {
|
|
403
|
+
maxBytes: Math.min(this.limits.textBytes, this.artifacts.maxReadBytes),
|
|
404
|
+
});
|
|
405
|
+
let text;
|
|
406
|
+
try {
|
|
407
|
+
text = new TextDecoder("utf-8", { fatal: true }).decode(data.data);
|
|
408
|
+
}
|
|
409
|
+
catch {
|
|
410
|
+
throw new AgentError("invalid_resource_text", "The resource is not valid UTF-8 text; choose a binary resource.");
|
|
411
|
+
}
|
|
412
|
+
inlineTextBytes = Buffer.byteLength(JSON.stringify(text)) - 2;
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
result.content.push({
|
|
416
|
+
type: kind,
|
|
417
|
+
resource: recordJson(resource),
|
|
418
|
+
mimeType,
|
|
419
|
+
...meta,
|
|
420
|
+
...(kind === "resource"
|
|
421
|
+
? { encoding, ...(encoding === "text" ? { inlineTextBytes } : {}) }
|
|
422
|
+
: {}),
|
|
423
|
+
});
|
|
424
|
+
return {
|
|
425
|
+
contentIndex: index,
|
|
426
|
+
resourceId: resource.resourceId,
|
|
427
|
+
uri: resource.uri,
|
|
428
|
+
name: resource.name,
|
|
429
|
+
mimeType,
|
|
430
|
+
size: resource.size,
|
|
431
|
+
};
|
|
432
|
+
};
|
|
433
|
+
const resolveMcp = async (input, explicit = false) => {
|
|
434
|
+
const known = mcpResult(input);
|
|
435
|
+
requireCondition(known && this.mcp, "mcp_source_unavailable", "Source-aware remote result routing is not configured.");
|
|
436
|
+
await this.mcp.resolve(known.source, scope);
|
|
437
|
+
const previous = remoteSeen.get(input);
|
|
438
|
+
if (previous !== undefined)
|
|
439
|
+
return { mcpResult: previous };
|
|
440
|
+
const slot = remoteResults.length;
|
|
441
|
+
requireCondition(slot < 1000, "mcp_result_too_large", "The result contains too many remote result components.");
|
|
442
|
+
remoteMetaBytes +=
|
|
443
|
+
mcpMetaSize({ source: known.source, meta: known.meta }, this.limits.metaBytes) + 1;
|
|
444
|
+
requireCondition(remoteMetaBytes <= this.limits.metaBytes, "mcp_meta_too_large", "Remote Host-only metadata exceeds its separate budget.");
|
|
445
|
+
remoteSeen.set(input, slot);
|
|
446
|
+
remoteResults.push({
|
|
447
|
+
source: known.source,
|
|
448
|
+
meta: known.meta,
|
|
449
|
+
method: known.method,
|
|
450
|
+
});
|
|
451
|
+
const blocks = known.kind === "resources"
|
|
452
|
+
? known.model.contents.map((resource) => ({
|
|
453
|
+
type: "resource",
|
|
454
|
+
resource,
|
|
455
|
+
}))
|
|
456
|
+
: known.model.content;
|
|
457
|
+
for (let sourceIndex = 0; sourceIndex < blocks.length; sourceIndex++) {
|
|
458
|
+
const block = blocks[sourceIndex], start = result.content.length;
|
|
459
|
+
if (block.type === "resource_link") {
|
|
460
|
+
// A remote coordinate is not evidence of a downloaded local artifact.
|
|
461
|
+
requireCondition(start < 10000, "result_content_too_large", "The result exceeds its content-item budget.");
|
|
462
|
+
result.content.push({
|
|
463
|
+
...copyMcpJSON(block),
|
|
464
|
+
remote: {
|
|
465
|
+
source: known.source,
|
|
466
|
+
uri: block.uri,
|
|
467
|
+
},
|
|
468
|
+
});
|
|
469
|
+
}
|
|
470
|
+
else
|
|
471
|
+
await append(block);
|
|
472
|
+
for (let index = start; index < result.content.length; index++) {
|
|
473
|
+
const stored = result.content[index];
|
|
474
|
+
stored.mcp = { slot, index: sourceIndex };
|
|
475
|
+
if (block.type === "resource")
|
|
476
|
+
stored.remote = {
|
|
477
|
+
source: known.source,
|
|
478
|
+
uri: block.resource.uri,
|
|
479
|
+
};
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
const association = {
|
|
483
|
+
mcpResult: slot,
|
|
484
|
+
contentIndices: result.content.flatMap((item, index) => item.mcp?.slot === slot ? [index] : []),
|
|
485
|
+
...(Object.hasOwn(known.model, "structuredContent")
|
|
486
|
+
? { structuredContent: known.model.structuredContent }
|
|
487
|
+
: {}),
|
|
488
|
+
...(known.model.isError === undefined
|
|
489
|
+
? {}
|
|
490
|
+
: { isError: known.model.isError }),
|
|
491
|
+
...(known.model.resultType === undefined
|
|
492
|
+
? {}
|
|
493
|
+
: { resultType: known.model.resultType }),
|
|
494
|
+
};
|
|
495
|
+
if (known.model.isError === true)
|
|
496
|
+
result.isError = true;
|
|
497
|
+
result.mcpResults ??= [];
|
|
498
|
+
if (explicit) {
|
|
499
|
+
const normalized = await normalizeData(association, {
|
|
500
|
+
mode: "data",
|
|
501
|
+
maxBytes: this.limits.maxDataBytes,
|
|
502
|
+
assertCurrent: () => scope.assertCurrent(),
|
|
503
|
+
});
|
|
504
|
+
result.mcpResults.push(normalized.data);
|
|
505
|
+
}
|
|
506
|
+
else
|
|
507
|
+
result.mcpResults.push({
|
|
508
|
+
mcpResult: slot,
|
|
509
|
+
contentIndices: association.contentIndices,
|
|
510
|
+
});
|
|
511
|
+
return association;
|
|
512
|
+
};
|
|
513
|
+
const data = async (input, pure = false) => {
|
|
514
|
+
const normalized = await normalizeData(input, {
|
|
515
|
+
mode: pure ? "data" : "auto",
|
|
516
|
+
pwd: scope.pwd,
|
|
517
|
+
maxBytes: this.limits.maxDataBytes,
|
|
518
|
+
assertCurrent: () => scope.assertCurrent(),
|
|
519
|
+
resolveContent: (value) => append(value),
|
|
520
|
+
resolveTransferOffer: resolveOffer,
|
|
521
|
+
resolveMcpResult: (value) => resolveMcp(value),
|
|
522
|
+
});
|
|
523
|
+
result.data = normalized.data;
|
|
524
|
+
if (normalized.conversions.length)
|
|
525
|
+
result.conversions = normalized.conversions;
|
|
526
|
+
};
|
|
527
|
+
const intent = outputIntent(value), remote = mcpResult(value);
|
|
528
|
+
if (remote) {
|
|
529
|
+
await resolveMcp(value);
|
|
530
|
+
if (Object.hasOwn(remote.model, "structuredContent"))
|
|
531
|
+
await data(remote.model.structuredContent, true);
|
|
532
|
+
if (remote.model.isError !== undefined)
|
|
533
|
+
result.isError = remote.model.isError;
|
|
534
|
+
if (remote.model.resultType !== undefined)
|
|
535
|
+
result.resultType = remote.model.resultType;
|
|
536
|
+
}
|
|
537
|
+
else if (intent?.kind === "result") {
|
|
538
|
+
const body = intent.value;
|
|
539
|
+
for (const item of body.content)
|
|
540
|
+
await append(item);
|
|
541
|
+
if (Object.hasOwn(body, "structuredContent"))
|
|
542
|
+
await data(body.structuredContent, true);
|
|
543
|
+
if (body.isError !== undefined)
|
|
544
|
+
result.isError = body.isError;
|
|
545
|
+
}
|
|
546
|
+
else if (intent?.kind === "json")
|
|
547
|
+
await data(intent.value, true);
|
|
548
|
+
else if (value === undefined) {
|
|
549
|
+
}
|
|
550
|
+
else if (typeof value === "string")
|
|
551
|
+
await append(createOutput(scope.pwd, () => scope.assertCurrent()).text(value));
|
|
552
|
+
else if (intent || contentValue(value, scope.pwd))
|
|
553
|
+
await append(value);
|
|
554
|
+
else if (!types.isProxy(value) && Array.isArray(value) && value.length) {
|
|
555
|
+
// Descriptor-based normalization below rejects holes/accessors without executing them.
|
|
556
|
+
requireCondition(value.length <= 100000, "result_content_too_large", "The result array exceeds its item budget.");
|
|
557
|
+
const items = [];
|
|
558
|
+
let all = true;
|
|
559
|
+
for (let i = 0; i < value.length; i++) {
|
|
560
|
+
const item = Object.getOwnPropertyDescriptor(value, String(i));
|
|
561
|
+
if (!item ||
|
|
562
|
+
!("value" in item) ||
|
|
563
|
+
!(mcpResult(item.value) || contentValue(item.value, scope.pwd))) {
|
|
564
|
+
all = false;
|
|
565
|
+
break;
|
|
566
|
+
}
|
|
567
|
+
items.push(item.value);
|
|
568
|
+
}
|
|
569
|
+
if (all)
|
|
570
|
+
for (const item of items)
|
|
571
|
+
await append(item);
|
|
572
|
+
else
|
|
573
|
+
await data(value);
|
|
574
|
+
}
|
|
575
|
+
else
|
|
576
|
+
await data(value);
|
|
577
|
+
if (transfers.size)
|
|
578
|
+
result.transferOffers = [...transfers.values()];
|
|
579
|
+
if (remoteResults.length)
|
|
580
|
+
result.mcpSources = remoteResults;
|
|
581
|
+
await this.#fit(result, scope);
|
|
582
|
+
await this.#authorizeMcp(result, scope);
|
|
583
|
+
scope.assertCurrent();
|
|
584
|
+
scope.signal?.throwIfAborted();
|
|
585
|
+
return result;
|
|
586
|
+
}
|
|
587
|
+
#projection(result, run, fallback) {
|
|
588
|
+
const content = result.content.map((item) => {
|
|
589
|
+
if (item.type === "text")
|
|
590
|
+
return {
|
|
591
|
+
type: "text",
|
|
592
|
+
text: item.text,
|
|
593
|
+
...(item.annotations ? { annotations: item.annotations } : {}),
|
|
594
|
+
};
|
|
595
|
+
const remote = item.remote;
|
|
596
|
+
if (item.type === "resource_link" && remote) {
|
|
597
|
+
requireCondition(this.mcp, "mcp_source_unavailable", "Remote resource routing is unavailable.");
|
|
598
|
+
const { remote: _remote, mcp: _mcp, ...link } = item;
|
|
599
|
+
return {
|
|
600
|
+
...link,
|
|
601
|
+
uri: this.mcp.uri(mcpSource(remote.source), remote.uri),
|
|
602
|
+
};
|
|
603
|
+
}
|
|
604
|
+
const resource = record(item.resource);
|
|
605
|
+
const meta = {
|
|
606
|
+
...(item.annotations ? { annotations: item.annotations } : {}),
|
|
607
|
+
...(item.description ? { description: item.description } : {}),
|
|
608
|
+
};
|
|
609
|
+
if (item.type === "resource_link")
|
|
610
|
+
return {
|
|
611
|
+
type: "resource_link",
|
|
612
|
+
uri: resource.uri,
|
|
613
|
+
name: item.name ?? resource.name,
|
|
614
|
+
mimeType: item.mimeType ?? resource.mimeType,
|
|
615
|
+
...meta,
|
|
616
|
+
};
|
|
617
|
+
if (item.type === "resource")
|
|
618
|
+
return {
|
|
619
|
+
type: "resource",
|
|
620
|
+
resource: {
|
|
621
|
+
uri: remote ? this.mcpUri(remote) : resource.uri,
|
|
622
|
+
mimeType: item.mimeType ?? resource.mimeType,
|
|
623
|
+
...(item.encoding === "text" ? { text: "" } : { blob: "" }),
|
|
624
|
+
},
|
|
625
|
+
...meta,
|
|
626
|
+
};
|
|
627
|
+
return {
|
|
628
|
+
type: item.type,
|
|
629
|
+
data: "",
|
|
630
|
+
mimeType: item.mimeType ?? resource.mimeType,
|
|
631
|
+
...(item.annotations ? { annotations: item.annotations } : {}),
|
|
632
|
+
};
|
|
633
|
+
});
|
|
634
|
+
const transfers = this.#transfers(result);
|
|
635
|
+
const delivery = {
|
|
636
|
+
...(result.delivery ?? {}),
|
|
637
|
+
...(transfers.length
|
|
638
|
+
? {
|
|
639
|
+
transfers: transfers.map((item) => ({
|
|
640
|
+
transferId: item.reference.transferId,
|
|
641
|
+
available: false,
|
|
642
|
+
reason: "delivery_unavailable",
|
|
643
|
+
snapshot: item.snapshot,
|
|
644
|
+
})),
|
|
645
|
+
}
|
|
646
|
+
: {}),
|
|
647
|
+
};
|
|
648
|
+
const structuredContent = {
|
|
649
|
+
run,
|
|
650
|
+
...(Object.hasOwn(result, "data") ? { data: result.data } : {}),
|
|
651
|
+
...(result.conversions ? { conversions: result.conversions } : {}),
|
|
652
|
+
...(result.mcpResults
|
|
653
|
+
? {
|
|
654
|
+
mcpResults: result.mcpResults.map((entry) => ({
|
|
655
|
+
...entry,
|
|
656
|
+
contentIndices: result.content.flatMap((item, index) => item.mcp?.slot === entry.mcpResult
|
|
657
|
+
? [index]
|
|
658
|
+
: []),
|
|
659
|
+
})),
|
|
660
|
+
}
|
|
661
|
+
: {}),
|
|
662
|
+
...(Object.keys(delivery).length ? { delivery } : {}),
|
|
663
|
+
};
|
|
664
|
+
if (fallback) {
|
|
665
|
+
const text = Object.hasOwn(result, "data")
|
|
666
|
+
? JSON.stringify(result.data)
|
|
667
|
+
: "";
|
|
668
|
+
content.push({
|
|
669
|
+
type: "text",
|
|
670
|
+
text: `runId: ${String(run.runId ?? "")}\nstatus: ${String(run.status ?? "")}${text ? "\n" + text : ""}`,
|
|
671
|
+
});
|
|
672
|
+
}
|
|
673
|
+
return {
|
|
674
|
+
content: content,
|
|
675
|
+
structuredContent,
|
|
676
|
+
...(result.isError === undefined ? {} : { isError: result.isError }),
|
|
677
|
+
...(result.resultType === undefined
|
|
678
|
+
? {}
|
|
679
|
+
: { resultType: result.resultType }),
|
|
680
|
+
};
|
|
681
|
+
}
|
|
682
|
+
mcpUri(remote) {
|
|
683
|
+
requireCondition(this.mcp, "mcp_source_unavailable", "Remote resource routing is unavailable.");
|
|
684
|
+
return this.mcp.uri(mcpSource(remote.source), remote.uri);
|
|
685
|
+
}
|
|
686
|
+
#mcpSources(result) {
|
|
687
|
+
if (result.mcpSources === undefined)
|
|
688
|
+
return [];
|
|
689
|
+
requireCondition(Array.isArray(result.mcpSources) && result.mcpSources.length <= 1000, "invalid_saved_result", "Saved remote results require bounded provenance.");
|
|
690
|
+
let bytes = 2;
|
|
691
|
+
return result.mcpSources.map((value) => {
|
|
692
|
+
requireCondition(value &&
|
|
693
|
+
!Array.isArray(value) &&
|
|
694
|
+
typeof value === "object" &&
|
|
695
|
+
Array.isArray(value.meta) &&
|
|
696
|
+
typeof value.method === "string", "invalid_saved_result", "Saved remote result provenance is invalid.");
|
|
697
|
+
const source = mcpSource(value.source), meta = copyMcpJSON(value.meta, this.limits.metaBytes);
|
|
698
|
+
bytes += mcpMetaSize({ source, meta }, this.limits.metaBytes) + 1;
|
|
699
|
+
requireCondition(bytes <= this.limits.metaBytes &&
|
|
700
|
+
meta.every((item) => item &&
|
|
701
|
+
["result", "content", "resource", "entry", "message"].includes(item.target) &&
|
|
702
|
+
item.meta &&
|
|
703
|
+
!Array.isArray(item.meta) &&
|
|
704
|
+
typeof item.meta === "object"), "mcp_meta_too_large", "Saved Host-only metadata exceeds its separate budget or is malformed.");
|
|
705
|
+
return { source, meta, method: value.method };
|
|
706
|
+
});
|
|
707
|
+
}
|
|
708
|
+
async #authorizeMcp(result, scope) {
|
|
709
|
+
for (const entry of this.#mcpSources(result)) {
|
|
710
|
+
if (!entry.meta.length)
|
|
711
|
+
continue;
|
|
712
|
+
requireCondition(this.mcp, "mcp_source_unavailable", "The original remote result source is unavailable.");
|
|
713
|
+
// Received fixed bytes remain historical artifacts after the connection closes.
|
|
714
|
+
// Host-only metadata still needs this caller's current connection authority.
|
|
715
|
+
const authority = this.mcp.authority(scope, entry.source);
|
|
716
|
+
authority.assertCurrent();
|
|
717
|
+
authority.authorizeConnection(entry.source.connection, undefined, "result");
|
|
718
|
+
}
|
|
719
|
+
for (const item of result.content)
|
|
720
|
+
if (item.type === "resource_link" && item.remote) {
|
|
721
|
+
const remote = item.remote;
|
|
722
|
+
requireCondition(this.mcp && typeof remote.uri === "string", "invalid_saved_result", "A saved remote coordinate is invalid.");
|
|
723
|
+
await this.mcp.resolve(mcpSource(remote.source), scope, "resources.read", remote.uri);
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
#applyMcpMeta(result, response) {
|
|
727
|
+
const sources = this.#mcpSources(result);
|
|
728
|
+
if (!sources.some((source) => source.meta.length))
|
|
729
|
+
return;
|
|
730
|
+
const slots = sources.map((entry, slot) => ({
|
|
731
|
+
slot,
|
|
732
|
+
connection: entry.source.connection,
|
|
733
|
+
extensionId: entry.source.extensionId,
|
|
734
|
+
revision: entry.source.origin.revision,
|
|
735
|
+
method: entry.method,
|
|
736
|
+
contentIndices: result.content.flatMap((item, index) => item.mcp?.slot === slot
|
|
737
|
+
? [{ index, sourceIndex: item.mcp.index }]
|
|
738
|
+
: []),
|
|
739
|
+
protocolMeta: entry.meta,
|
|
740
|
+
}));
|
|
741
|
+
const root = sources.length === 1
|
|
742
|
+
? sources[0].meta.find((item) => item.target === "result")?.meta
|
|
743
|
+
: undefined;
|
|
744
|
+
const hostMeta = { ...(root ?? {}) };
|
|
745
|
+
let key = "io.nexum/mcp", suffix = 0;
|
|
746
|
+
while (Object.hasOwn(hostMeta, key))
|
|
747
|
+
key = `io.nexum/mcp/${++suffix}`;
|
|
748
|
+
hostMeta[key] = { results: slots };
|
|
749
|
+
response._meta = hostMeta;
|
|
750
|
+
mcpMetaSize(response._meta, this.limits.metaBytes);
|
|
751
|
+
}
|
|
752
|
+
#transfers(result) {
|
|
753
|
+
if (result.transferOffers === undefined)
|
|
754
|
+
return [];
|
|
755
|
+
requireCondition(Array.isArray(result.transferOffers) &&
|
|
756
|
+
result.transferOffers.length <= 1024, "invalid_saved_result", "Saved transfer references must be a bounded array.");
|
|
757
|
+
try {
|
|
758
|
+
canonicalJson(result.transferOffers, Math.min(this.limits.textBytes, 65536));
|
|
759
|
+
}
|
|
760
|
+
catch {
|
|
761
|
+
throw new AgentError("result_transfer_too_large", "Saved transfer references exceed their bounded budget.");
|
|
762
|
+
}
|
|
763
|
+
const seen = new Set();
|
|
764
|
+
return result.transferOffers.map((value) => {
|
|
765
|
+
requireCondition(value &&
|
|
766
|
+
!Array.isArray(value) &&
|
|
767
|
+
typeof value === "object" &&
|
|
768
|
+
Object.keys(value).every((key) => ["reference", "snapshot"].includes(key)), "invalid_saved_result", "A saved transfer entry contains unsupported fields.");
|
|
769
|
+
const reference = transferReference(value.reference), snapshot = issuedTransferSnapshot(value.snapshot);
|
|
770
|
+
requireCondition(reference.transferId === snapshot.transferId &&
|
|
771
|
+
reference.expiresAt === snapshot.expiresAt &&
|
|
772
|
+
!seen.has(reference.transferId), "invalid_saved_result", "Saved transfer identity and snapshot must agree without duplicates.");
|
|
773
|
+
seen.add(reference.transferId);
|
|
774
|
+
return { reference, snapshot };
|
|
775
|
+
});
|
|
776
|
+
}
|
|
777
|
+
async #fit(result, scope) {
|
|
778
|
+
const hasData = Object.hasOwn(result, "data") || Object.hasOwn(result, "mcpResults");
|
|
779
|
+
const dataText = hasData
|
|
780
|
+
? JSON.stringify({
|
|
781
|
+
...(Object.hasOwn(result, "data") ? { data: result.data } : {}),
|
|
782
|
+
...(result.mcpResults ? { mcpResults: result.mcpResults } : {}),
|
|
783
|
+
...(result.conversions ? { conversions: result.conversions } : {}),
|
|
784
|
+
})
|
|
785
|
+
: undefined;
|
|
786
|
+
let obvious = dataText !== undefined &&
|
|
787
|
+
Buffer.byteLength(dataText) > this.limits.textBytes;
|
|
788
|
+
let plainBytes = 0;
|
|
789
|
+
for (const item of result.content)
|
|
790
|
+
if (item.type === "text" && typeof item.text === "string")
|
|
791
|
+
plainBytes += Buffer.byteLength(item.text);
|
|
792
|
+
obvious ||= plainBytes > this.limits.textBytes;
|
|
793
|
+
let size = obvious
|
|
794
|
+
? this.limits.textBytes + 1
|
|
795
|
+
: Buffer.byteLength(JSON.stringify(this.#projection(result, { runId: scope.runId ?? "", status: "succeeded" }, true)));
|
|
796
|
+
for (const item of result.content)
|
|
797
|
+
if (item.type === "resource" && item.encoding === "text")
|
|
798
|
+
size += Number(item.inlineTextBytes ?? record(item.resource).size);
|
|
799
|
+
if (size <= this.limits.textBytes)
|
|
800
|
+
return;
|
|
801
|
+
// Keep the whole normalized JSON or text in an actual resource and make the incomplete model view explicit.
|
|
802
|
+
const summary = [];
|
|
803
|
+
let changed = false;
|
|
804
|
+
if (hasData) {
|
|
805
|
+
const resource = await this.artifacts.register({
|
|
806
|
+
data: Buffer.from(dataText),
|
|
807
|
+
name: "result.json",
|
|
808
|
+
mimeType: "application/json",
|
|
809
|
+
}, scope);
|
|
810
|
+
delete result.data;
|
|
811
|
+
delete result.conversions;
|
|
812
|
+
delete result.mcpResults;
|
|
813
|
+
changed = true;
|
|
814
|
+
summary.push({
|
|
815
|
+
type: "resource_link",
|
|
816
|
+
resource: recordJson(resource),
|
|
817
|
+
mimeType: resource.mimeType,
|
|
818
|
+
});
|
|
819
|
+
result.delivery = {
|
|
820
|
+
complete: false,
|
|
821
|
+
reason: "context_budget",
|
|
822
|
+
dataResource: recordJson(resource),
|
|
823
|
+
};
|
|
824
|
+
}
|
|
825
|
+
const afterDataBytes = plainBytes > this.limits.textBytes
|
|
826
|
+
? this.limits.textBytes + 1
|
|
827
|
+
: Buffer.byteLength(JSON.stringify(this.#projection(result, { runId: scope.runId ?? "", status: "succeeded" }, true)));
|
|
828
|
+
let textResource;
|
|
829
|
+
if (afterDataBytes > this.limits.textBytes && plainBytes > 0) {
|
|
830
|
+
const texts = result.content
|
|
831
|
+
.map((item, index) => ({ item, index }))
|
|
832
|
+
.filter(({ item }) => item.type === "text");
|
|
833
|
+
const normalized = await normalizeData(texts, {
|
|
834
|
+
mode: "data",
|
|
835
|
+
maxBytes: this.limits.maxDataBytes,
|
|
836
|
+
assertCurrent: () => scope.assertCurrent(),
|
|
837
|
+
});
|
|
838
|
+
const bytes = Buffer.from(JSON.stringify(normalized.data));
|
|
839
|
+
textResource = await this.artifacts.register({
|
|
840
|
+
data: bytes,
|
|
841
|
+
name: "result-content.json",
|
|
842
|
+
mimeType: "application/json",
|
|
843
|
+
}, scope);
|
|
844
|
+
changed = true;
|
|
845
|
+
result.delivery = {
|
|
846
|
+
...(result.delivery ?? {}),
|
|
847
|
+
complete: false,
|
|
848
|
+
reason: "context_budget",
|
|
849
|
+
textResource: recordJson(textResource),
|
|
850
|
+
};
|
|
851
|
+
}
|
|
852
|
+
let linked = false;
|
|
853
|
+
for (const item of result.content) {
|
|
854
|
+
if (textResource && item.type === "text") {
|
|
855
|
+
if (!linked)
|
|
856
|
+
summary.push({
|
|
857
|
+
type: "resource_link",
|
|
858
|
+
resource: recordJson(textResource),
|
|
859
|
+
mimeType: textResource.mimeType,
|
|
860
|
+
});
|
|
861
|
+
linked = true;
|
|
862
|
+
}
|
|
863
|
+
else
|
|
864
|
+
summary.push(item);
|
|
865
|
+
}
|
|
866
|
+
if (changed) {
|
|
867
|
+
result.content = summary;
|
|
868
|
+
result.content.unshift({
|
|
869
|
+
type: "text",
|
|
870
|
+
text: "结果超过模型上下文预算,完整内容已保存为资源;当前返回资源引用。",
|
|
871
|
+
});
|
|
872
|
+
}
|
|
873
|
+
const control = this.#projection(result, { runId: scope.runId ?? "", status: "succeeded" }, true);
|
|
874
|
+
let bytes = Buffer.byteLength(JSON.stringify(control));
|
|
875
|
+
for (const item of result.content)
|
|
876
|
+
if (item.type === "resource" && item.encoding === "text")
|
|
877
|
+
bytes += Number(item.inlineTextBytes ?? record(item.resource).size);
|
|
878
|
+
requireCondition(bytes <= this.limits.textBytes, "result_context_too_large", "The result metadata or explicitly embedded text exceeds its context budget; choose resource links.");
|
|
879
|
+
}
|
|
880
|
+
async describe(result, scope, options = {}) {
|
|
881
|
+
authorizeCall(() => scope.assertCurrent());
|
|
882
|
+
scope.signal?.throwIfAborted();
|
|
883
|
+
result = JSON.parse(JSON.stringify(copyMcpJSON(result, Math.min(128 * MiB, Math.max(this.limits.textBytes * 4, MiB) + this.limits.metaBytes))));
|
|
884
|
+
if (options.textBytes !== undefined) {
|
|
885
|
+
requireCondition(Number.isSafeInteger(options.textBytes) && options.textBytes > 0, "invalid_result_options", "The current result text budget must be a positive integer.");
|
|
886
|
+
if (!options.readOnly && options.textBytes < this.limits.textBytes) {
|
|
887
|
+
const encoder = new ResultEncoder(this.artifacts, { ...this.limits, textBytes: options.textBytes }, this.offers, this.mcp);
|
|
888
|
+
await encoder.#fit(result, scope);
|
|
889
|
+
return encoder.describe(result, scope);
|
|
890
|
+
}
|
|
891
|
+
}
|
|
892
|
+
if (!options.readOnly)
|
|
893
|
+
await this.#authorizeMcp(result, scope);
|
|
894
|
+
const projected = this.#projection(result, {}, false);
|
|
895
|
+
const visible = projected.content;
|
|
896
|
+
const content = [];
|
|
897
|
+
const artifact = (value) => ({
|
|
898
|
+
uri: value.uri,
|
|
899
|
+
name: value.name,
|
|
900
|
+
mimeType: value.mimeType,
|
|
901
|
+
size: value.size,
|
|
902
|
+
sha256: value.sha256,
|
|
903
|
+
expiresAt: value.expiresAt,
|
|
904
|
+
});
|
|
905
|
+
for (let index = 0; index < result.content.length; index++) {
|
|
906
|
+
const item = result.content[index], view = visible[index];
|
|
907
|
+
if (item.type === "text" ||
|
|
908
|
+
(item.type === "resource_link" && item.remote)) {
|
|
909
|
+
content.push(view);
|
|
910
|
+
continue;
|
|
911
|
+
}
|
|
912
|
+
const fixed = await this.artifacts.metadata(record(item.resource).uri, scope);
|
|
913
|
+
const metadata = {
|
|
914
|
+
...(view.annotations === undefined
|
|
915
|
+
? {}
|
|
916
|
+
: { annotations: view.annotations }),
|
|
917
|
+
...(view.description === undefined
|
|
918
|
+
? {}
|
|
919
|
+
: { description: view.description }),
|
|
920
|
+
};
|
|
921
|
+
if (item.type === "resource_link")
|
|
922
|
+
content.push(view);
|
|
923
|
+
else if (item.type === "resource")
|
|
924
|
+
content.push({
|
|
925
|
+
type: "resource",
|
|
926
|
+
resource: artifact(fixed),
|
|
927
|
+
uri: view.resource.uri,
|
|
928
|
+
encoding: item.encoding,
|
|
929
|
+
...metadata,
|
|
930
|
+
});
|
|
931
|
+
else {
|
|
932
|
+
requireCondition((item.type === "image" || item.type === "audio") &&
|
|
933
|
+
fixed.size <=
|
|
934
|
+
(item.type === "image"
|
|
935
|
+
? this.limits.imageBytes
|
|
936
|
+
: this.limits.audioBytes), "inline_media_too_large", "The retained media exceeds the current delivery budget.");
|
|
937
|
+
content.push({
|
|
938
|
+
type: item.type,
|
|
939
|
+
resource: artifact(fixed),
|
|
940
|
+
mimeType: view.mimeType,
|
|
941
|
+
...metadata,
|
|
942
|
+
});
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
const structured = projected.structuredContent;
|
|
946
|
+
const described = {
|
|
947
|
+
content,
|
|
948
|
+
...(Object.hasOwn(result, "data") ? { data: result.data } : {}),
|
|
949
|
+
...(result.conversions === undefined
|
|
950
|
+
? {}
|
|
951
|
+
: { conversions: result.conversions }),
|
|
952
|
+
...(structured.mcpResults === undefined
|
|
953
|
+
? {}
|
|
954
|
+
: { mcpResults: structured.mcpResults }),
|
|
955
|
+
...(result.isError === undefined ? {} : { isError: result.isError }),
|
|
956
|
+
...(result.resultType === undefined
|
|
957
|
+
? {}
|
|
958
|
+
: { resultType: result.resultType }),
|
|
959
|
+
};
|
|
960
|
+
if (result.delivery) {
|
|
961
|
+
const delivery = result.delivery;
|
|
962
|
+
const fixedDelivery = {
|
|
963
|
+
complete: delivery.complete,
|
|
964
|
+
reason: delivery.reason,
|
|
965
|
+
};
|
|
966
|
+
for (const key of ["dataResource", "textResource"])
|
|
967
|
+
if (delivery[key])
|
|
968
|
+
fixedDelivery[key] = artifact(await this.artifacts.metadata(record(delivery[key]).uri, scope));
|
|
969
|
+
described.delivery = fixedDelivery;
|
|
970
|
+
}
|
|
971
|
+
const meta = {};
|
|
972
|
+
if (!options.readOnly)
|
|
973
|
+
this.#applyMcpMeta(result, meta);
|
|
974
|
+
const transfers = this.#transfers(result).map((entry) => {
|
|
975
|
+
const delivery = (options.readOnly
|
|
976
|
+
? undefined
|
|
977
|
+
: this.offers?.deliver(entry.reference, scope)) ?? {
|
|
978
|
+
transferId: entry.reference.transferId,
|
|
979
|
+
available: false,
|
|
980
|
+
reason: options.readOnly ? "read_only_view" : "delivery_unavailable",
|
|
981
|
+
};
|
|
982
|
+
const value = {
|
|
983
|
+
transferId: delivery.transferId,
|
|
984
|
+
available: delivery.available,
|
|
985
|
+
};
|
|
986
|
+
if (delivery.available)
|
|
987
|
+
value.request = delivery.request;
|
|
988
|
+
else
|
|
989
|
+
value.reason = delivery.reason;
|
|
990
|
+
return value;
|
|
991
|
+
});
|
|
992
|
+
authorizeCall(() => scope.assertCurrent());
|
|
993
|
+
scope.signal?.throwIfAborted();
|
|
994
|
+
return {
|
|
995
|
+
result: described,
|
|
996
|
+
...(meta._meta ? { hostMeta: meta._meta } : {}),
|
|
997
|
+
transfers,
|
|
998
|
+
};
|
|
999
|
+
}
|
|
1000
|
+
async render(result, scope, run, options = {}) {
|
|
1001
|
+
scope.assertCurrent();
|
|
1002
|
+
scope.signal?.throwIfAborted();
|
|
1003
|
+
// Only normalized saved JSON is accepted; caller-supplied functions/accessors never reach the protocol boundary.
|
|
1004
|
+
result = JSON.parse(JSON.stringify(copyMcpJSON(result, Math.min(128 * MiB, Math.max(this.limits.textBytes * 4, MiB) + this.limits.metaBytes))));
|
|
1005
|
+
await this.#authorizeMcp(result, scope);
|
|
1006
|
+
const response = this.#projection(result, asJson(run), options.textFallback ?? true);
|
|
1007
|
+
const content = response.content;
|
|
1008
|
+
const maximum = Math.min(this.limits.responseBytes, options.maxResponseBytes ?? this.limits.responseBytes);
|
|
1009
|
+
requireCondition(Number.isSafeInteger(maximum) && maximum > 0, "invalid_result_options", "The actual response budget must be a positive integer.");
|
|
1010
|
+
const control = this.#projection(result, asJson(run), options.textFallback ?? true);
|
|
1011
|
+
const transfers = this.#transfers(result);
|
|
1012
|
+
const applyTransfers = () => {
|
|
1013
|
+
if (transfers.length) {
|
|
1014
|
+
const current = transfers.map((item) => ({
|
|
1015
|
+
...(this.offers
|
|
1016
|
+
? this.offers.deliver(item.reference, scope)
|
|
1017
|
+
: {
|
|
1018
|
+
transferId: item.reference.transferId,
|
|
1019
|
+
available: false,
|
|
1020
|
+
reason: "delivery_unavailable",
|
|
1021
|
+
}),
|
|
1022
|
+
snapshot: item.snapshot,
|
|
1023
|
+
}));
|
|
1024
|
+
for (const target of [response, control]) {
|
|
1025
|
+
const structured = target.structuredContent;
|
|
1026
|
+
structured.delivery = {
|
|
1027
|
+
...(structured.delivery ?? {}),
|
|
1028
|
+
transfers: current,
|
|
1029
|
+
};
|
|
1030
|
+
}
|
|
1031
|
+
}
|
|
1032
|
+
};
|
|
1033
|
+
applyTransfers();
|
|
1034
|
+
this.#applyMcpMeta(result, response);
|
|
1035
|
+
const hostMetaBytes = response._meta === undefined
|
|
1036
|
+
? 0
|
|
1037
|
+
: mcpMetaSize(response._meta, this.limits.metaBytes) + 10;
|
|
1038
|
+
let inlineBytes = 0, encodedBinaryBytes = 0;
|
|
1039
|
+
for (let i = 0; i < result.content.length; i++) {
|
|
1040
|
+
const item = result.content[i];
|
|
1041
|
+
requireCondition(["text", "image", "audio", "resource_link", "resource"].includes(item.type), "invalid_saved_result", "The saved content type is unsupported.");
|
|
1042
|
+
if (item.type === "text")
|
|
1043
|
+
continue;
|
|
1044
|
+
if (item.type === "resource_link" && item.remote)
|
|
1045
|
+
continue;
|
|
1046
|
+
const source = record(item.resource), kind = item.type;
|
|
1047
|
+
const actual = await this.artifacts.metadata(source.uri, scope);
|
|
1048
|
+
requireCondition(actual.sha256 === source.sha256 &&
|
|
1049
|
+
actual.size === source.size &&
|
|
1050
|
+
actual.mimeType === source.mimeType, "saved_resource_changed", "The historical content no longer matches its fixed identity.", { uri: source.uri });
|
|
1051
|
+
if (kind === "resource_link")
|
|
1052
|
+
continue;
|
|
1053
|
+
if (kind === "image" || kind === "audio") {
|
|
1054
|
+
const mimeType = item.mimeType;
|
|
1055
|
+
const supported = kind === "image" ? options.supportedImages : options.supportedAudio;
|
|
1056
|
+
requireCondition(!supported || supported.has(new MIMEType(mimeType).essence), "host_content_unsupported", "This Host does not support the saved media type.", { uri: source.uri, mimeType });
|
|
1057
|
+
}
|
|
1058
|
+
const cap = kind === "image"
|
|
1059
|
+
? this.limits.imageBytes
|
|
1060
|
+
: kind === "audio"
|
|
1061
|
+
? this.limits.audioBytes
|
|
1062
|
+
: item.encoding === "text"
|
|
1063
|
+
? this.limits.textBytes
|
|
1064
|
+
: this.limits.inlineBytes;
|
|
1065
|
+
if (!(kind === "resource" && item.encoding === "text")) {
|
|
1066
|
+
encodedBinaryBytes += Math.ceil(source.size / 3) * 4;
|
|
1067
|
+
requireCondition(encodedBinaryBytes +
|
|
1068
|
+
Buffer.byteLength(JSON.stringify(control)) +
|
|
1069
|
+
hostMetaBytes <=
|
|
1070
|
+
maximum, "mcp_response_too_large", "Encoded media exceeds the actual transport/Host budget.");
|
|
1071
|
+
}
|
|
1072
|
+
const bytes = await this.artifacts.read(source.uri, scope, {
|
|
1073
|
+
maxBytes: Math.min(cap, this.artifacts.maxReadBytes),
|
|
1074
|
+
});
|
|
1075
|
+
requireCondition(bytes.resource.sha256 === source.sha256 &&
|
|
1076
|
+
bytes.resource.size === source.size, "saved_resource_changed", "The historical content no longer matches its fixed identity.", { uri: source.uri });
|
|
1077
|
+
if (kind === "resource" && item.encoding === "text") {
|
|
1078
|
+
let text;
|
|
1079
|
+
try {
|
|
1080
|
+
text = new TextDecoder("utf-8", { fatal: true }).decode(bytes.data);
|
|
1081
|
+
}
|
|
1082
|
+
catch {
|
|
1083
|
+
throw new AgentError("invalid_resource_text", "The resource is not valid UTF-8 text; return it as a binary resource.", { uri: source.uri });
|
|
1084
|
+
}
|
|
1085
|
+
content[i].resource.text = text;
|
|
1086
|
+
control.content[i].resource.text =
|
|
1087
|
+
text;
|
|
1088
|
+
}
|
|
1089
|
+
else {
|
|
1090
|
+
inlineBytes += bytes.data.length;
|
|
1091
|
+
requireCondition(inlineBytes <= this.limits.inlineBytes, "inline_content_too_large", "Saved content exceeds its aggregate inline budget.");
|
|
1092
|
+
if (kind === "image" || kind === "audio")
|
|
1093
|
+
await validateMedia(bytes.data, kind, item.mimeType, {
|
|
1094
|
+
signal: scope.signal,
|
|
1095
|
+
maxBytes: cap,
|
|
1096
|
+
});
|
|
1097
|
+
if (kind === "resource")
|
|
1098
|
+
content[i].resource.blob =
|
|
1099
|
+
bytes.data.toString("base64");
|
|
1100
|
+
else
|
|
1101
|
+
content[i].data = bytes.data.toString("base64");
|
|
1102
|
+
}
|
|
1103
|
+
}
|
|
1104
|
+
// Resource I/O may yield long enough for a channel to be claimed, expire or
|
|
1105
|
+
// lose authority. Re-project current delivery immediately before returning.
|
|
1106
|
+
applyTransfers();
|
|
1107
|
+
await this.#authorizeMcp(result, scope);
|
|
1108
|
+
requireCondition(Buffer.byteLength(JSON.stringify(control)) <= this.limits.textBytes, "result_context_too_large", "The final text/structured response exceeds the model context budget.");
|
|
1109
|
+
requireCondition(Number.isSafeInteger(maximum) &&
|
|
1110
|
+
maximum > 0 &&
|
|
1111
|
+
Buffer.byteLength(JSON.stringify(response)) <= maximum, "mcp_response_too_large", "The final MCP response exceeds the actual transport/Host budget.");
|
|
1112
|
+
scope.assertCurrent();
|
|
1113
|
+
scope.signal?.throwIfAborted();
|
|
1114
|
+
return response;
|
|
1115
|
+
}
|
|
1116
|
+
async listResources(scope, page = {}) {
|
|
1117
|
+
const result = await this.artifacts.list(scope, page);
|
|
1118
|
+
const response = {
|
|
1119
|
+
resources: result.resources.map((resource) => ({
|
|
1120
|
+
uri: resource.uri,
|
|
1121
|
+
name: resource.name,
|
|
1122
|
+
mimeType: resource.mimeType,
|
|
1123
|
+
size: resource.size,
|
|
1124
|
+
})),
|
|
1125
|
+
...(result.nextCursor ? { nextCursor: result.nextCursor } : {}),
|
|
1126
|
+
};
|
|
1127
|
+
requireCondition(Buffer.byteLength(JSON.stringify(response)) <=
|
|
1128
|
+
Math.min(this.limits.textBytes, this.limits.responseBytes), "resource_list_too_large", "The resource directory exceeds this response budget; request a smaller page.");
|
|
1129
|
+
return response;
|
|
1130
|
+
}
|
|
1131
|
+
/** Standard resources/read uses text/blob bodies, never image/audio tool blocks. */
|
|
1132
|
+
async readResource(uri, scope) {
|
|
1133
|
+
if (/^nexum:\/\/agents\/[^/]+\/mcp\//.test(uri)) {
|
|
1134
|
+
requireCondition(this.mcp, "mcp_source_unavailable", "Remote resource routing is unavailable.");
|
|
1135
|
+
return await this.mcp.readResource(uri, scope, this.limits);
|
|
1136
|
+
}
|
|
1137
|
+
const resource = await this.artifacts.metadata(uri, scope);
|
|
1138
|
+
const text = textMime(resource.mimeType), essence = new MIMEType(resource.mimeType).essence;
|
|
1139
|
+
const cap = text
|
|
1140
|
+
? this.limits.textBytes
|
|
1141
|
+
: essence.startsWith("image/")
|
|
1142
|
+
? this.limits.imageBytes
|
|
1143
|
+
: essence.startsWith("audio/")
|
|
1144
|
+
? this.limits.audioBytes
|
|
1145
|
+
: this.limits.inlineBytes;
|
|
1146
|
+
const empty = {
|
|
1147
|
+
contents: [
|
|
1148
|
+
{
|
|
1149
|
+
uri: resource.uri,
|
|
1150
|
+
mimeType: resource.mimeType,
|
|
1151
|
+
...(text ? { text: "" } : { blob: "" }),
|
|
1152
|
+
},
|
|
1153
|
+
],
|
|
1154
|
+
};
|
|
1155
|
+
requireCondition(Buffer.byteLength(JSON.stringify(empty)) +
|
|
1156
|
+
(text ? resource.size : Math.ceil(resource.size / 3) * 4) <=
|
|
1157
|
+
this.limits.responseBytes, "mcp_response_too_large", "The encoded resource exceeds its response budget before reading.", { uri });
|
|
1158
|
+
const fixed = await this.artifacts.read(uri, scope, {
|
|
1159
|
+
maxBytes: Math.min(cap, this.artifacts.maxReadBytes),
|
|
1160
|
+
});
|
|
1161
|
+
const body = { uri: resource.uri, mimeType: resource.mimeType };
|
|
1162
|
+
if (text) {
|
|
1163
|
+
try {
|
|
1164
|
+
body.text = new TextDecoder("utf-8", { fatal: true }).decode(fixed.data);
|
|
1165
|
+
}
|
|
1166
|
+
catch {
|
|
1167
|
+
throw new AgentError("invalid_resource_text", "The registered resource is not valid UTF-8 text.", { uri });
|
|
1168
|
+
}
|
|
1169
|
+
}
|
|
1170
|
+
else
|
|
1171
|
+
body.blob = fixed.data.toString("base64");
|
|
1172
|
+
const response = { contents: [body] };
|
|
1173
|
+
if (text)
|
|
1174
|
+
requireCondition(Buffer.byteLength(JSON.stringify(response)) <= this.limits.textBytes, "resource_read_too_large", "The encoded text resource exceeds the context budget; use transfer.createDownload({ uri }) for a file stream.", { uri });
|
|
1175
|
+
requireCondition(Buffer.byteLength(JSON.stringify(response)) <= this.limits.responseBytes, "mcp_response_too_large", "The resource response exceeds its final encoded budget.", { uri });
|
|
1176
|
+
return response;
|
|
1177
|
+
}
|
|
1178
|
+
}
|
|
1179
|
+
//# sourceMappingURL=encoder.js.map
|