@nexum-hub/agent 0.0.0-stage → 0.0.2
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 +133 -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,1159 @@
|
|
|
1
|
+
import { EventEmitter, once } from "node:events";
|
|
2
|
+
import { Console } from "node:console";
|
|
3
|
+
import { performance } from "node:perf_hooks";
|
|
4
|
+
import { readFileSync, realpathSync, statSync, openSync, readSync, closeSync, fstatSync, constants, } from "node:fs";
|
|
5
|
+
import { types } from "node:util";
|
|
6
|
+
import { StringDecoder } from "node:string_decoder";
|
|
7
|
+
import path from "node:path";
|
|
8
|
+
import { AgentError, requireCondition } from "../contracts/errors.js";
|
|
9
|
+
import { safeErrorData } from "../contracts/error-data.js";
|
|
10
|
+
import { canonicalJson, digest } from "../contracts/json.js";
|
|
11
|
+
import { terminalStatuses } from "../contracts/types.js";
|
|
12
|
+
import { compileInputSchema, validateContract, } from "../contracts/validation.js";
|
|
13
|
+
import { scriptHeader } from "./scripts.js";
|
|
14
|
+
import { createHash } from "node:crypto";
|
|
15
|
+
import { atomicText, contains, privateDirectory } from "./paths.js";
|
|
16
|
+
import { RunOperations } from "./operations.js";
|
|
17
|
+
import { qualifyControlScript } from "./control-scripts.js";
|
|
18
|
+
import { RunLog, readRunLogRange } from "./run-log.js";
|
|
19
|
+
import { authorizeCall, callerKey, fixedCaller, } from "../contracts/caller.js";
|
|
20
|
+
export { callerKey } from "../contracts/caller.js";
|
|
21
|
+
function failure(error, phase) {
|
|
22
|
+
// Exceptions never cross the control plane with host stack, cause or configuration.
|
|
23
|
+
return {
|
|
24
|
+
...safeErrorData(error, {
|
|
25
|
+
code: phase === "compile" ? "script_syntax_error" : "script_execution_failed",
|
|
26
|
+
message: phase === "compile"
|
|
27
|
+
? "The JavaScript body could not be compiled."
|
|
28
|
+
: "The script or its result processing failed; inspect the local run log.",
|
|
29
|
+
}),
|
|
30
|
+
phase,
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
function frozenJson(value) {
|
|
34
|
+
const copy = JSON.parse(canonicalJson(value, 2 * 1024 * 1024));
|
|
35
|
+
const freeze = (item) => {
|
|
36
|
+
if (item && typeof item === "object") {
|
|
37
|
+
for (const nested of Object.values(item))
|
|
38
|
+
freeze(nested);
|
|
39
|
+
Object.freeze(item);
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
freeze(copy);
|
|
43
|
+
return copy;
|
|
44
|
+
}
|
|
45
|
+
function attachmentIntent(references = []) {
|
|
46
|
+
return references.map((reference) => {
|
|
47
|
+
if (typeof reference.sourceId === "string")
|
|
48
|
+
return { sourceId: reference.sourceId };
|
|
49
|
+
// Host temporary URLs are delivery credentials, not a submission's identity.
|
|
50
|
+
if (typeof reference.file_id === "string")
|
|
51
|
+
return {
|
|
52
|
+
file_id: reference.file_id,
|
|
53
|
+
...(reference.file_name === undefined
|
|
54
|
+
? {}
|
|
55
|
+
: { file_name: reference.file_name }),
|
|
56
|
+
...(reference.mime_type === undefined
|
|
57
|
+
? {}
|
|
58
|
+
: { mime_type: reference.mime_type }),
|
|
59
|
+
};
|
|
60
|
+
if (typeof reference.transferId === "string")
|
|
61
|
+
return { transferId: reference.transferId };
|
|
62
|
+
return { uri: reference.uri };
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
const historyDenials = new Set([
|
|
66
|
+
"forbidden",
|
|
67
|
+
"permission_denied",
|
|
68
|
+
"access_denied",
|
|
69
|
+
"resource_forbidden",
|
|
70
|
+
"path_not_allowed",
|
|
71
|
+
"unauthorized",
|
|
72
|
+
]);
|
|
73
|
+
function deniedHistory(cause) {
|
|
74
|
+
if (!cause || typeof cause !== "object" || types.isProxy(cause))
|
|
75
|
+
return false;
|
|
76
|
+
const code = Object.getOwnPropertyDescriptor(cause, "code");
|
|
77
|
+
return !!code && "value" in code && historyDenials.has(code.value);
|
|
78
|
+
}
|
|
79
|
+
export class RunEngine extends EventEmitter {
|
|
80
|
+
#scopes = new Map();
|
|
81
|
+
#inputDeliveries = new Map();
|
|
82
|
+
store;
|
|
83
|
+
loader;
|
|
84
|
+
scripts;
|
|
85
|
+
#options;
|
|
86
|
+
constructor(store, loader, scripts, options) {
|
|
87
|
+
super();
|
|
88
|
+
this.setMaxListeners(0); // Each observer has a bounded, individually cancelled once listener.
|
|
89
|
+
requireCondition(scripts.work === path.join(store.root, "work") &&
|
|
90
|
+
loader.work === scripts.work &&
|
|
91
|
+
scripts.owner === `local:${store.binding.agentId}`, "runtime_profile_mismatch", "Runtime components must use this Agent's one profile/work environment.");
|
|
92
|
+
this.store = store;
|
|
93
|
+
this.loader = loader;
|
|
94
|
+
this.scripts = scripts;
|
|
95
|
+
this.#options = options;
|
|
96
|
+
requireCondition(!options.resources || options.resources.store === store, "runtime_profile_mismatch", "Managed resources must use this runtime's actual Agent/profile store.");
|
|
97
|
+
}
|
|
98
|
+
#publish(runId) {
|
|
99
|
+
this.emit(runId);
|
|
100
|
+
}
|
|
101
|
+
activeSnapshotRefs() {
|
|
102
|
+
return new Set([...this.#scopes.values()].map((scope) => scope.work.snapshotRef));
|
|
103
|
+
}
|
|
104
|
+
#authorize(caller, target) {
|
|
105
|
+
authorizeCall(() => this.#options.authorize(caller, target));
|
|
106
|
+
}
|
|
107
|
+
#run(caller, runId, action) {
|
|
108
|
+
const run = this.store.getRun(runId);
|
|
109
|
+
this.#authorize(caller, { action, run });
|
|
110
|
+
this.#checkDeadline(this.#scopes.get(runId));
|
|
111
|
+
return this.store.getRun(runId);
|
|
112
|
+
}
|
|
113
|
+
#relative(filename) {
|
|
114
|
+
return path.relative(this.store.root, filename).split(path.sep).join("/");
|
|
115
|
+
}
|
|
116
|
+
#read(ref, runId, limit = 2 * 1024 * 1024) {
|
|
117
|
+
requireCondition(ref, "snapshot_unavailable", "The retained run snapshot is unavailable.");
|
|
118
|
+
const expected = path.join(this.scripts.work, "tmp", "runs", runId);
|
|
119
|
+
const root = realpathSync.native(expected);
|
|
120
|
+
requireCondition(root === expected, "snapshot_unavailable", "The retained run root was redirected outside the Agent work directory.");
|
|
121
|
+
const filename = realpathSync.native(path.resolve(this.store.root, ref));
|
|
122
|
+
requireCondition(contains(root, filename) &&
|
|
123
|
+
statSync(filename).isFile() &&
|
|
124
|
+
statSync(filename).size <= limit, "snapshot_unavailable", "The snapshot is outside the run directory or exceeds its budget.");
|
|
125
|
+
return readFileSync(filename, "utf8");
|
|
126
|
+
}
|
|
127
|
+
#directory(runId) {
|
|
128
|
+
return privateDirectory(this.scripts.work, "tmp", "runs", runId);
|
|
129
|
+
}
|
|
130
|
+
#agent(agentId) {
|
|
131
|
+
requireCondition(agentId === this.store.binding.agentId, "agent_mismatch", "The query targets another Agent.");
|
|
132
|
+
}
|
|
133
|
+
async get(caller, input, signal) {
|
|
134
|
+
validateContract("agent.run.get", input);
|
|
135
|
+
input = JSON.parse(canonicalJson(input));
|
|
136
|
+
caller = fixedCaller(caller);
|
|
137
|
+
this.#agent(input.agentId);
|
|
138
|
+
this.#authorize(caller, { action: "get" });
|
|
139
|
+
const runId = input.runId ??
|
|
140
|
+
this.store.findSubmission(callerKey(caller), input.requestId).runId;
|
|
141
|
+
let view = await this.observe(caller, runId, input.waitMs ?? 0, signal);
|
|
142
|
+
// Observation can yield; inspect retained details only under current authority.
|
|
143
|
+
const current = this.#run(caller, runId, "get");
|
|
144
|
+
if (current.revision !== view.run.revision)
|
|
145
|
+
view = this.#view(caller, runId);
|
|
146
|
+
return {
|
|
147
|
+
...view,
|
|
148
|
+
snapshots: {
|
|
149
|
+
code: this.#snapshot(view.run, "code", true),
|
|
150
|
+
input: this.#snapshot(view.run, "input", true),
|
|
151
|
+
logs: this.#snapshot(view.run, "logs", true),
|
|
152
|
+
},
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
list(caller, input) {
|
|
156
|
+
validateContract("agent.run.list", input);
|
|
157
|
+
input = JSON.parse(canonicalJson(input));
|
|
158
|
+
caller = fixedCaller(caller);
|
|
159
|
+
this.#agent(input.agentId);
|
|
160
|
+
this.#authorize(caller, { action: "list" });
|
|
161
|
+
const time = (value) => {
|
|
162
|
+
if (value === undefined)
|
|
163
|
+
return undefined;
|
|
164
|
+
const milliseconds = Date.parse(value);
|
|
165
|
+
requireCondition(Number.isFinite(milliseconds), "invalid_range", "The history time must be representable.");
|
|
166
|
+
// SQLite accepts integer milliseconds. Keep RFC3339 sub-millisecond
|
|
167
|
+
// ordering before rounding both half-open boundaries up to that grid.
|
|
168
|
+
const fraction = /\.(\d+)(?:z|[+-]\d{2}:\d{2})$/i.exec(value)?.[1] ?? "";
|
|
169
|
+
const remainder = fraction.slice(3).replace(/0+$/, "");
|
|
170
|
+
return {
|
|
171
|
+
milliseconds,
|
|
172
|
+
remainder,
|
|
173
|
+
boundary: milliseconds + (remainder ? 1 : 0),
|
|
174
|
+
};
|
|
175
|
+
};
|
|
176
|
+
const from = time(input.from), to = time(input.to);
|
|
177
|
+
if (from && to) {
|
|
178
|
+
const precision = Math.max(from.remainder.length, to.remainder.length);
|
|
179
|
+
requireCondition(from.milliseconds < to.milliseconds ||
|
|
180
|
+
(from.milliseconds === to.milliseconds &&
|
|
181
|
+
from.remainder.padEnd(precision, "0") <=
|
|
182
|
+
to.remainder.padEnd(precision, "0")), "invalid_range", "The history start must not exceed the end.");
|
|
183
|
+
}
|
|
184
|
+
const filter = {
|
|
185
|
+
status: input.status,
|
|
186
|
+
scriptName: input.scriptName,
|
|
187
|
+
sourceKind: input.source === undefined
|
|
188
|
+
? undefined
|
|
189
|
+
: { inline: "inline", named: "script", history: "replay" }[input.source],
|
|
190
|
+
projectId: input.projectId,
|
|
191
|
+
contextId: input.contextId,
|
|
192
|
+
from: from?.boundary,
|
|
193
|
+
to: to?.boundary,
|
|
194
|
+
};
|
|
195
|
+
const scope = digest({
|
|
196
|
+
caller: callerKey(caller),
|
|
197
|
+
grantId: caller.grantId ?? null,
|
|
198
|
+
from: input.from ?? null,
|
|
199
|
+
to: input.to ?? null,
|
|
200
|
+
});
|
|
201
|
+
const runs = [];
|
|
202
|
+
let cursor = input.cursor, scanned = 0;
|
|
203
|
+
const limit = input.limit ?? 20;
|
|
204
|
+
// Bounded scan, including denied rows. A short/empty page can carry its
|
|
205
|
+
// opaque continuation without claiming that no further authorized history exists.
|
|
206
|
+
while (scanned < 1000) {
|
|
207
|
+
const page = this.store.scanRuns(filter, scope, Math.min(100, 1000 - scanned), cursor);
|
|
208
|
+
for (const item of page.items) {
|
|
209
|
+
let run;
|
|
210
|
+
try {
|
|
211
|
+
run = this.#run(caller, item.record.runId, "get");
|
|
212
|
+
}
|
|
213
|
+
catch (cause) {
|
|
214
|
+
if (!deniedHistory(cause))
|
|
215
|
+
throw cause;
|
|
216
|
+
cursor = item.cursor;
|
|
217
|
+
scanned++;
|
|
218
|
+
continue;
|
|
219
|
+
}
|
|
220
|
+
// Deadline observation or a reentrant current-policy callback can change
|
|
221
|
+
// mutable fields after SQL selected the candidate.
|
|
222
|
+
if ((filter.status !== undefined && run.status !== filter.status) ||
|
|
223
|
+
(filter.scriptName !== undefined &&
|
|
224
|
+
run.scriptName !== filter.scriptName)) {
|
|
225
|
+
cursor = item.cursor;
|
|
226
|
+
scanned++;
|
|
227
|
+
continue;
|
|
228
|
+
}
|
|
229
|
+
const summary = this.#summary(run);
|
|
230
|
+
if (Buffer.byteLength(canonicalJson({ runs: [...runs, summary], nextCursor: item.cursor }, 128 * 1024)) >
|
|
231
|
+
64 * 1024) {
|
|
232
|
+
requireCondition(runs.length > 0, "history_summary_too_large", "A retained history summary exceeds the page budget.");
|
|
233
|
+
return { runs, nextCursor: cursor ?? null };
|
|
234
|
+
}
|
|
235
|
+
runs.push(summary);
|
|
236
|
+
cursor = item.cursor;
|
|
237
|
+
scanned++;
|
|
238
|
+
if (runs.length === limit) {
|
|
239
|
+
const remaining = item !== page.items.at(-1) || page.more;
|
|
240
|
+
return { runs, nextCursor: remaining ? cursor : null };
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
if (!page.more)
|
|
244
|
+
return { runs, nextCursor: null };
|
|
245
|
+
}
|
|
246
|
+
return { runs, nextCursor: cursor ?? null };
|
|
247
|
+
}
|
|
248
|
+
#snapshot(run, kind, value = false) {
|
|
249
|
+
const ref = run[`${kind}Ref`];
|
|
250
|
+
if (!ref)
|
|
251
|
+
return { ref: null, status: "not_recorded", bytes: null };
|
|
252
|
+
let bytes = null;
|
|
253
|
+
try {
|
|
254
|
+
const expected = path.join(this.store.root, ...(kind === "logs"
|
|
255
|
+
? ["logs", "runs", run.runId]
|
|
256
|
+
: ["work", "tmp", "runs", run.runId]));
|
|
257
|
+
const root = realpathSync.native(expected);
|
|
258
|
+
const filename = realpathSync.native(path.resolve(this.store.root, ref));
|
|
259
|
+
requireCondition(root === expected && contains(root, filename), "snapshot_unavailable", "The retained snapshot was redirected.");
|
|
260
|
+
const file = openSync(filename, constants.O_RDONLY |
|
|
261
|
+
(constants.O_NOFOLLOW ?? 0) |
|
|
262
|
+
(constants.O_NONBLOCK ?? 0));
|
|
263
|
+
try {
|
|
264
|
+
const stat = fstatSync(file);
|
|
265
|
+
requireCondition(stat.isFile(), "snapshot_unavailable", "The retained snapshot is not a file.");
|
|
266
|
+
bytes = stat.size;
|
|
267
|
+
if (!value)
|
|
268
|
+
return { ref, status: "available", bytes };
|
|
269
|
+
if (kind !== "logs" && bytes > 8192)
|
|
270
|
+
return { ref, status: "too_large", bytes };
|
|
271
|
+
const maximum = kind === "logs" ? 4096 : 8192;
|
|
272
|
+
const range = kind === "logs" ? readRunLogRange(file, bytes) : null;
|
|
273
|
+
const dataOffset = range?.dataOffset ?? 0;
|
|
274
|
+
const buffer = Buffer.alloc(Math.min(bytes - dataOffset + 1, maximum + 1));
|
|
275
|
+
const count = readSync(file, buffer, 0, buffer.length, dataOffset);
|
|
276
|
+
if (kind !== "logs") {
|
|
277
|
+
if (count > 8192)
|
|
278
|
+
return { ref, status: "too_large", bytes: Math.max(bytes, count) };
|
|
279
|
+
return {
|
|
280
|
+
ref,
|
|
281
|
+
status: "available",
|
|
282
|
+
bytes,
|
|
283
|
+
value: JSON.parse(canonicalJson(JSON.parse(buffer.subarray(0, count).toString("utf8")), 8192)),
|
|
284
|
+
};
|
|
285
|
+
}
|
|
286
|
+
const text = new StringDecoder("utf8").write(buffer.subarray(0, Math.min(count, maximum)));
|
|
287
|
+
const consumed = Buffer.byteLength(text);
|
|
288
|
+
return {
|
|
289
|
+
ref,
|
|
290
|
+
status: "available",
|
|
291
|
+
bytes,
|
|
292
|
+
value: text,
|
|
293
|
+
startOffset: range.startOffset,
|
|
294
|
+
endOffset: range.endOffset,
|
|
295
|
+
dataOffset,
|
|
296
|
+
...(range.startOffset > 0 ||
|
|
297
|
+
consumed < bytes - dataOffset ||
|
|
298
|
+
count > maximum
|
|
299
|
+
? { truncated: true, nextOffset: dataOffset + consumed }
|
|
300
|
+
: {}),
|
|
301
|
+
};
|
|
302
|
+
}
|
|
303
|
+
finally {
|
|
304
|
+
closeSync(file);
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
catch {
|
|
308
|
+
return { ref, status: "unavailable", bytes };
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
#summary(run) {
|
|
312
|
+
const source = run.source;
|
|
313
|
+
const origin = source.origin;
|
|
314
|
+
const trustedOrigin = origin && typeof origin === "object" && !Array.isArray(origin)
|
|
315
|
+
? {
|
|
316
|
+
type: origin.type ?? null,
|
|
317
|
+
owner: origin.owner ?? null,
|
|
318
|
+
namespace: origin.namespace ?? null,
|
|
319
|
+
version: origin.version ?? null,
|
|
320
|
+
revision: origin.revision ?? null,
|
|
321
|
+
}
|
|
322
|
+
: null;
|
|
323
|
+
const description = typeof source.scriptDesc === "string" ? source.scriptDesc : null;
|
|
324
|
+
return {
|
|
325
|
+
runId: run.runId,
|
|
326
|
+
scriptName: run.scriptName,
|
|
327
|
+
scriptDesc: description === null ? null : description.slice(0, 2048),
|
|
328
|
+
...(description !== null && description.length > 2048
|
|
329
|
+
? { descriptionTruncated: true }
|
|
330
|
+
: {}),
|
|
331
|
+
source: { inline: "inline", script: "named", replay: "history" }[run.sourceKind],
|
|
332
|
+
origin: trustedOrigin,
|
|
333
|
+
projectId: run.projectId,
|
|
334
|
+
contextId: run.contextId,
|
|
335
|
+
status: run.status,
|
|
336
|
+
acceptedAt: new Date(run.acceptedAt).toISOString(),
|
|
337
|
+
startedAt: run.startedAt === null ? null : new Date(run.startedAt).toISOString(),
|
|
338
|
+
endedAt: run.endedAt === null ? null : new Date(run.endedAt).toISOString(),
|
|
339
|
+
replayOfRunId: typeof source.replayRunId === "string" ? source.replayRunId : null,
|
|
340
|
+
availability: {
|
|
341
|
+
code: this.#snapshot(run, "code").status,
|
|
342
|
+
input: this.#snapshot(run, "input").status,
|
|
343
|
+
result: this.#snapshot(run, "result").status,
|
|
344
|
+
logs: this.#snapshot(run, "logs").status,
|
|
345
|
+
artifacts: "unknown",
|
|
346
|
+
},
|
|
347
|
+
};
|
|
348
|
+
}
|
|
349
|
+
async start(caller, input, observationSignal) {
|
|
350
|
+
validateContract("runtime:agent.run.start", input);
|
|
351
|
+
input = JSON.parse(canonicalJson(input));
|
|
352
|
+
caller = fixedCaller(caller);
|
|
353
|
+
this.#authorize(caller, { action: "start" });
|
|
354
|
+
const { waitMs: _wait, attachments: _attachments, ...intent } = input;
|
|
355
|
+
const key = callerKey(caller);
|
|
356
|
+
const intentDigest = digest({
|
|
357
|
+
...intent,
|
|
358
|
+
...(input.attachments === undefined
|
|
359
|
+
? {}
|
|
360
|
+
: { attachments: attachmentIntent(input.attachments) }),
|
|
361
|
+
});
|
|
362
|
+
const original = input.requestId
|
|
363
|
+
? this.store.findMatchingSubmission(key, input.requestId, intentDigest)
|
|
364
|
+
: null;
|
|
365
|
+
if (original) {
|
|
366
|
+
this.#authorize(caller, { action: "get", run: original });
|
|
367
|
+
return await this.observe(caller, original.runId, input.waitMs ?? 1000, observationSignal);
|
|
368
|
+
}
|
|
369
|
+
let pinned;
|
|
370
|
+
try {
|
|
371
|
+
if (input.scriptName !== undefined)
|
|
372
|
+
pinned = qualifyControlScript(this.scripts, input.scriptName);
|
|
373
|
+
}
|
|
374
|
+
catch (cause) {
|
|
375
|
+
// A source resolver can call trusted services reentrantly. A submission
|
|
376
|
+
// accepted since the first lookup still owns its original identity.
|
|
377
|
+
const concurrent = input.requestId
|
|
378
|
+
? this.store.findMatchingSubmission(key, input.requestId, intentDigest)
|
|
379
|
+
: null;
|
|
380
|
+
if (!concurrent)
|
|
381
|
+
throw cause;
|
|
382
|
+
this.#authorize(caller, { action: "get", run: concurrent });
|
|
383
|
+
return await this.observe(caller, concurrent.runId, input.waitMs ?? 1000, observationSignal);
|
|
384
|
+
}
|
|
385
|
+
let admission;
|
|
386
|
+
try {
|
|
387
|
+
if (this.#options.reserve)
|
|
388
|
+
admission = await this.#options.reserve(65536, {
|
|
389
|
+
control: pinned !== undefined,
|
|
390
|
+
});
|
|
391
|
+
}
|
|
392
|
+
catch (cause) {
|
|
393
|
+
const concurrent = input.requestId
|
|
394
|
+
? this.store.findMatchingSubmission(key, input.requestId, intentDigest)
|
|
395
|
+
: null;
|
|
396
|
+
if (!concurrent)
|
|
397
|
+
throw cause;
|
|
398
|
+
this.#authorize(caller, { action: "get", run: concurrent });
|
|
399
|
+
return await this.observe(caller, concurrent.runId, input.waitMs ?? 1000, observationSignal);
|
|
400
|
+
}
|
|
401
|
+
let accepted;
|
|
402
|
+
try {
|
|
403
|
+
this.#authorize(caller, { action: "start" });
|
|
404
|
+
accepted = this.store.acceptRun({
|
|
405
|
+
callerKey: key,
|
|
406
|
+
contextId: input.contextId,
|
|
407
|
+
sourceKind: input.script !== undefined
|
|
408
|
+
? "inline"
|
|
409
|
+
: input.scriptName !== undefined
|
|
410
|
+
? "script"
|
|
411
|
+
: "replay",
|
|
412
|
+
source: {
|
|
413
|
+
entry: input.script !== undefined
|
|
414
|
+
? "inline"
|
|
415
|
+
: input.scriptName !== undefined
|
|
416
|
+
? "named"
|
|
417
|
+
: "history",
|
|
418
|
+
...(input.replayRunId ? { replayRunId: input.replayRunId } : {}),
|
|
419
|
+
},
|
|
420
|
+
...(input.scriptName === undefined
|
|
421
|
+
? {}
|
|
422
|
+
: { scriptName: input.scriptName }),
|
|
423
|
+
timeoutMs: input.timeoutMs,
|
|
424
|
+
requestId: input.requestId,
|
|
425
|
+
intentDigest,
|
|
426
|
+
capacity: this.#options.capacity,
|
|
427
|
+
controlCapacity: this.#options.controlCapacity,
|
|
428
|
+
controlEligible: pinned !== undefined,
|
|
429
|
+
});
|
|
430
|
+
}
|
|
431
|
+
finally {
|
|
432
|
+
admission?.release();
|
|
433
|
+
}
|
|
434
|
+
if (accepted.duplicate)
|
|
435
|
+
this.#authorize(caller, { action: "get", run: accepted.run });
|
|
436
|
+
else {
|
|
437
|
+
const scope = this.#scope(accepted.run, caller, pinned !== undefined);
|
|
438
|
+
this.#scopes.set(scope.runId, scope);
|
|
439
|
+
this.#scheduleDeadline(scope);
|
|
440
|
+
const begin = () => {
|
|
441
|
+
void this.#drive(scope, input, pinned)
|
|
442
|
+
.finally(async () => {
|
|
443
|
+
await scope.log?.finish();
|
|
444
|
+
})
|
|
445
|
+
.catch((error) => this.#persistenceFailure(scope, error));
|
|
446
|
+
};
|
|
447
|
+
// Fixed code already has a known source. Acquire its lease before the
|
|
448
|
+
// caller can synchronously stop/replace that source after start returns.
|
|
449
|
+
if (pinned)
|
|
450
|
+
begin();
|
|
451
|
+
else
|
|
452
|
+
queueMicrotask(begin);
|
|
453
|
+
}
|
|
454
|
+
return await this.observe(caller, accepted.run.runId, input.waitMs ?? 1000, observationSignal);
|
|
455
|
+
}
|
|
456
|
+
#scope(run, caller, controlEligible = false) {
|
|
457
|
+
const scope = {
|
|
458
|
+
runId: run.runId,
|
|
459
|
+
caller: fixedCaller(caller),
|
|
460
|
+
controlEligible,
|
|
461
|
+
work: this.store.getWork(run.contextId),
|
|
462
|
+
controller: new AbortController(),
|
|
463
|
+
acceptedMono: performance.now(),
|
|
464
|
+
acceptedAt: run.acceptedAt,
|
|
465
|
+
duration: run.deadlineAt - run.acceptedAt,
|
|
466
|
+
context: {},
|
|
467
|
+
accepting: true,
|
|
468
|
+
pending: null,
|
|
469
|
+
deliveries: new Set(),
|
|
470
|
+
};
|
|
471
|
+
scope.operations = new RunOperations(this.store, run.runId, () => this.#assertCurrent(scope), (error) => this.#persistenceFailure(scope, error), () => this.#publish(run.runId));
|
|
472
|
+
scope.services = Object.freeze({
|
|
473
|
+
runId: run.runId,
|
|
474
|
+
controlStorage: scope.controlEligible,
|
|
475
|
+
signal: scope.controller.signal,
|
|
476
|
+
deadlineAt: run.deadlineAt,
|
|
477
|
+
get context() {
|
|
478
|
+
return scope.context;
|
|
479
|
+
},
|
|
480
|
+
assertActive: () => this.#assertActive(scope),
|
|
481
|
+
assertCurrent: () => this.#assertCurrent(scope),
|
|
482
|
+
operation: (origin, method, action, hooks) => scope.operations.start(origin, method, action, hooks),
|
|
483
|
+
requestInput: (request) => this.#requestInput(scope, request),
|
|
484
|
+
});
|
|
485
|
+
return scope;
|
|
486
|
+
}
|
|
487
|
+
#remaining(scope) {
|
|
488
|
+
return Math.min(scope.duration - (performance.now() - scope.acceptedMono), scope.acceptedAt + scope.duration - Date.now());
|
|
489
|
+
}
|
|
490
|
+
#now(scope) {
|
|
491
|
+
return Math.floor(Math.max(Date.now(), scope.acceptedAt + performance.now() - scope.acceptedMono));
|
|
492
|
+
}
|
|
493
|
+
#checkDeadline(scope) {
|
|
494
|
+
if (scope &&
|
|
495
|
+
!scope.controller.signal.aborted &&
|
|
496
|
+
this.#remaining(scope) <= 0)
|
|
497
|
+
this.#stop(scope, { kind: "deadline", code: "run_deadline_exceeded" });
|
|
498
|
+
if (scope?.pending &&
|
|
499
|
+
this.#now(scope) >= scope.pending.record.deadlineAt &&
|
|
500
|
+
!scope.controller.signal.aborted)
|
|
501
|
+
this.#expireInput(scope, scope.pending.record.waitId);
|
|
502
|
+
}
|
|
503
|
+
#scheduleDeadline(scope) {
|
|
504
|
+
scope.timer = setTimeout(() => {
|
|
505
|
+
try {
|
|
506
|
+
this.#checkDeadline(scope);
|
|
507
|
+
if (!scope.controller.signal.aborted)
|
|
508
|
+
this.#scheduleDeadline(scope);
|
|
509
|
+
}
|
|
510
|
+
catch (error) {
|
|
511
|
+
this.#persistenceFailure(scope, error);
|
|
512
|
+
}
|
|
513
|
+
}, Math.max(1, Math.min(this.#remaining(scope), 2_147_483_647)));
|
|
514
|
+
scope.timer.unref();
|
|
515
|
+
}
|
|
516
|
+
#persistenceFailure(scope, error) {
|
|
517
|
+
scope.fatal ??= new AgentError("run_persistence_failed", "The run could not confirm its saved state; do not replay it automatically.", { runId: scope.runId }, { cause: error });
|
|
518
|
+
scope.accepting = false;
|
|
519
|
+
clearTimeout(scope.timer);
|
|
520
|
+
if (scope.pending) {
|
|
521
|
+
const pending = scope.pending;
|
|
522
|
+
scope.pending = null;
|
|
523
|
+
clearTimeout(pending.timer);
|
|
524
|
+
pending.reject(scope.fatal);
|
|
525
|
+
}
|
|
526
|
+
scope.controller.abort(scope.fatal);
|
|
527
|
+
this.#publish(scope.runId);
|
|
528
|
+
}
|
|
529
|
+
#assertActive(scope) {
|
|
530
|
+
requireCondition(scope.accepting && !scope.controller.signal.aborted, "run_stopping", "The run no longer accepts new managed work.");
|
|
531
|
+
this.#assertCurrent(scope);
|
|
532
|
+
}
|
|
533
|
+
#assertCurrent(scope) {
|
|
534
|
+
this.#checkDeadline(scope);
|
|
535
|
+
scope.controller.signal.throwIfAborted();
|
|
536
|
+
const run = this.store.getRun(scope.runId);
|
|
537
|
+
requireCondition(run.bootId === this.store.bootId &&
|
|
538
|
+
run.endedAt === null &&
|
|
539
|
+
run.stop === null, "run_stopping", "The originating run no longer admits operation continuations.");
|
|
540
|
+
this.#authorize(scope.caller, {
|
|
541
|
+
action: "operation",
|
|
542
|
+
run,
|
|
543
|
+
});
|
|
544
|
+
}
|
|
545
|
+
#stop(scope, reason) {
|
|
546
|
+
const stopped = this.store.requestStop(scope.runId, reason, this.#now(scope));
|
|
547
|
+
if (stopped.accepted) {
|
|
548
|
+
scope.accepting = false;
|
|
549
|
+
clearTimeout(scope.timer);
|
|
550
|
+
scope.controller.abort(new AgentError(reason.kind === "cancel"
|
|
551
|
+
? "run_cancelled"
|
|
552
|
+
: reason.kind === "authorization"
|
|
553
|
+
? String(reason.code)
|
|
554
|
+
: "run_deadline_exceeded", "The run accepted a stop request."));
|
|
555
|
+
if (scope.pending) {
|
|
556
|
+
const pending = scope.pending;
|
|
557
|
+
scope.pending = null;
|
|
558
|
+
clearTimeout(pending.timer);
|
|
559
|
+
pending.reject(scope.controller.signal.reason);
|
|
560
|
+
}
|
|
561
|
+
this.#publish(scope.runId);
|
|
562
|
+
}
|
|
563
|
+
return stopped;
|
|
564
|
+
}
|
|
565
|
+
async #drive(scope, input, pinned) {
|
|
566
|
+
let phase = "prepare", directory = "";
|
|
567
|
+
let result, error;
|
|
568
|
+
let resultRef;
|
|
569
|
+
let releaseScript;
|
|
570
|
+
const moduleUses = new Map();
|
|
571
|
+
let modulesIncomplete = false;
|
|
572
|
+
try {
|
|
573
|
+
this.#assertActive(scope);
|
|
574
|
+
let run = this.store.getRun(scope.runId);
|
|
575
|
+
if (pinned) {
|
|
576
|
+
this.#authorize(scope.caller, {
|
|
577
|
+
action: "script",
|
|
578
|
+
run,
|
|
579
|
+
origin: pinned.origin,
|
|
580
|
+
});
|
|
581
|
+
this.#assertActive(scope);
|
|
582
|
+
releaseScript = this.#options.leaseScript?.(pinned.origin);
|
|
583
|
+
}
|
|
584
|
+
run = this.store.transitionRun(run.runId, run.revision, "preparing_inputs", {}, this.#now(scope));
|
|
585
|
+
this.#publish(run.runId);
|
|
586
|
+
directory = this.#directory(run.runId);
|
|
587
|
+
const work = await this.#options.loadWork(scope.work);
|
|
588
|
+
const pwd = realpathSync.native(input.pwd ?? scope.work.pwd);
|
|
589
|
+
requireCondition(statSync(pwd).isDirectory(), "invalid_pwd", "The requested working directory is not a directory.");
|
|
590
|
+
this.#authorize(scope.caller, {
|
|
591
|
+
action: "prepare",
|
|
592
|
+
work: scope.work,
|
|
593
|
+
path: pwd,
|
|
594
|
+
});
|
|
595
|
+
let snapshot, businessInput = null;
|
|
596
|
+
let attachments = input.attachments;
|
|
597
|
+
if (input.script !== undefined)
|
|
598
|
+
snapshot = (await this.scripts.enrollManaged(input.script, {
|
|
599
|
+
reserve: this.#options.reserve
|
|
600
|
+
? (bytes) => this.#options.reserve(bytes, {
|
|
601
|
+
control: scope.controlEligible,
|
|
602
|
+
})
|
|
603
|
+
: undefined,
|
|
604
|
+
assertCurrent: () => this.#assertActive(scope),
|
|
605
|
+
})).snapshot;
|
|
606
|
+
else if (input.scriptName !== undefined)
|
|
607
|
+
snapshot = pinned ?? this.scripts.resolve(input.scriptName);
|
|
608
|
+
else {
|
|
609
|
+
const previous = this.#run(scope.caller, input.replayRunId, "replay");
|
|
610
|
+
const saved = JSON.parse(this.#read(previous.inputRef, previous.runId));
|
|
611
|
+
snapshot = JSON.parse(this.#read(previous.codeRef, previous.runId));
|
|
612
|
+
requireCondition(typeof snapshot.code === "string" &&
|
|
613
|
+
createHash("sha256").update(snapshot.code).digest("hex") ===
|
|
614
|
+
previous.source.revision, "snapshot_changed", "The retained code no longer matches the recorded revision.");
|
|
615
|
+
snapshot.origin = previous.source.origin;
|
|
616
|
+
snapshot.name = previous.scriptName;
|
|
617
|
+
snapshot.metadata = scriptHeader(snapshot.code);
|
|
618
|
+
if (attachments === undefined)
|
|
619
|
+
requireCondition(saved.attachmentsReady !== false || saved.expectedAttachments === 0, "attachments_unavailable", "Historical required attachments were never fully prepared; supply replacements.");
|
|
620
|
+
if (attachments === undefined &&
|
|
621
|
+
Array.isArray(saved.attachments) &&
|
|
622
|
+
saved.attachments.length) {
|
|
623
|
+
// Only local retained references are reused; Host URL/file IDs were never saved.
|
|
624
|
+
attachments = saved.attachments.map((item) => ({
|
|
625
|
+
uri: item.resourceUri,
|
|
626
|
+
}));
|
|
627
|
+
requireCondition(attachments.every((item) => typeof item.uri === "string"), "attachments_unavailable", "The historical attachments have no reusable authorized resource references.");
|
|
628
|
+
}
|
|
629
|
+
if (!Object.hasOwn(input, "input"))
|
|
630
|
+
businessInput = saved.input;
|
|
631
|
+
}
|
|
632
|
+
businessInput = Object.hasOwn(input, "input")
|
|
633
|
+
? input.input
|
|
634
|
+
: (businessInput ?? null);
|
|
635
|
+
this.#authorize(scope.caller, {
|
|
636
|
+
action: "script",
|
|
637
|
+
run: this.store.getRun(scope.runId),
|
|
638
|
+
origin: snapshot.origin,
|
|
639
|
+
});
|
|
640
|
+
this.#assertActive(scope);
|
|
641
|
+
if (!pinned)
|
|
642
|
+
releaseScript = this.#options.leaseScript?.(snapshot.origin);
|
|
643
|
+
const codeRef = this.#relative(path.join(directory, "code.json"));
|
|
644
|
+
const inputRef = this.#relative(path.join(directory, "input.json"));
|
|
645
|
+
await this.#writeSnapshot(scope, path.join(directory, "code.json"), canonicalJson(snapshot));
|
|
646
|
+
await this.#writeSnapshot(scope, path.join(directory, "input.json"), canonicalJson({
|
|
647
|
+
input: businessInput,
|
|
648
|
+
attachments: [],
|
|
649
|
+
expectedAttachments: (attachments ?? []).length,
|
|
650
|
+
attachmentsReady: false,
|
|
651
|
+
}));
|
|
652
|
+
run = this.store.getRun(scope.runId);
|
|
653
|
+
const source = {
|
|
654
|
+
origin: snapshot.origin,
|
|
655
|
+
revision: snapshot.origin.revision,
|
|
656
|
+
nodeVersion: process.version,
|
|
657
|
+
workRevision: scope.work.revision,
|
|
658
|
+
...(snapshot.metadata
|
|
659
|
+
? { scriptDesc: snapshot.metadata.scriptDesc }
|
|
660
|
+
: {}),
|
|
661
|
+
...(input.replayRunId ? { replayRunId: input.replayRunId } : {}),
|
|
662
|
+
};
|
|
663
|
+
run = this.store.savePreparation(run.runId, run.revision, {
|
|
664
|
+
codeRef,
|
|
665
|
+
inputRef,
|
|
666
|
+
source,
|
|
667
|
+
...(snapshot.name ? { scriptName: snapshot.name } : {}),
|
|
668
|
+
});
|
|
669
|
+
if (snapshot.metadata)
|
|
670
|
+
compileInputSchema(snapshot.metadata.scriptInputSchema)(businessInput);
|
|
671
|
+
const paths = {
|
|
672
|
+
work: this.scripts.work,
|
|
673
|
+
docs: this.scripts.docs,
|
|
674
|
+
scripts: this.scripts.local,
|
|
675
|
+
resources: path.join(this.scripts.work, "resources"),
|
|
676
|
+
temp: directory,
|
|
677
|
+
};
|
|
678
|
+
scope.context = {
|
|
679
|
+
contextId: run.contextId,
|
|
680
|
+
agentId: this.store.binding.agentId,
|
|
681
|
+
runId: run.runId,
|
|
682
|
+
pwd,
|
|
683
|
+
project: work.project ?? null,
|
|
684
|
+
caller: { ...scope.caller },
|
|
685
|
+
script: {
|
|
686
|
+
name: snapshot.name,
|
|
687
|
+
source: input.script !== undefined
|
|
688
|
+
? "inline"
|
|
689
|
+
: input.scriptName !== undefined
|
|
690
|
+
? "named"
|
|
691
|
+
: "history",
|
|
692
|
+
origin: snapshot.origin,
|
|
693
|
+
code: snapshot.code,
|
|
694
|
+
},
|
|
695
|
+
paths,
|
|
696
|
+
input: businessInput,
|
|
697
|
+
attachments: [],
|
|
698
|
+
agent: work.agentShared ?? {},
|
|
699
|
+
user: work.userShared ?? {},
|
|
700
|
+
};
|
|
701
|
+
const prepared = await this.#prepareAttachments(attachments ?? [], privateDirectory(directory, "inputs"), scope);
|
|
702
|
+
this.#assertActive(scope);
|
|
703
|
+
scope.context.attachments = prepared;
|
|
704
|
+
scope.context = frozenJson(scope.context);
|
|
705
|
+
// The context is copied/frozen by ModuleLoader; later input never mutates it.
|
|
706
|
+
await this.#writeSnapshot(scope, path.join(directory, "input.json"), canonicalJson({
|
|
707
|
+
input: businessInput,
|
|
708
|
+
attachments: prepared,
|
|
709
|
+
attachmentsReady: true,
|
|
710
|
+
}, 2 * 1024 * 1024));
|
|
711
|
+
scope.log = new RunLog(this.store.root, run.runId, this.#options.reserve
|
|
712
|
+
? (bytes) => this.#options.reserve(bytes, { control: scope.controlEligible })
|
|
713
|
+
: undefined);
|
|
714
|
+
await scope.log.open();
|
|
715
|
+
this.#assertActive(scope);
|
|
716
|
+
const logsFile = scope.log.filename;
|
|
717
|
+
// Console inspects guest objects only when the script explicitly chooses to log them.
|
|
718
|
+
const runConsole = new Console({
|
|
719
|
+
stdout: scope.log,
|
|
720
|
+
stderr: scope.log,
|
|
721
|
+
ignoreErrors: false,
|
|
722
|
+
});
|
|
723
|
+
phase = "compile";
|
|
724
|
+
await scope.operations.settle();
|
|
725
|
+
const execute = this.loader.compile(snapshot.code, { ...this.#options.bindings(scope.services), context: scope.context }, {
|
|
726
|
+
filename: `nexum:${snapshot.name ?? run.runId + ".js"}`,
|
|
727
|
+
console: runConsole,
|
|
728
|
+
onModule: (use) => {
|
|
729
|
+
if (moduleUses.size < 256 || moduleUses.has(use.entry))
|
|
730
|
+
moduleUses.set(use.entry, use);
|
|
731
|
+
else
|
|
732
|
+
modulesIncomplete = true;
|
|
733
|
+
},
|
|
734
|
+
});
|
|
735
|
+
this.#assertActive(scope);
|
|
736
|
+
run = this.store.getRun(run.runId);
|
|
737
|
+
this.store.transitionRun(run.runId, run.revision, "running", {
|
|
738
|
+
codeRef,
|
|
739
|
+
inputRef,
|
|
740
|
+
logsRef: this.#relative(logsFile),
|
|
741
|
+
source,
|
|
742
|
+
...(snapshot.name ? { scriptName: snapshot.name } : {}),
|
|
743
|
+
}, this.#now(scope));
|
|
744
|
+
this.#publish(run.runId);
|
|
745
|
+
phase = "execute";
|
|
746
|
+
const value = await scope.operations.audit.run(execute);
|
|
747
|
+
if (scope.log?.failure)
|
|
748
|
+
throw new AgentError("run_log_failed", "The local run log could not be saved.");
|
|
749
|
+
scope.accepting = false;
|
|
750
|
+
if (scope.pending || scope.inputPreparation) {
|
|
751
|
+
const pending = scope.pending;
|
|
752
|
+
scope.pending = null;
|
|
753
|
+
if (pending) {
|
|
754
|
+
clearTimeout(pending.timer);
|
|
755
|
+
pending.reject(new AgentError("input_not_awaited", "The root script returned without awaiting its input request."));
|
|
756
|
+
}
|
|
757
|
+
throw new AgentError("input_not_awaited", "The root script returned without awaiting its input request.");
|
|
758
|
+
}
|
|
759
|
+
phase = "operations";
|
|
760
|
+
await scope.operations.settle();
|
|
761
|
+
if (scope.log?.failure)
|
|
762
|
+
throw new AgentError("run_log_failed", "The local run log could not be saved.");
|
|
763
|
+
this.#checkDeadline(scope);
|
|
764
|
+
scope.controller.signal.throwIfAborted();
|
|
765
|
+
phase = "result";
|
|
766
|
+
result = await this.#options.encodeResult(value, scope.services);
|
|
767
|
+
this.#checkDeadline(scope);
|
|
768
|
+
scope.controller.signal.throwIfAborted();
|
|
769
|
+
await this.#writeSnapshot(scope, path.join(directory, "result.json"), canonicalJson(result, 96 * 1024 * 1024));
|
|
770
|
+
resultRef = this.#relative(path.join(directory, "result.json"));
|
|
771
|
+
}
|
|
772
|
+
catch (cause) {
|
|
773
|
+
error = failure(cause, phase);
|
|
774
|
+
}
|
|
775
|
+
scope.accepting = false;
|
|
776
|
+
if (scope.pending) {
|
|
777
|
+
const pending = scope.pending;
|
|
778
|
+
scope.pending = null;
|
|
779
|
+
clearTimeout(pending.timer);
|
|
780
|
+
pending.reject(new AgentError("run_closed", "The root execution is closing."));
|
|
781
|
+
}
|
|
782
|
+
if (error && !scope.controller.signal.aborted)
|
|
783
|
+
scope.controller.abort(new AgentError("run_failed", "The root or its managed work failed; in-flight operations must stop."));
|
|
784
|
+
try {
|
|
785
|
+
await scope.operations.settle();
|
|
786
|
+
}
|
|
787
|
+
catch (cause) {
|
|
788
|
+
error ??= failure(cause, "operations");
|
|
789
|
+
}
|
|
790
|
+
await Promise.allSettled([...scope.deliveries]);
|
|
791
|
+
let cleanup = {};
|
|
792
|
+
if (this.#options.resources) {
|
|
793
|
+
if (error && !scope.controller.signal.aborted)
|
|
794
|
+
scope.controller.abort(new AgentError("run_failed", "The root execution failed; managed work must stop."));
|
|
795
|
+
const resources = this.#options.resources;
|
|
796
|
+
let report = await resources.cleanupRun(scope.runId, scope.controller.signal.reason);
|
|
797
|
+
if (report.unconfirmed.length) {
|
|
798
|
+
this.store.saveCleanup(scope.runId, { phase: "cleanup", ...report, ...(error ? { cause: error } : {}) }, this.#now(scope));
|
|
799
|
+
this.#publish(scope.runId);
|
|
800
|
+
// A bounded cleanup attempt is over; physical closure remains unconfirmed.
|
|
801
|
+
// Wait on actual resource evidence without polling or manufacturing a terminal state.
|
|
802
|
+
await resources.waitForRunClosure(scope.runId);
|
|
803
|
+
report = await resources.cleanupRun(scope.runId, scope.controller.signal.reason);
|
|
804
|
+
}
|
|
805
|
+
cleanup = report;
|
|
806
|
+
}
|
|
807
|
+
if (scope.fatal) {
|
|
808
|
+
scope.operations.audit.close();
|
|
809
|
+
return;
|
|
810
|
+
}
|
|
811
|
+
try {
|
|
812
|
+
await scope.operations.settle();
|
|
813
|
+
}
|
|
814
|
+
catch (cause) {
|
|
815
|
+
error ??= failure(cause, "cleanup");
|
|
816
|
+
}
|
|
817
|
+
if (scope.fatal) {
|
|
818
|
+
scope.operations.audit.close();
|
|
819
|
+
return;
|
|
820
|
+
}
|
|
821
|
+
await scope.log?.finish();
|
|
822
|
+
if (scope.log?.failure)
|
|
823
|
+
error ??= failure(new AgentError("run_log_failed", "The local run log could not be saved."), "cleanup");
|
|
824
|
+
this.#checkDeadline(scope);
|
|
825
|
+
const run = this.store.getRun(scope.runId);
|
|
826
|
+
const status = run.stop
|
|
827
|
+
? run.stop.kind === "cancel"
|
|
828
|
+
? "cancelled"
|
|
829
|
+
: "failed"
|
|
830
|
+
: error
|
|
831
|
+
? "failed"
|
|
832
|
+
: "succeeded";
|
|
833
|
+
releaseScript?.();
|
|
834
|
+
releaseScript = undefined;
|
|
835
|
+
this.store.transitionRun(run.runId, run.revision, status, {
|
|
836
|
+
...(error ? { error } : {}),
|
|
837
|
+
...(resultRef ? { resultRef } : {}),
|
|
838
|
+
cleanup,
|
|
839
|
+
source: {
|
|
840
|
+
...run.source,
|
|
841
|
+
modules: [...moduleUses.values()].map((use) => ({ ...use })),
|
|
842
|
+
modulesIncomplete,
|
|
843
|
+
},
|
|
844
|
+
}, this.#now(scope));
|
|
845
|
+
clearTimeout(scope.timer);
|
|
846
|
+
scope.operations.audit.close();
|
|
847
|
+
this.#scopes.delete(scope.runId);
|
|
848
|
+
this.#publish(scope.runId);
|
|
849
|
+
}
|
|
850
|
+
async #writeSnapshot(scope, filename, text) {
|
|
851
|
+
const ticket = await this.#options.reserve?.(Buffer.byteLength(text) + 1024, { control: scope.controlEligible });
|
|
852
|
+
try {
|
|
853
|
+
this.#assertCurrent(scope);
|
|
854
|
+
atomicText(filename, text);
|
|
855
|
+
}
|
|
856
|
+
finally {
|
|
857
|
+
ticket?.release();
|
|
858
|
+
}
|
|
859
|
+
}
|
|
860
|
+
async #prepareAttachments(references, directory, scope) {
|
|
861
|
+
if (!references.length)
|
|
862
|
+
return [];
|
|
863
|
+
requireCondition(this.#options.prepareAttachments, "attachments_unavailable", "The attachment data-plane service is unavailable.");
|
|
864
|
+
return await this.#options.prepareAttachments(references, directory, scope.services);
|
|
865
|
+
}
|
|
866
|
+
#requestInput(scope, request) {
|
|
867
|
+
if (!this.#options.reserve)
|
|
868
|
+
return this.#openInput(scope, request);
|
|
869
|
+
this.#assertActive(scope);
|
|
870
|
+
requireCondition(!scope.pending && !scope.inputPreparation, "input_busy", "This run already has an input request being prepared or awaiting a response.");
|
|
871
|
+
const fixed = JSON.parse(canonicalJson(request));
|
|
872
|
+
const response = Promise.withResolvers();
|
|
873
|
+
void response.promise.catch(() => { });
|
|
874
|
+
const prepare = (async () => {
|
|
875
|
+
const ticket = await this.#options.reserve(Buffer.byteLength(canonicalJson(fixed)) + 65536, { control: scope.controlEligible });
|
|
876
|
+
try {
|
|
877
|
+
this.#assertActive(scope);
|
|
878
|
+
this.#openInput(scope, fixed).then(response.resolve, response.reject);
|
|
879
|
+
}
|
|
880
|
+
finally {
|
|
881
|
+
ticket.release();
|
|
882
|
+
}
|
|
883
|
+
})();
|
|
884
|
+
scope.inputPreparation = prepare;
|
|
885
|
+
scope.deliveries.add(prepare);
|
|
886
|
+
const settled = () => {
|
|
887
|
+
if (scope.inputPreparation === prepare)
|
|
888
|
+
scope.inputPreparation = undefined;
|
|
889
|
+
scope.deliveries.delete(prepare);
|
|
890
|
+
};
|
|
891
|
+
void prepare.then(settled, (cause) => {
|
|
892
|
+
settled();
|
|
893
|
+
response.reject(cause);
|
|
894
|
+
});
|
|
895
|
+
return response.promise;
|
|
896
|
+
}
|
|
897
|
+
#openInput(scope, request) {
|
|
898
|
+
this.#assertActive(scope);
|
|
899
|
+
request = JSON.parse(canonicalJson(request));
|
|
900
|
+
requireCondition(typeof request.message === "string" && request.message.trim().length > 0, "invalid_wait", "An input request needs a message.");
|
|
901
|
+
compileInputSchema(request.inputSchema);
|
|
902
|
+
requireCondition(request.timeoutMs === undefined ||
|
|
903
|
+
(Number.isSafeInteger(request.timeoutMs) && request.timeoutMs > 0), "invalid_wait", "The input timeout must be positive.");
|
|
904
|
+
const run = this.store.getRun(scope.runId);
|
|
905
|
+
const deadline = Math.floor(Math.min(run.deadlineAt, this.#now(scope) + (request.timeoutMs ?? this.#remaining(scope))));
|
|
906
|
+
const record = this.store.createWait(scope.runId, { message: request.message, inputSchema: request.inputSchema }, deadline, this.#now(scope));
|
|
907
|
+
const deferred = Promise.withResolvers();
|
|
908
|
+
// Internal lifecycle rejection is observed even if the guest abandons this wait.
|
|
909
|
+
void deferred.promise.catch(() => { });
|
|
910
|
+
const timer = setTimeout(() => {
|
|
911
|
+
try {
|
|
912
|
+
this.#expireInput(scope, record.waitId);
|
|
913
|
+
}
|
|
914
|
+
catch (error) {
|
|
915
|
+
this.#persistenceFailure(scope, error);
|
|
916
|
+
}
|
|
917
|
+
}, Math.min(Math.max(1, deadline - this.#now(scope)), 2_147_483_647));
|
|
918
|
+
timer.unref();
|
|
919
|
+
scope.pending = {
|
|
920
|
+
record,
|
|
921
|
+
resolve: deferred.resolve,
|
|
922
|
+
reject: deferred.reject,
|
|
923
|
+
timer,
|
|
924
|
+
};
|
|
925
|
+
this.#publish(scope.runId);
|
|
926
|
+
return deferred.promise;
|
|
927
|
+
}
|
|
928
|
+
#expireInput(scope, waitId) {
|
|
929
|
+
if (scope.pending?.record.waitId !== waitId)
|
|
930
|
+
return;
|
|
931
|
+
const run = this.store.getRun(scope.runId);
|
|
932
|
+
if (this.#remaining(scope) <= 0 || Date.now() >= run.deadlineAt) {
|
|
933
|
+
this.#stop(scope, { kind: "deadline", code: "run_deadline_exceeded" });
|
|
934
|
+
return;
|
|
935
|
+
}
|
|
936
|
+
const pending = scope.pending;
|
|
937
|
+
if (this.#now(scope) < pending.record.deadlineAt) {
|
|
938
|
+
pending.timer = setTimeout(() => {
|
|
939
|
+
try {
|
|
940
|
+
this.#expireInput(scope, waitId);
|
|
941
|
+
}
|
|
942
|
+
catch (error) {
|
|
943
|
+
this.#persistenceFailure(scope, error);
|
|
944
|
+
}
|
|
945
|
+
}, Math.min(pending.record.deadlineAt - this.#now(scope), 2_147_483_647));
|
|
946
|
+
pending.timer.unref();
|
|
947
|
+
return;
|
|
948
|
+
}
|
|
949
|
+
this.store.expireWait(waitId, this.#now(scope));
|
|
950
|
+
scope.pending = null;
|
|
951
|
+
clearTimeout(pending.timer);
|
|
952
|
+
const error = new AgentError("input_timeout", "The local input wait expired.");
|
|
953
|
+
error.name = "InputTimeoutError";
|
|
954
|
+
pending.reject(error);
|
|
955
|
+
this.#publish(scope.runId);
|
|
956
|
+
}
|
|
957
|
+
async input(caller, input, signal) {
|
|
958
|
+
validateContract("runtime:agent.run.input", input);
|
|
959
|
+
input = JSON.parse(canonicalJson(input));
|
|
960
|
+
requireCondition(input.agentId === this.store.binding.agentId, "agent_mismatch", "The input targets a different Agent.");
|
|
961
|
+
this.#run(caller, input.runId, "input");
|
|
962
|
+
const intent = digest({
|
|
963
|
+
input: input.input,
|
|
964
|
+
...(input.attachments === undefined
|
|
965
|
+
? {}
|
|
966
|
+
: { attachments: attachmentIntent(input.attachments) }),
|
|
967
|
+
});
|
|
968
|
+
const previous = this.store.getWait(input.waitId);
|
|
969
|
+
const duplicate = previous.runId === input.runId &&
|
|
970
|
+
previous.inputDigest === intent &&
|
|
971
|
+
(previous.status === "consumed" ||
|
|
972
|
+
previous.deliveryState === "preparing");
|
|
973
|
+
const ticket = duplicate
|
|
974
|
+
? undefined
|
|
975
|
+
: await this.#options.reserve?.(65536, {
|
|
976
|
+
control: this.#scopes.get(input.runId)?.controlEligible === true,
|
|
977
|
+
});
|
|
978
|
+
let reservation;
|
|
979
|
+
try {
|
|
980
|
+
this.#run(caller, input.runId, "input");
|
|
981
|
+
reservation = this.store.reserveInput(input.runId, input.waitId, intent);
|
|
982
|
+
}
|
|
983
|
+
finally {
|
|
984
|
+
ticket?.release();
|
|
985
|
+
}
|
|
986
|
+
if (!reservation.duplicate) {
|
|
987
|
+
const scope = this.#scopes.get(input.runId);
|
|
988
|
+
requireCondition(scope && scope.pending?.record.waitId === input.waitId, "input_closed", "The live input continuation is unavailable.");
|
|
989
|
+
const delivery = this.#deliverInput(scope, input, reservation.wait, intent, fixedCaller(caller));
|
|
990
|
+
scope.deliveries.add(delivery);
|
|
991
|
+
this.#inputDeliveries.set(input.waitId, delivery);
|
|
992
|
+
void delivery
|
|
993
|
+
.finally(() => {
|
|
994
|
+
scope.deliveries.delete(delivery);
|
|
995
|
+
if (this.#inputDeliveries.get(input.waitId) === delivery)
|
|
996
|
+
this.#inputDeliveries.delete(input.waitId);
|
|
997
|
+
})
|
|
998
|
+
.catch(() => { });
|
|
999
|
+
}
|
|
1000
|
+
const delivery = this.#inputDeliveries.get(input.waitId);
|
|
1001
|
+
// Delivery is independent of the observation. Do not wait for it unboundedly.
|
|
1002
|
+
void delivery?.catch(() => { });
|
|
1003
|
+
const result = await this.observe(caller, input.runId, input.waitMs ?? 1000, signal, true);
|
|
1004
|
+
return { ...result, submission: this.store.getWait(input.waitId) };
|
|
1005
|
+
}
|
|
1006
|
+
async #deliverInput(scope, input, wait, intent, controller) {
|
|
1007
|
+
try {
|
|
1008
|
+
compileInputSchema(wait.request.inputSchema)(input.input);
|
|
1009
|
+
const directory = privateDirectory(this.#directory(scope.runId), "inputs", input.waitId);
|
|
1010
|
+
const prepared = await this.#prepareAttachments(input.attachments ?? [], directory, scope);
|
|
1011
|
+
this.#checkDeadline(scope);
|
|
1012
|
+
scope.controller.signal.throwIfAborted();
|
|
1013
|
+
const filename = path.join(directory, "input.json");
|
|
1014
|
+
const reply = JSON.parse(canonicalJson({ input: input.input, attachments: prepared }, 2 * 1024 * 1024));
|
|
1015
|
+
await this.#writeSnapshot(scope, filename, canonicalJson(reply, 2 * 1024 * 1024));
|
|
1016
|
+
this.#run(controller, scope.runId, "input");
|
|
1017
|
+
this.store.consumeInput(scope.runId, input.waitId, intent, wait.revision, this.#relative(filename), { accepted: true, waitId: input.waitId, controller: { ...controller } }, this.#now(scope));
|
|
1018
|
+
const pending = scope.pending;
|
|
1019
|
+
requireCondition(pending?.record.waitId === input.waitId, "input_closed", "The live continuation is no longer current.");
|
|
1020
|
+
scope.pending = null;
|
|
1021
|
+
clearTimeout(pending.timer);
|
|
1022
|
+
pending.resolve(reply);
|
|
1023
|
+
this.#publish(scope.runId);
|
|
1024
|
+
}
|
|
1025
|
+
catch (error) {
|
|
1026
|
+
const current = this.store.getWait(input.waitId);
|
|
1027
|
+
if (current.status === "waiting" && current.revision === wait.revision)
|
|
1028
|
+
this.store.failInput(input.waitId, wait.revision, failure(error, "input"));
|
|
1029
|
+
this.#publish(scope.runId);
|
|
1030
|
+
}
|
|
1031
|
+
}
|
|
1032
|
+
/** Trusted Core authority revocation, never a script/transport parameter entry. */
|
|
1033
|
+
stopAcceptedRun(runId, reason) {
|
|
1034
|
+
requireCondition(typeof reason.code === "string" &&
|
|
1035
|
+
/^[a-z][a-z0-9_]{0,127}$/.test(reason.code), "invalid_stop_reason", "A Core authority stop needs its fixed failure code.");
|
|
1036
|
+
const run = this.store.getRun(runId);
|
|
1037
|
+
requireCondition(run.bootId === this.store.bootId, "run_boot_mismatch", "Only this boot's actually accepted execution can be stopped.");
|
|
1038
|
+
const scope = this.#scopes.get(runId);
|
|
1039
|
+
return scope && !terminalStatuses.has(run.status)
|
|
1040
|
+
? this.#stop(scope, { kind: "authorization", code: reason.code })
|
|
1041
|
+
: { accepted: false, run };
|
|
1042
|
+
}
|
|
1043
|
+
cancel(caller, runId) {
|
|
1044
|
+
caller = fixedCaller(caller);
|
|
1045
|
+
const run = this.#run(caller, runId, "cancel");
|
|
1046
|
+
const scope = this.#scopes.get(runId);
|
|
1047
|
+
const accepted = scope && !terminalStatuses.has(run.status)
|
|
1048
|
+
? this.#stop(scope, {
|
|
1049
|
+
kind: "cancel",
|
|
1050
|
+
requestedBy: {
|
|
1051
|
+
principalId: caller.principalId,
|
|
1052
|
+
clientId: caller.clientId,
|
|
1053
|
+
},
|
|
1054
|
+
}).accepted
|
|
1055
|
+
: false;
|
|
1056
|
+
return { ...this.#view(caller, runId), accepted };
|
|
1057
|
+
}
|
|
1058
|
+
#view(caller, runId) {
|
|
1059
|
+
const run = this.#run(caller, runId, "get");
|
|
1060
|
+
const fatal = this.#scopes.get(runId)?.fatal;
|
|
1061
|
+
if (fatal)
|
|
1062
|
+
throw fatal;
|
|
1063
|
+
let result = null, unavailable;
|
|
1064
|
+
if (run.resultRef) {
|
|
1065
|
+
try {
|
|
1066
|
+
result = JSON.parse(this.#read(run.resultRef, runId, 96 * 1024 * 1024));
|
|
1067
|
+
}
|
|
1068
|
+
catch {
|
|
1069
|
+
unavailable = {
|
|
1070
|
+
code: "result_unavailable",
|
|
1071
|
+
message: "The retained result is unavailable; the original run state is unchanged.",
|
|
1072
|
+
};
|
|
1073
|
+
}
|
|
1074
|
+
}
|
|
1075
|
+
const operations = this.store.operationsForRun(runId, 65);
|
|
1076
|
+
const resources = this.store.resourcesForRun(runId, 65);
|
|
1077
|
+
let resourceDetailBytes = 0;
|
|
1078
|
+
return {
|
|
1079
|
+
run,
|
|
1080
|
+
wait: this.store.activeWait(runId),
|
|
1081
|
+
result,
|
|
1082
|
+
resources: {
|
|
1083
|
+
items: resources.slice(0, 64).map((resource) => {
|
|
1084
|
+
const details = resource.diagnostic.details ?? {};
|
|
1085
|
+
const bytes = Buffer.byteLength(canonicalJson(details, 16384));
|
|
1086
|
+
const included = bytes <= 4096 && resourceDetailBytes + bytes <= 16384;
|
|
1087
|
+
if (included)
|
|
1088
|
+
resourceDetailBytes += bytes;
|
|
1089
|
+
return {
|
|
1090
|
+
resourceId: resource.resourceId,
|
|
1091
|
+
kind: resource.kind,
|
|
1092
|
+
status: resource.status,
|
|
1093
|
+
lifetime: resource.lifetime,
|
|
1094
|
+
createdAt: resource.createdAt,
|
|
1095
|
+
handedOffAt: resource.handedOffAt,
|
|
1096
|
+
closedAt: resource.closedAt,
|
|
1097
|
+
details: included ? details : {},
|
|
1098
|
+
...(included ? {} : { detailsTruncated: true }),
|
|
1099
|
+
};
|
|
1100
|
+
}),
|
|
1101
|
+
complete: resources.length <= 64,
|
|
1102
|
+
},
|
|
1103
|
+
operations: {
|
|
1104
|
+
items: operations.slice(0, 64).map((operation) => ({
|
|
1105
|
+
operationId: operation.operationId,
|
|
1106
|
+
namespace: operation.namespace,
|
|
1107
|
+
method: operation.method,
|
|
1108
|
+
source: operation.source,
|
|
1109
|
+
status: operation.status,
|
|
1110
|
+
error: operation.error,
|
|
1111
|
+
createdAt: operation.createdAt,
|
|
1112
|
+
endedAt: operation.endedAt,
|
|
1113
|
+
})),
|
|
1114
|
+
complete: operations.length <= 64,
|
|
1115
|
+
},
|
|
1116
|
+
...(unavailable ? { unavailable } : {}),
|
|
1117
|
+
};
|
|
1118
|
+
}
|
|
1119
|
+
async observe(caller, runId, waitMs = 0, signal, afterInput = false) {
|
|
1120
|
+
requireCondition(Number.isInteger(waitMs) && waitMs >= 0 && waitMs <= 30000, "invalid_wait", "Observation waitMs must be between 0 and 30000.");
|
|
1121
|
+
const deadline = performance.now() + waitMs;
|
|
1122
|
+
for (;;) {
|
|
1123
|
+
signal?.throwIfAborted();
|
|
1124
|
+
const controller = new AbortController();
|
|
1125
|
+
const combined = signal
|
|
1126
|
+
? AbortSignal.any([signal, controller.signal])
|
|
1127
|
+
: controller.signal;
|
|
1128
|
+
const event = once(this, runId, { signal: combined });
|
|
1129
|
+
void event.catch(() => { });
|
|
1130
|
+
let view;
|
|
1131
|
+
try {
|
|
1132
|
+
view = this.#view(caller, runId);
|
|
1133
|
+
}
|
|
1134
|
+
catch (error) {
|
|
1135
|
+
controller.abort();
|
|
1136
|
+
throw error;
|
|
1137
|
+
}
|
|
1138
|
+
if (terminalStatuses.has(view.run.status) ||
|
|
1139
|
+
(view.wait &&
|
|
1140
|
+
(!afterInput || view.wait.deliveryState !== "preparing")) ||
|
|
1141
|
+
performance.now() >= deadline) {
|
|
1142
|
+
controller.abort();
|
|
1143
|
+
return view;
|
|
1144
|
+
}
|
|
1145
|
+
const timer = setTimeout(() => controller.abort(), Math.max(1, deadline - performance.now()));
|
|
1146
|
+
try {
|
|
1147
|
+
await event;
|
|
1148
|
+
}
|
|
1149
|
+
catch {
|
|
1150
|
+
signal?.throwIfAborted();
|
|
1151
|
+
}
|
|
1152
|
+
finally {
|
|
1153
|
+
clearTimeout(timer);
|
|
1154
|
+
controller.abort();
|
|
1155
|
+
}
|
|
1156
|
+
}
|
|
1157
|
+
}
|
|
1158
|
+
}
|
|
1159
|
+
//# sourceMappingURL=engine.js.map
|