@agentims/runtime 0.9.4 → 0.9.6
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/dist/cli/update-commands.js +1 -1
- package/dist/configuration/environment.js +3 -0
- package/dist/configuration/execution-artifact.d.ts +19 -0
- package/dist/configuration/execution-artifact.js +51 -0
- package/dist/configuration/native-command.d.ts +2 -0
- package/dist/configuration/native-command.js +4 -0
- package/dist/lifecycle/process.js +2 -1
- package/dist/lifecycle/shutdown-lease.js +2 -1
- package/dist/managed/control.js +3 -3
- package/dist/managed/execution.d.ts +7 -0
- package/dist/managed/execution.js +95 -0
- package/dist/managed/lease.js +2 -1
- package/dist/managed/shutdown.js +2 -2
- package/dist/managed/state.d.ts +2 -0
- package/dist/managed/state.js +11 -19
- package/dist/native/daemon-driver.d.ts +1 -0
- package/dist/native/daemon-driver.js +54 -0
- package/dist/storage/archive.js +2 -1
- package/dist/supervision/launchd.js +3 -2
- package/dist/supervision/service.d.ts +1 -0
- package/dist/supervision/service.js +1 -1
- package/dist/supervision/systemd.js +3 -2
- package/dist/supervision/windows-task.ps1 +5 -4
- package/dist/updates/activation.d.ts +1 -1
- package/dist/updates/activation.js +9 -2
- package/dist/updates/discovery.js +1 -1
- package/dist/updates/installation.js +4 -3
- package/dist/updates/ledger.js +1 -1
- package/dist/updates/managed.js +8 -22
- package/package.json +2 -2
|
@@ -65,7 +65,7 @@ export async function updateCommand(argv) {
|
|
|
65
65
|
onUpdate: notice => { process.stdout.write(stringifyAgentIMJSON(notice) + "\n"); } });
|
|
66
66
|
await watcher.done;
|
|
67
67
|
await watcher.close();
|
|
68
|
-
if (!controller.signal.aborted && await delegateActiveCLI(argv, root))
|
|
68
|
+
if (!controller.signal.aborted && await delegateActiveCLI(argv, root, controller.signal))
|
|
69
69
|
return undefined;
|
|
70
70
|
return { watching: false, communicationPreserved: true };
|
|
71
71
|
}
|
|
@@ -4,6 +4,7 @@ import { access } from "node:fs/promises";
|
|
|
4
4
|
import { constants } from "node:fs";
|
|
5
5
|
import { accountCredential, deviceAuthorization } from "./account-credential.js";
|
|
6
6
|
import { bundledExecutable } from "./executable.js";
|
|
7
|
+
import { executionArtifact } from "./execution-artifact.js";
|
|
7
8
|
import { assertRuntimeNode } from "./node-version.js";
|
|
8
9
|
import { readNativeSettings } from "./native-settings.js";
|
|
9
10
|
export { origin } from "./service-origin.js";
|
|
@@ -39,5 +40,7 @@ export async function configuration(env) {
|
|
|
39
40
|
const config = await deviceConfiguration(env);
|
|
40
41
|
const executable = env.AGENTIM_DAEMON_BIN ? resolve(env.AGENTIM_DAEMON_BIN) : bundledExecutable();
|
|
41
42
|
await access(executable, constants.X_OK);
|
|
43
|
+
if (executable.endsWith(".mjs"))
|
|
44
|
+
await executionArtifact(executable);
|
|
42
45
|
return { ...config, executable };
|
|
43
46
|
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export interface DriverManifest {
|
|
2
|
+
execution: "node-addon-driver";
|
|
3
|
+
platform: string;
|
|
4
|
+
sha256: string;
|
|
5
|
+
addon_package: string;
|
|
6
|
+
addon_version: string;
|
|
7
|
+
addon_sha256: string;
|
|
8
|
+
source_digest: string;
|
|
9
|
+
private_payload?: boolean;
|
|
10
|
+
}
|
|
11
|
+
export interface ExecutionArtifact {
|
|
12
|
+
readonly sha256: string;
|
|
13
|
+
readonly identity: string;
|
|
14
|
+
readonly driver?: {
|
|
15
|
+
readonly manifest: DriverManifest;
|
|
16
|
+
readonly addon: string;
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
export declare function executionArtifact(executable: string): Promise<ExecutionArtifact>;
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/** Verify both roles of a shared native payload before executing or staging it. */
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { createRequire } from "node:module";
|
|
4
|
+
import { lstat, readFile } from "node:fs/promises";
|
|
5
|
+
import { dirname, isAbsolute, join } from "node:path";
|
|
6
|
+
const digest = (value) => createHash("sha256").update(value).digest("hex");
|
|
7
|
+
const checksum = (value) => typeof value === "string" && /^[a-f0-9]{64}$/.test(value);
|
|
8
|
+
export async function executionArtifact(executable) {
|
|
9
|
+
if (!isAbsolute(executable))
|
|
10
|
+
throw new Error("Communication executable must be absolute");
|
|
11
|
+
const metadata = await lstat(executable);
|
|
12
|
+
if (!metadata.isFile() || metadata.isSymbolicLink())
|
|
13
|
+
throw new Error("Communication executable must be a regular file");
|
|
14
|
+
const sha256 = digest(await readFile(executable));
|
|
15
|
+
if (!executable.endsWith(".mjs"))
|
|
16
|
+
return { sha256, identity: sha256 };
|
|
17
|
+
const [major, minor, patch] = process.versions.node.split(".").map(Number);
|
|
18
|
+
if (major !== 24 || (minor ?? 0) < 22 || minor === 22 && (patch ?? 0) < 2)
|
|
19
|
+
throw new Error("Native driver requires supported Node 24");
|
|
20
|
+
const path = join(dirname(executable), "manifest.json");
|
|
21
|
+
const file = await lstat(path);
|
|
22
|
+
if (!file.isFile() || file.isSymbolicLink() || file.size > 16384)
|
|
23
|
+
throw new Error("Invalid shared native manifest");
|
|
24
|
+
const value = JSON.parse(await readFile(path, "utf8"));
|
|
25
|
+
if (!value || typeof value !== "object" || !("execution" in value) || value.execution !== "node-addon-driver"
|
|
26
|
+
|| !("platform" in value) || value.platform !== `${process.platform}-${process.arch}`
|
|
27
|
+
|| !("sha256" in value) || value.sha256 !== sha256
|
|
28
|
+
|| !("source_digest" in value) || !checksum(value.source_digest)
|
|
29
|
+
|| !("addon_sha256" in value) || !checksum(value.addon_sha256)
|
|
30
|
+
|| !("addon_package" in value) || value.addon_package !== `@agentims/native-sdk-${process.platform}-${process.arch}`
|
|
31
|
+
|| !("addon_version" in value) || typeof value.addon_version !== "string" || !/^\d+\.\d+\.\d+$/.test(value.addon_version))
|
|
32
|
+
throw new Error("Shared native payload binding differs");
|
|
33
|
+
const manifest = { execution: "node-addon-driver", platform: String(value.platform), sha256,
|
|
34
|
+
addon_package: String(value.addon_package), addon_version: value.addon_version, addon_sha256: value.addon_sha256, source_digest: value.source_digest };
|
|
35
|
+
let addon;
|
|
36
|
+
if ("private_payload" in value && value.private_payload === true) {
|
|
37
|
+
manifest.private_payload = true;
|
|
38
|
+
addon = join(dirname(executable), "engine.node");
|
|
39
|
+
}
|
|
40
|
+
else {
|
|
41
|
+
const load = createRequire(executable);
|
|
42
|
+
const dependency = JSON.parse(await readFile(load.resolve(manifest.addon_package), "utf8"));
|
|
43
|
+
if (!dependency || typeof dependency !== "object" || !("version" in dependency) || dependency.version !== manifest.addon_version)
|
|
44
|
+
throw new Error("Native dependency version differs");
|
|
45
|
+
addon = load.resolve(manifest.addon_package + "/addon");
|
|
46
|
+
}
|
|
47
|
+
const native = await lstat(addon);
|
|
48
|
+
if (!native.isFile() || native.isSymbolicLink() || digest(await readFile(addon)) !== manifest.addon_sha256)
|
|
49
|
+
throw new Error("Shared native addon bytes differ");
|
|
50
|
+
return { sha256, identity: digest(sha256 + "\0" + manifest.addon_sha256), driver: { manifest, addon } };
|
|
51
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
/** Native executables retain their argv; shared drivers use the current trusted Node. */
|
|
2
|
+
export function nativeCommand(executable, args, node = process.execPath) {
|
|
3
|
+
return executable.endsWith(".mjs") ? [node, ["--max-old-space-size=128", executable, ...args]] : [executable, [...args]];
|
|
4
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { nativeCommand } from "../configuration/native-command.js";
|
|
1
2
|
import { spawn } from "node:child_process";
|
|
2
3
|
import { createServer } from "node:net";
|
|
3
4
|
import { setTimeout as delay } from "node:timers/promises";
|
|
@@ -20,7 +21,7 @@ export async function freePort() {
|
|
|
20
21
|
}
|
|
21
22
|
export function launch(executable, config) {
|
|
22
23
|
// No inherited credentials or shell interpolation, and no unbounded log buffer.
|
|
23
|
-
const child = spawn(executable, ["--config", config], { stdio: "pipe", windowsHide: true, env: {
|
|
24
|
+
const child = spawn(...nativeCommand(executable, ["--config", config]), { stdio: "pipe", windowsHide: true, env: {
|
|
24
25
|
PATH: process.env.PATH ?? "", RUST_LOG: "error", TOKIO_WORKER_THREADS: "1", RAYON_NUM_THREADS: "1",
|
|
25
26
|
...(process.platform === "win32" && process.env.SystemRoot ? { SystemRoot: process.env.SystemRoot } : {}),
|
|
26
27
|
} });
|
|
@@ -1,10 +1,11 @@
|
|
|
1
|
+
import { nativeCommand } from "../configuration/native-command.js";
|
|
1
2
|
import { spawn } from "node:child_process";
|
|
2
3
|
import { setTimeout as delay } from "node:timers/promises";
|
|
3
4
|
import { ManagedError } from "../managed/errors.js";
|
|
4
5
|
import { stop } from "./process.js";
|
|
5
6
|
import { lowerOwnedPriority } from "./process-priority.js";
|
|
6
7
|
function attempt(executable, directory, identity, timeoutMs) {
|
|
7
|
-
const child = spawn(executable, ["--reserve-shutdown-lock", directory, identity.ownerGeneration, identity.sourceDigest], {
|
|
8
|
+
const child = spawn(...nativeCommand(executable, ["--reserve-shutdown-lock", directory, identity.ownerGeneration, identity.sourceDigest]), {
|
|
8
9
|
stdio: "pipe", windowsHide: true, env: { PATH: "/usr/bin:/bin", ...(process.env.SystemRoot ? { SystemRoot: process.env.SystemRoot } : {}) },
|
|
9
10
|
});
|
|
10
11
|
lowerOwnedPriority(child);
|
package/dist/managed/control.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
import { join } from "node:path";
|
|
2
2
|
import { accountEnvironment } from "../accounts/context.js";
|
|
3
3
|
import { assertDeviceBinding, assertSavedDeviceBinding } from "../configuration/device-binding.js";
|
|
4
|
-
import {
|
|
4
|
+
import { executionArtifact } from "../configuration/execution-artifact.js";
|
|
5
5
|
import { configuration } from "../configuration/environment.js";
|
|
6
6
|
import { directory } from "../configuration/private-state.js";
|
|
7
7
|
import { initializeIdentity } from "../lifecycle/identity.js";
|
|
8
8
|
import { supervisor } from "../supervision/select.js";
|
|
9
9
|
import { managedDirectory } from "./directory.js";
|
|
10
10
|
import { controlLease } from "./lease.js";
|
|
11
|
-
import {
|
|
11
|
+
import { prepareBundle, readBundle, serviceSpec } from "./state.js";
|
|
12
12
|
import { bundleClient, waitForApi, waitForCommunication } from "./connection.js";
|
|
13
13
|
import { ManagedError } from "./errors.js";
|
|
14
14
|
import { sameNativeSettings } from "../configuration/native-settings.js";
|
|
@@ -40,7 +40,7 @@ async function openManagedDevice(env, initialize, passwordLogin) {
|
|
|
40
40
|
throw new ManagedError("UPGRADE_REQUIRES_STOP", "Stop managed communication before changing its portable account backup");
|
|
41
41
|
if (config.native !== undefined && !sameNativeSettings(config.native, previous.native))
|
|
42
42
|
throw new ManagedError("UPGRADE_REQUIRES_STOP", "Stop the original communication before changing its native settings");
|
|
43
|
-
if (previous.
|
|
43
|
+
if (previous.executionHash !== (await executionArtifact(config.executable)).identity)
|
|
44
44
|
throw new ManagedError("UPGRADE_REQUIRES_STOP", "Stop managed communication before upgrading its core");
|
|
45
45
|
}
|
|
46
46
|
const bundle = registered ? await readBundle(state) : await prepareBundle(config);
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export interface ManagedExecution {
|
|
2
|
+
executable: string;
|
|
3
|
+
node?: string;
|
|
4
|
+
}
|
|
5
|
+
export declare function readManagedExecution(location: string): Promise<ManagedExecution>;
|
|
6
|
+
/** Caller holds the controller lease and has unregistered the original supervisor. */
|
|
7
|
+
export declare function activateManagedExecution(location: string, source: string): Promise<void>;
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/** Complete immutable payloads precede the single durable activation pointer. */
|
|
2
|
+
import { constants } from "node:fs";
|
|
3
|
+
import { chmod, copyFile, lstat, open, rename, rm } from "node:fs/promises";
|
|
4
|
+
import { isAbsolute, join } from "node:path";
|
|
5
|
+
import { randomBytes } from "node:crypto";
|
|
6
|
+
import { directory, privateText, replacePrivate, assertPrivateDirectory } from "../configuration/private-state.js";
|
|
7
|
+
import { executionArtifact } from "../configuration/execution-artifact.js";
|
|
8
|
+
async function sync(path, directory = false) {
|
|
9
|
+
if (directory && process.platform === "win32")
|
|
10
|
+
return;
|
|
11
|
+
const file = await open(path, "r");
|
|
12
|
+
try {
|
|
13
|
+
await file.sync();
|
|
14
|
+
}
|
|
15
|
+
finally {
|
|
16
|
+
await file.close();
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
export async function readManagedExecution(location) {
|
|
20
|
+
let value;
|
|
21
|
+
try {
|
|
22
|
+
value = JSON.parse(await privateText(join(location, "execution.json")));
|
|
23
|
+
}
|
|
24
|
+
catch (error) {
|
|
25
|
+
if (error.code === "ENOENT")
|
|
26
|
+
return { executable: join(location, process.platform === "win32" ? "core.exe" : "core") };
|
|
27
|
+
throw error;
|
|
28
|
+
}
|
|
29
|
+
if (!value || typeof value !== "object" || !("version" in value) || value.version !== 1
|
|
30
|
+
|| !("payload" in value) || typeof value.payload !== "string" || !/^[a-f0-9]{64}$/.test(value.payload)
|
|
31
|
+
|| !("identity" in value) || typeof value.identity !== "string" || !/^[a-f0-9]{64}$/.test(value.identity)
|
|
32
|
+
|| ("node" in value && (typeof value.node !== "string" || !isAbsolute(value.node))))
|
|
33
|
+
throw new Error("Invalid managed execution pointer; original state was preserved");
|
|
34
|
+
const base = join(location, "runtimes", value.payload);
|
|
35
|
+
await assertPrivateDirectory(join(location, "runtimes"));
|
|
36
|
+
await assertPrivateDirectory(base);
|
|
37
|
+
const executable = join(base, "node" in value ? "core.mjs" : process.platform === "win32" ? "core.exe" : "core");
|
|
38
|
+
const artifact = await executionArtifact(executable);
|
|
39
|
+
if (artifact.identity !== value.identity || Boolean(artifact.driver) !== ("node" in value))
|
|
40
|
+
throw new Error("Managed execution payload differs");
|
|
41
|
+
if ("node" in value) {
|
|
42
|
+
const node = String(value.node);
|
|
43
|
+
const stat = await lstat(node);
|
|
44
|
+
if (!stat.isFile() || stat.isSymbolicLink())
|
|
45
|
+
throw new Error("Managed Node interpreter is unavailable");
|
|
46
|
+
return { executable, node };
|
|
47
|
+
}
|
|
48
|
+
return { executable };
|
|
49
|
+
}
|
|
50
|
+
/** Caller holds the controller lease and has unregistered the original supervisor. */
|
|
51
|
+
export async function activateManagedExecution(location, source) {
|
|
52
|
+
await assertPrivateDirectory(location);
|
|
53
|
+
const artifact = await executionArtifact(source);
|
|
54
|
+
const root = join(location, "runtimes");
|
|
55
|
+
await directory(root);
|
|
56
|
+
// Node is pinned in the execution pointer; payload identity covers every native byte.
|
|
57
|
+
const pointer = { version: 1, payload: artifact.identity, identity: artifact.identity,
|
|
58
|
+
...(artifact.driver ? { node: process.execPath } : {}) };
|
|
59
|
+
const destination = join(root, pointer.payload);
|
|
60
|
+
const temporary = join(root, `${pointer.payload}.${randomBytes(8).toString("hex")}.next`);
|
|
61
|
+
const filename = artifact.driver ? "core.mjs" : process.platform === "win32" ? "core.exe" : "core";
|
|
62
|
+
await directory(temporary);
|
|
63
|
+
try {
|
|
64
|
+
await copyFile(source, join(temporary, filename), constants.COPYFILE_EXCL | constants.COPYFILE_FICLONE);
|
|
65
|
+
await chmod(join(temporary, filename), 0o700);
|
|
66
|
+
if (artifact.driver) {
|
|
67
|
+
await copyFile(artifact.driver.addon, join(temporary, "engine.node"), constants.COPYFILE_EXCL | constants.COPYFILE_FICLONE);
|
|
68
|
+
await chmod(join(temporary, "engine.node"), 0o600);
|
|
69
|
+
await replacePrivate(join(temporary, "manifest.json"), JSON.stringify({ ...artifact.driver.manifest, private_payload: true }));
|
|
70
|
+
}
|
|
71
|
+
if ((await executionArtifact(join(temporary, filename))).identity !== artifact.identity)
|
|
72
|
+
throw new Error("Communication payload changed during staging");
|
|
73
|
+
await sync(join(temporary, filename));
|
|
74
|
+
if (artifact.driver) {
|
|
75
|
+
await sync(join(temporary, "engine.node"));
|
|
76
|
+
await sync(join(temporary, "manifest.json"));
|
|
77
|
+
}
|
|
78
|
+
await sync(temporary, true);
|
|
79
|
+
try {
|
|
80
|
+
await rename(temporary, destination);
|
|
81
|
+
}
|
|
82
|
+
catch (error) {
|
|
83
|
+
if (!["EEXIST", "ENOTEMPTY"].includes(error.code ?? ""))
|
|
84
|
+
throw error;
|
|
85
|
+
}
|
|
86
|
+
await assertPrivateDirectory(destination);
|
|
87
|
+
if ((await executionArtifact(join(destination, filename))).identity !== artifact.identity)
|
|
88
|
+
throw new Error("Existing immutable payload differs");
|
|
89
|
+
await sync(root, true);
|
|
90
|
+
await replacePrivate(join(location, "execution.json"), JSON.stringify(pointer));
|
|
91
|
+
}
|
|
92
|
+
finally {
|
|
93
|
+
await rm(temporary, { recursive: true, force: true });
|
|
94
|
+
}
|
|
95
|
+
}
|
package/dist/managed/lease.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { nativeCommand } from "../configuration/native-command.js";
|
|
1
2
|
import { stop } from "../lifecycle/process.js";
|
|
2
3
|
import { ManagedError } from "./errors.js";
|
|
3
4
|
import { setTimeout as delay } from "node:timers/promises";
|
|
@@ -7,7 +8,7 @@ import { lowerOwnedPriority } from "../lifecycle/process-priority.js";
|
|
|
7
8
|
export async function controlLease(executable, directory, kind = "controller") {
|
|
8
9
|
const deadline = Date.now() + 30_000;
|
|
9
10
|
while (Date.now() < deadline) {
|
|
10
|
-
const child = spawn(executable, [kind === "account" ? "--hold-account-lock" : "--hold-control-lock", directory], { stdio: "pipe", windowsHide: true, env: { PATH: "/usr/bin:/bin", ...(process.env.SystemRoot ? { SystemRoot: process.env.SystemRoot } : {}) } });
|
|
11
|
+
const child = spawn(...nativeCommand(executable, [kind === "account" ? "--hold-account-lock" : "--hold-control-lock", directory]), { stdio: "pipe", windowsHide: true, env: { PATH: "/usr/bin:/bin", ...(process.env.SystemRoot ? { SystemRoot: process.env.SystemRoot } : {}) } });
|
|
11
12
|
lowerOwnedPriority(child);
|
|
12
13
|
child.stderr.resume();
|
|
13
14
|
const result = await new Promise((resolve) => {
|
package/dist/managed/shutdown.js
CHANGED
|
@@ -23,12 +23,12 @@ async function previous(path, binaryHash) {
|
|
|
23
23
|
/** Wait for original token persistence and acquire device admission before any OS stop command. */
|
|
24
24
|
export async function stopManagedOwner(bundle, manager) {
|
|
25
25
|
const client = bundleClient(bundle), path = join(bundle.spec.directory, "shutdown.json");
|
|
26
|
-
let closing = await previous(path, bundle.
|
|
26
|
+
let closing = await previous(path, bundle.executionHash), lease;
|
|
27
27
|
try {
|
|
28
28
|
try {
|
|
29
29
|
const info = await client.reliability.runtimeInfo({ timeoutMs: 2000 });
|
|
30
30
|
if (info.capabilities.some(item => item.id === "runtime.clean_shutdown" && item.status === "supported")) {
|
|
31
|
-
closing = { version: 1, binaryHash: bundle.
|
|
31
|
+
closing = { version: 1, binaryHash: bundle.executionHash, ownerGeneration: info.owner_generation, sourceDigest: info.source_digest };
|
|
32
32
|
await replacePrivate(path, JSON.stringify(closing));
|
|
33
33
|
}
|
|
34
34
|
else {
|
package/dist/managed/state.d.ts
CHANGED
package/dist/managed/state.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
+
import { readManagedExecution, activateManagedExecution } from "./execution.js";
|
|
2
|
+
import { executionArtifact } from "../configuration/execution-artifact.js";
|
|
1
3
|
import { readConnection } from "../configuration/connection-descriptor.js";
|
|
2
4
|
import { createHash, randomBytes } from "node:crypto";
|
|
3
|
-
import {
|
|
4
|
-
import { copyFile, chmod, readFile, rename, realpath, unlink } from "node:fs/promises";
|
|
5
|
+
import { realpath } from "node:fs/promises";
|
|
5
6
|
import { join } from "node:path";
|
|
6
7
|
import { directory, privateText, replacePrivate, stateSecrets, assertPrivateDirectory } from "../configuration/private-state.js";
|
|
7
8
|
import { freePort } from "../lifecycle/process.js";
|
|
@@ -12,7 +13,7 @@ export const hash = (bytes) => createHash("sha256").update(bytes).digest("hex");
|
|
|
12
13
|
export async function serviceSpec(state) {
|
|
13
14
|
const canonical = await realpath(state);
|
|
14
15
|
const location = join(canonical, "managed");
|
|
15
|
-
return { directory: location, label: `im.agentim.${hash(canonical).slice(0, 24)}`,
|
|
16
|
+
return { directory: location, label: `im.agentim.${hash(canonical).slice(0, 24)}`, ...await readManagedExecution(location), configFile: join(location, "core.json") };
|
|
16
17
|
}
|
|
17
18
|
async function privateDocument(path) {
|
|
18
19
|
const contents = await privateText(path, 131072);
|
|
@@ -41,14 +42,16 @@ export async function readBundle(state) {
|
|
|
41
42
|
if (backup !== undefined && typeof backup !== "string")
|
|
42
43
|
throw new ManagedError("INVALID_MANAGED_STATE", "Managed account backup path is invalid");
|
|
43
44
|
const native = "native" in configuration ? validateNativeClientSettings(configuration.native) : undefined;
|
|
44
|
-
|
|
45
|
+
const artifact = await executionArtifact(spec.executable);
|
|
46
|
+
return { spec, connection, binaryHash: artifact.sha256, executionHash: artifact.identity, ...(artifact.driver ? { sourceDigest: artifact.driver.manifest.source_digest } : {}), ...(native ? { native } : {}), ...(typeof backup === "string" ? { credentialBackup: backup } : {}) };
|
|
45
47
|
}
|
|
46
48
|
export async function prepareBundle(config) {
|
|
47
49
|
const passphrase = await stateSecrets(config.state, config.homeserver);
|
|
48
50
|
const state = await realpath(config.state);
|
|
49
51
|
const location = join(state, "managed");
|
|
50
52
|
await directory(location);
|
|
51
|
-
const
|
|
53
|
+
const candidate = await executionArtifact(config.executable);
|
|
54
|
+
const candidateHash = candidate.identity;
|
|
52
55
|
const existing = await readBundle(state).catch(error => {
|
|
53
56
|
if (error.code === "ENOENT")
|
|
54
57
|
return undefined;
|
|
@@ -57,24 +60,13 @@ export async function prepareBundle(config) {
|
|
|
57
60
|
if (existing && existing.connection.homeserver !== config.homeserver)
|
|
58
61
|
throw new ManagedError("STATE_CONFLICT", "Managed identity belongs to another communication service");
|
|
59
62
|
const credentialBackup = config.credentialBackup;
|
|
60
|
-
if (existing && existing.
|
|
63
|
+
if (existing && existing.executionHash === candidateHash && existing.credentialBackup === credentialBackup && (config.native === undefined || sameNativeSettings(config.native, existing.native)))
|
|
61
64
|
return existing;
|
|
62
65
|
// Caller must verify that the registered supervisor is absent before replacing.
|
|
63
66
|
const token = existing?.connection.api_token ?? randomBytes(32).toString("base64url");
|
|
64
67
|
const port = existing ? Number(new URL(existing.connection.base_url).port) : await freePort();
|
|
65
|
-
if (!existing || existing.
|
|
66
|
-
|
|
67
|
-
try {
|
|
68
|
-
await copyFile(config.executable, staged, constants.COPYFILE_EXCL);
|
|
69
|
-
await chmod(staged, 0o700);
|
|
70
|
-
if (hash(await readFile(staged)) !== candidateHash)
|
|
71
|
-
throw new ManagedError("STATE_CONFLICT", "Communication core changed during staging");
|
|
72
|
-
await rename(staged, (await serviceSpec(state)).executable);
|
|
73
|
-
}
|
|
74
|
-
finally {
|
|
75
|
-
await unlink(staged).catch(() => { });
|
|
76
|
-
}
|
|
77
|
-
}
|
|
68
|
+
if (!existing || existing.executionHash !== candidateHash)
|
|
69
|
+
await activateManagedExecution(location, config.executable);
|
|
78
70
|
const native = config.native ?? existing?.native;
|
|
79
71
|
await replacePrivate(join(location, "core.json"), JSON.stringify({ homeserver: config.homeserver, store_dir: join(state, "device"), store_passphrase: passphrase, api_token: token, listen: `127.0.0.1:${port}`, shutdown_on_stdin_eof: false, ...(native ? { native } : {}), ...(credentialBackup ? { account_credential_backup: credentialBackup } : {}) }));
|
|
80
72
|
await replacePrivate(join(location, "connection.json"), JSON.stringify({ version: 1, base_url: `http://127.0.0.1:${port}`, api_token: token, homeserver: config.homeserver }));
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/** Minimal host for the existing Rust daemon. No communication logic lives here. */
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { readFileSync, lstatSync } from "node:fs";
|
|
4
|
+
import { createRequire } from "node:module";
|
|
5
|
+
import { dirname, join } from "node:path";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
async function main() {
|
|
8
|
+
const base = dirname(fileURLToPath(import.meta.url));
|
|
9
|
+
const manifest = JSON.parse(readFileSync(join(base, "manifest.json"), "utf8"));
|
|
10
|
+
if (!manifest || typeof manifest !== "object" || !("execution" in manifest) || manifest.execution !== "node-addon-driver"
|
|
11
|
+
|| !("platform" in manifest) || manifest.platform !== `${process.platform}-${process.arch}`
|
|
12
|
+
|| !("addon_package" in manifest) || manifest.addon_package !== `@agentims/native-sdk-${process.platform}-${process.arch}`
|
|
13
|
+
|| !("addon_version" in manifest) || typeof manifest.addon_version !== "string"
|
|
14
|
+
|| !("addon_sha256" in manifest) || typeof manifest.addon_sha256 !== "string"
|
|
15
|
+
|| !("sha256" in manifest) || typeof manifest.sha256 !== "string")
|
|
16
|
+
throw new Error("Invalid native driver binding");
|
|
17
|
+
const [major, minor, patch] = process.versions.node.split(".").map(Number);
|
|
18
|
+
if (major !== 24 || (minor ?? 0) < 22 || minor === 22 && (patch ?? 0) < 2)
|
|
19
|
+
throw new Error("Native driver requires supported Node 24");
|
|
20
|
+
const require = createRequire(import.meta.url);
|
|
21
|
+
let addon;
|
|
22
|
+
if ("private_payload" in manifest && manifest.private_payload === true)
|
|
23
|
+
addon = join(base, "engine.node");
|
|
24
|
+
else {
|
|
25
|
+
const metadata = JSON.parse(readFileSync(require.resolve(manifest.addon_package), "utf8"));
|
|
26
|
+
if (!metadata || typeof metadata !== "object" || !("version" in metadata) || metadata.version !== manifest.addon_version)
|
|
27
|
+
throw new Error("Native resource version differs");
|
|
28
|
+
addon = require.resolve(manifest.addon_package + "/addon");
|
|
29
|
+
}
|
|
30
|
+
for (const [path, expected] of [[fileURLToPath(import.meta.url), manifest.sha256], [addon, manifest.addon_sha256]]) {
|
|
31
|
+
if (!path || !expected || !lstatSync(path).isFile() || lstatSync(path).isSymbolicLink()
|
|
32
|
+
|| createHash("sha256").update(readFileSync(path)).digest("hex") !== expected)
|
|
33
|
+
throw new Error("Native resource bytes differ");
|
|
34
|
+
}
|
|
35
|
+
const binding = require(addon);
|
|
36
|
+
if (binding.bindingAbi() !== 1 || binding.daemonDriverAbi() !== 1)
|
|
37
|
+
throw new Error("Native driver ABI differs");
|
|
38
|
+
const command = new binding.NativeDaemonCommand(process.argv.slice(2));
|
|
39
|
+
const shutdown = () => command.shutdown();
|
|
40
|
+
if (command.cancellable) {
|
|
41
|
+
process.on("SIGTERM", shutdown);
|
|
42
|
+
process.on("SIGINT", shutdown);
|
|
43
|
+
}
|
|
44
|
+
try {
|
|
45
|
+
process.exitCode = await command.run();
|
|
46
|
+
}
|
|
47
|
+
finally {
|
|
48
|
+
if (command.cancellable) {
|
|
49
|
+
process.off("SIGTERM", shutdown);
|
|
50
|
+
process.off("SIGINT", shutdown);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
main().catch(() => { process.stderr.write("AgentIM native driver failed; original device state was preserved\n"); process.exitCode = 1; });
|
package/dist/storage/archive.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { nativeCommand } from "../configuration/native-command.js";
|
|
1
2
|
import { randomBytes } from "node:crypto";
|
|
2
3
|
import { spawn } from "node:child_process";
|
|
3
4
|
import { realpath, unlink } from "node:fs/promises";
|
|
@@ -47,7 +48,7 @@ async function maintainDeviceState(stateDir, output, options, mode) {
|
|
|
47
48
|
try {
|
|
48
49
|
const args = mode === "secrets" ? ["--config", config, "--export-secrets-bundle", resolve(output)] : ["--config", config, mode === "branch" ? "--branch-stream" : mode === "migrate" ? "--migrate-store" : "--archive-store", "--backup", resolve(output), ...(options.compact ? ["--compact-store"] : [])];
|
|
49
50
|
const text = await new Promise((accept, reject) => {
|
|
50
|
-
const child = spawn(executable, args, { windowsHide: true, stdio: "pipe", env: {
|
|
51
|
+
const child = spawn(...nativeCommand(executable, args), { windowsHide: true, stdio: "pipe", env: {
|
|
51
52
|
PATH: process.env.PATH ?? "", TOKIO_WORKER_THREADS: "1", RAYON_NUM_THREADS: "1",
|
|
52
53
|
...(process.platform === "win32" && process.env.SystemRoot ? { SystemRoot: process.env.SystemRoot } : {}),
|
|
53
54
|
} });
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { nativeCommand } from "../configuration/native-command.js";
|
|
1
2
|
import { join } from "node:path";
|
|
2
3
|
import { readFile } from "node:fs/promises";
|
|
3
4
|
import { command } from "./command.js";
|
|
@@ -9,7 +10,7 @@ export function launchdDocument(spec) {
|
|
|
9
10
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
10
11
|
<plist version="1.0"><dict>
|
|
11
12
|
<key>Label</key><string>${xml(spec.label)}</string>
|
|
12
|
-
<key>ProgramArguments</key><array
|
|
13
|
+
<key>ProgramArguments</key><array>${nativeCommand(spec.executable, ["--config", spec.configFile], spec.node).flat().map(value => `<string>${xml(value)}</string>`).join("")}</array>
|
|
13
14
|
<key>RunAtLoad</key><true/><key>KeepAlive</key><true/><key>ThrottleInterval</key><integer>10</integer>
|
|
14
15
|
<key>ExitTimeOut</key><integer>900</integer>
|
|
15
16
|
<key>Nice</key><integer>10</integer><key>ProcessType</key><string>Standard</string><key>LowPriorityIO</key><false/>
|
|
@@ -35,7 +36,7 @@ export async function launchd() {
|
|
|
35
36
|
if (!result.ok)
|
|
36
37
|
return false;
|
|
37
38
|
const lines = result.text.split("\n").map(line => line.trim());
|
|
38
|
-
if (!lines.includes(`program = ${spec.executable}`) || !lines.includes(spec.configFile)) {
|
|
39
|
+
if (!lines.includes(`program = ${spec.node ?? spec.executable}`) || (spec.node && !lines.includes(spec.executable)) || !lines.includes(spec.configFile)) {
|
|
39
40
|
throw new ManagedError("SERVICE_CONFLICT", "Supervisor job does not match this communication device");
|
|
40
41
|
}
|
|
41
42
|
return true;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
2
|
export function signature(spec) {
|
|
3
|
-
return createHash("sha256").update(spec.executable + "\0" + spec.configFile).digest("hex");
|
|
3
|
+
return createHash("sha256").update((spec.node ? spec.node + "\0" : "") + spec.executable + "\0" + spec.configFile).digest("hex");
|
|
4
4
|
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { nativeCommand } from "../configuration/native-command.js";
|
|
1
2
|
import { command } from "./command.js";
|
|
2
3
|
import { signature } from "./service.js";
|
|
3
4
|
import { ManagedError } from "../managed/errors.js";
|
|
@@ -5,9 +6,9 @@ export function systemdArguments(spec) {
|
|
|
5
6
|
return ["--user", `--unit=${spec.label}`, "--collect", "--service-type=exec",
|
|
6
7
|
`--description=AgentIM ${signature(spec)}`, "--property=Restart=always", "--property=RestartSec=10s",
|
|
7
8
|
"--property=TimeoutStopSec=900s",
|
|
8
|
-
"--property=Nice=10", "--property=CPUQuota=50%", "--property=MemoryMax=512M", "--property=TasksMax=
|
|
9
|
+
"--property=Nice=10", "--property=CPUQuota=50%", "--property=MemoryMax=512M", "--property=TasksMax=48",
|
|
9
10
|
"--property=StandardOutput=null", "--property=StandardError=null", "--setenv=RUST_LOG=error",
|
|
10
|
-
"--setenv=TOKIO_WORKER_THREADS=1", "--setenv=RAYON_NUM_THREADS=1", spec.executable, "--config", spec.configFile];
|
|
11
|
+
"--setenv=TOKIO_WORKER_THREADS=1", "--setenv=RAYON_NUM_THREADS=1", ...nativeCommand(spec.executable, ["--config", spec.configFile], spec.node).flat()];
|
|
11
12
|
}
|
|
12
13
|
export async function systemd() {
|
|
13
14
|
if (!process.getuid?.() || !(await command("/usr/bin/systemctl", ["--user", "show-environment"])).ok) {
|
|
@@ -7,7 +7,7 @@ try {
|
|
|
7
7
|
try { $inputData = $reader.ReadToEnd() | ConvertFrom-Json } finally { $reader.Dispose() }
|
|
8
8
|
$spec = $inputData.spec
|
|
9
9
|
if ($spec.label -notmatch '^im\.agentim\.[a-f0-9]{24}$') { throw 'label' }
|
|
10
|
-
foreach ($path in @($spec.executable, $spec.configFile)) {
|
|
10
|
+
foreach ($path in @($spec.executable, $spec.configFile) + $(if ($spec.node) { @($spec.node) } else { @() })) {
|
|
11
11
|
if (![IO.Path]::IsPathRooted($path) -or $path -match '["\r\n]') { throw 'path' }
|
|
12
12
|
}
|
|
13
13
|
$sid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value
|
|
@@ -20,13 +20,14 @@ try {
|
|
|
20
20
|
# PowerShell can wrap COM failures in MethodInvocationException.
|
|
21
21
|
if ($_.Exception.GetBaseException().HResult -ne -2147024894) { throw }
|
|
22
22
|
}
|
|
23
|
-
$
|
|
23
|
+
$program = $(if ($spec.node) { $spec.node } else { $spec.executable })
|
|
24
|
+
$arguments = $(if ($spec.node) { '--max-old-space-size=128 "' + $spec.executable + '" ' } else { '' }) + '--config "' + $spec.configFile + '"'
|
|
24
25
|
if ($task) {
|
|
25
26
|
$definition = $task.Definition
|
|
26
27
|
if ($definition.RegistrationInfo.Description -ne $inputData.signature -or
|
|
27
28
|
$definition.Principal.UserId -ne $sid -or $definition.Principal.LogonType -ne 3 -or
|
|
28
29
|
$definition.Principal.RunLevel -ne 0 -or $definition.Actions.Count -ne 1 -or
|
|
29
|
-
$definition.Actions.Item(1).Path -ne $
|
|
30
|
+
$definition.Actions.Item(1).Path -ne $program -or
|
|
30
31
|
$definition.Actions.Item(1).Arguments -ne $arguments) { throw 'service conflict' }
|
|
31
32
|
}
|
|
32
33
|
switch ($inputData.operation) {
|
|
@@ -51,7 +52,7 @@ try {
|
|
|
51
52
|
$trigger = $definition.Triggers.Create(9) # At logon of this user only.
|
|
52
53
|
$trigger.UserId = $sid
|
|
53
54
|
$action = $definition.Actions.Create(0)
|
|
54
|
-
$action.Path = $
|
|
55
|
+
$action.Path = $program
|
|
55
56
|
$action.Arguments = $arguments
|
|
56
57
|
$task = $folder.RegisterTaskDefinition($spec.label, $definition, 2, $sid, $null, 3)
|
|
57
58
|
}
|
|
@@ -6,4 +6,4 @@ export interface ActiveClient {
|
|
|
6
6
|
}
|
|
7
7
|
export declare function activeClient(root?: string): Promise<ActiveClient | undefined>;
|
|
8
8
|
/** Stable CLI entry delegates only to this user's already-verified activated release slot. */
|
|
9
|
-
export declare function delegateActiveCLI(argv: readonly string[], root?: string): Promise<boolean>;
|
|
9
|
+
export declare function delegateActiveCLI(argv: readonly string[], root?: string, signal?: AbortSignal): Promise<boolean>;
|
|
@@ -25,7 +25,9 @@ export async function activeClient(root = clientUpdateRoot()) {
|
|
|
25
25
|
}
|
|
26
26
|
}
|
|
27
27
|
/** Stable CLI entry delegates only to this user's already-verified activated release slot. */
|
|
28
|
-
export async function delegateActiveCLI(argv, root = clientUpdateRoot()) {
|
|
28
|
+
export async function delegateActiveCLI(argv, root = clientUpdateRoot(), signal) {
|
|
29
|
+
if (signal?.aborted)
|
|
30
|
+
return false;
|
|
29
31
|
const active = await activeClient(root);
|
|
30
32
|
if (!active)
|
|
31
33
|
return false;
|
|
@@ -42,6 +44,8 @@ export async function delegateActiveCLI(argv, root = clientUpdateRoot()) {
|
|
|
42
44
|
return false;
|
|
43
45
|
if (process.env.AGENTIM_CLIENT_GENERATION === active.digest)
|
|
44
46
|
throw new UpdateError("UPDATE_ACTIVATION_LOOP", "Client activation did not resolve to its verified CLI");
|
|
47
|
+
if (signal?.aborted)
|
|
48
|
+
return false;
|
|
45
49
|
const code = await new Promise((accept, reject) => {
|
|
46
50
|
const child = spawn(process.execPath, [cli, ...argv], { stdio: "inherit", windowsHide: true,
|
|
47
51
|
env: { ...process.env, AGENTIM_CLIENT_GENERATION: active.digest } });
|
|
@@ -49,7 +53,10 @@ export async function delegateActiveCLI(argv, root = clientUpdateRoot()) {
|
|
|
49
53
|
const terminate = () => { child.kill("SIGTERM"); };
|
|
50
54
|
process.on("SIGINT", interrupt);
|
|
51
55
|
process.on("SIGTERM", terminate);
|
|
52
|
-
|
|
56
|
+
signal?.addEventListener("abort", terminate, { once: true });
|
|
57
|
+
if (signal?.aborted)
|
|
58
|
+
terminate();
|
|
59
|
+
const cleanup = () => { process.off("SIGINT", interrupt); process.off("SIGTERM", terminate); signal?.removeEventListener("abort", terminate); };
|
|
53
60
|
child.once("error", () => { cleanup(); reject(new UpdateError("UPDATE_CLI_START_FAILED", "Activated client CLI could not start")); });
|
|
54
61
|
child.once("exit", (code, signal) => { cleanup(); accept(code ?? (signal === "SIGINT" ? 130 : 1)); });
|
|
55
62
|
});
|
|
@@ -17,7 +17,7 @@ export async function runtimePackageInfo() {
|
|
|
17
17
|
}
|
|
18
18
|
export async function boundedJSON(url, maxBytes = 196608) {
|
|
19
19
|
safeURL(url);
|
|
20
|
-
const response = await fetch(url, { headers: clientRequestHeaders, redirect: "error", credentials: "omit", cache: "no-store", signal: AbortSignal.timeout(15000) });
|
|
20
|
+
const response = await fetch(url, { headers: { ...clientRequestHeaders, "X-AgentIM-Native-Driver": "1" }, redirect: "error", credentials: "omit", cache: "no-store", signal: AbortSignal.timeout(15000) });
|
|
21
21
|
if (!response.ok || !response.body)
|
|
22
22
|
throw new UpdateError("UPDATE_SOURCE_UNAVAILABLE", "Client update source is unavailable");
|
|
23
23
|
const reader = response.body.getReader();
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { nativeCommand } from "../configuration/native-command.js";
|
|
1
2
|
import { spawn } from "node:child_process";
|
|
2
3
|
import { access, readFile, stat } from "node:fs/promises";
|
|
3
4
|
import { dirname, isAbsolute, join } from "node:path";
|
|
@@ -6,7 +7,7 @@ import { lowerOwnedPriority } from "../lifecycle/process-priority.js";
|
|
|
6
7
|
import { bundledExecutable } from "../configuration/executable.js";
|
|
7
8
|
import { validateBindings } from "./binding-preflight.js";
|
|
8
9
|
import { installationDigest } from "./installation-integrity.js";
|
|
9
|
-
import {
|
|
10
|
+
import { executionArtifact } from "../configuration/execution-artifact.js";
|
|
10
11
|
import { downloadArtifact } from "./download.js";
|
|
11
12
|
import { packageVersion, platformPackages } from "./manifest.js";
|
|
12
13
|
import { compareVersion } from "./version.js";
|
|
@@ -15,7 +16,7 @@ export async function runUpdateProcess(command, args, cwd, budgetMs = 300000) {
|
|
|
15
16
|
if (!isAbsolute(command))
|
|
16
17
|
throw new UpdateError("UPDATE_EXECUTABLE_INVALID", "Update executable must be absolute");
|
|
17
18
|
return new Promise((resolve, reject) => {
|
|
18
|
-
const child = spawn(command,
|
|
19
|
+
const child = spawn(...nativeCommand(command, args), { cwd, windowsHide: true, stdio: "pipe", env: {
|
|
19
20
|
PATH: dirname(process.execPath), NODE_OPTIONS: "--max-old-space-size=512", TOKIO_WORKER_THREADS: "1", RAYON_NUM_THREADS: "1",
|
|
20
21
|
...(process.platform === "win32" && process.env.SystemRoot ? { SystemRoot: process.env.SystemRoot } : {}),
|
|
21
22
|
} });
|
|
@@ -88,7 +89,7 @@ export async function validateInstallation(release, slot) {
|
|
|
88
89
|
}
|
|
89
90
|
const executable = bundledExecutable(process.platform, process.arch, undefined, runtime);
|
|
90
91
|
const platform = release.platforms.find(value => value.platform === `${process.platform}-${process.arch}`);
|
|
91
|
-
if (!platform || (await
|
|
92
|
+
if (!platform || (await executionArtifact(executable)).identity !== platform.coreSha256)
|
|
92
93
|
throw new UpdateError("UPDATE_CORE_MISMATCH", "Installed communication core differs from the signed release");
|
|
93
94
|
const facts = JSON.parse(await runUpdateProcess(executable, ["--client-info"], slot, 30000));
|
|
94
95
|
if (!facts || typeof facts !== "object" || !("source_digest" in facts) || facts.source_digest !== platform.sourceDigest
|
package/dist/updates/ledger.js
CHANGED
|
@@ -39,7 +39,7 @@ export async function planClientUpdate(options) {
|
|
|
39
39
|
let needsCore = compareVersion(assessment.targetVersion, loaded) > 0 && assessment.state === "current" && compareVersion(assessment.targetVersion, current) === 0;
|
|
40
40
|
if ((options.owner ?? "managed") === "managed" && assessment.state === "current" && compareVersion(assessment.targetVersion, current) === 0) {
|
|
41
41
|
const bundle = await readBundle(options.stateDir);
|
|
42
|
-
needsCore ||= release.platforms.some(item => item.platform === `${process.platform}-${process.arch}` && item.executionValidated && item.coreSha256 !== bundle.
|
|
42
|
+
needsCore ||= release.platforms.some(item => item.platform === `${process.platform}-${process.arch}` && item.executionValidated && item.coreSha256 !== bundle.executionHash);
|
|
43
43
|
}
|
|
44
44
|
if (options.client && options.owner === "embedded" && assessment.state === "current" && compareVersion(assessment.targetVersion, current) === 0) {
|
|
45
45
|
if (options.client.ownerKind !== "embedded" || options.client.storeDirectory !== await realpath(join(stateDir, "device")))
|
package/dist/updates/managed.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
+
import { activateManagedExecution } from "../managed/execution.js";
|
|
1
2
|
import { constants } from "node:fs";
|
|
2
3
|
import { quiesceForUpdate } from "./admission.js";
|
|
3
4
|
import { expectCleanShutdown, verifyCleanShutdown } from "./shutdown-proof.js";
|
|
4
|
-
import { chmod, copyFile, lstat
|
|
5
|
+
import { chmod, copyFile, lstat } from "node:fs/promises";
|
|
5
6
|
import { join } from "node:path";
|
|
6
|
-
import { randomBytes } from "node:crypto";
|
|
7
7
|
import { readBundle } from "../managed/state.js";
|
|
8
8
|
import { bundleClient, waitForApi, waitForCommunication } from "../managed/connection.js";
|
|
9
9
|
import { updateLease, updateControllerExecutable } from "./locking.js";
|
|
@@ -35,21 +35,6 @@ async function exists(path) {
|
|
|
35
35
|
throw error;
|
|
36
36
|
}
|
|
37
37
|
}
|
|
38
|
-
async function switchCore(source, destination, expected) {
|
|
39
|
-
if ((await fileDigest(destination)).sha256 === expected)
|
|
40
|
-
return;
|
|
41
|
-
const temporary = `${destination}.${randomBytes(8).toString("hex")}.next`;
|
|
42
|
-
try {
|
|
43
|
-
await copyFile(source, temporary, constants.COPYFILE_EXCL);
|
|
44
|
-
await chmod(temporary, 0o700);
|
|
45
|
-
if ((await fileDigest(temporary)).sha256 !== expected)
|
|
46
|
-
throw new UpdateError("UPDATE_CORE_MISMATCH", "Candidate core changed during activation");
|
|
47
|
-
await rename(temporary, destination);
|
|
48
|
-
}
|
|
49
|
-
finally {
|
|
50
|
-
await unlink(temporary).catch(() => { });
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
38
|
/** Internal driver seam also permits a controlled foreground supervisor in acceptance tests. */
|
|
54
39
|
export async function applyManagedUpdate(options, manager, observe) {
|
|
55
40
|
const policy = await readUpdatePolicy(options.root);
|
|
@@ -71,7 +56,7 @@ export async function applyManagedUpdate(options, manager, observe) {
|
|
|
71
56
|
if (!platform?.executionValidated)
|
|
72
57
|
throw new UpdateError("UPDATE_PLATFORM_UNVALIDATED", "The release has no executed acceptance for this client platform");
|
|
73
58
|
const installed = await stageInstallation(release, record.manifestDigest, policy);
|
|
74
|
-
|
|
59
|
+
let bundle = await readBundle(record.stateDir);
|
|
75
60
|
const releaseDevice = await controlLease(updateControllerExecutable(), bundle.spec.directory);
|
|
76
61
|
const transition = async (phase, errorCode = null) => {
|
|
77
62
|
record = { ...record, phase, errorCode, updatedAtMs: Date.now() };
|
|
@@ -87,7 +72,7 @@ export async function applyManagedUpdate(options, manager, observe) {
|
|
|
87
72
|
return record;
|
|
88
73
|
}
|
|
89
74
|
if (["staged", "quiescing"].includes(record.phase)) {
|
|
90
|
-
const approvedLegacy = platform.compatibleCoreSha256.includes(bundle.
|
|
75
|
+
const approvedLegacy = platform.compatibleCoreSha256.includes(bundle.executionHash) || bundle.executionHash === platform.coreSha256;
|
|
91
76
|
if (!approvedLegacy) {
|
|
92
77
|
await transition("deferred", "UPDATE_SOURCE_CORE_NOT_APPROVED");
|
|
93
78
|
await resumeHost(policy, record.updateId, options.host);
|
|
@@ -132,7 +117,7 @@ export async function applyManagedUpdate(options, manager, observe) {
|
|
|
132
117
|
}
|
|
133
118
|
if ((await fileDigest(oldCore)).sha256 !== bundle.binaryHash)
|
|
134
119
|
throw new UpdateError("UPDATE_OLD_CORE_CONFLICT", "Original communication core backup differs");
|
|
135
|
-
await updateDocument(policy.root, `${record.updateId}.owner.json`, { binaryHash: bundle.binaryHash });
|
|
120
|
+
await updateDocument(policy.root, `${record.updateId}.owner.json`, { binaryHash: bundle.binaryHash, executionHash: bundle.executionHash, executable: bundle.spec.executable });
|
|
136
121
|
await expectCleanShutdown(policy.root, record.updateId, info);
|
|
137
122
|
await transition("quiesced");
|
|
138
123
|
await client?.close();
|
|
@@ -201,12 +186,13 @@ export async function applyManagedUpdate(options, manager, observe) {
|
|
|
201
186
|
if (["migrated", "switching"].includes(record.phase)) {
|
|
202
187
|
const original = JSON.parse(await privateText(join(policy.root, `${record.updateId}.owner.json`)));
|
|
203
188
|
const hash = (await fileDigest(bundle.spec.executable)).sha256;
|
|
204
|
-
if (hash !== original.binaryHash &&
|
|
189
|
+
if ((original.executionHash ? bundle.executionHash !== original.executionHash : hash !== original.binaryHash) && bundle.executionHash !== platform.coreSha256)
|
|
205
190
|
throw new UpdateError("UPDATE_OWNER_CHANGED", "Managed communication changed since update planning");
|
|
206
191
|
if (await manager.registered(bundle.spec))
|
|
207
192
|
throw new UpdateError("UPDATE_OLD_OWNER_ACTIVE", "The original supervisor is still registered");
|
|
208
193
|
await transition("switching");
|
|
209
|
-
await
|
|
194
|
+
await activateManagedExecution(bundle.spec.directory, installed.executable);
|
|
195
|
+
bundle = await readBundle(record.stateDir);
|
|
210
196
|
await transition("opening");
|
|
211
197
|
}
|
|
212
198
|
if (record.phase === "opening") {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@agentims/runtime",
|
|
3
|
-
"version": "0.9.
|
|
3
|
+
"version": "0.9.6",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"engines": {
|
|
6
6
|
"node": ">=24.22.2 <25"
|
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
"dependencies": {
|
|
23
23
|
"@agentims/sdk": "0.8.2",
|
|
24
24
|
"@agentims/adapter": "0.1.5",
|
|
25
|
-
"@agentims/runtime-assets": "0.9.
|
|
25
|
+
"@agentims/runtime-assets": "0.9.6"
|
|
26
26
|
},
|
|
27
27
|
"publishConfig": {
|
|
28
28
|
"access": "public",
|