@agentage/extension 0.14.0 → 0.15.0
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 +3 -1
- package/dist/health/health.d.ts +2 -0
- package/dist/health/health.js +4 -2
- package/dist/health/health.schema.d.ts +9 -0
- package/dist/health/health.schema.js +3 -0
- package/dist/host/clock-rate.d.ts +1 -0
- package/dist/host/clock-rate.js +12 -0
- package/dist/host/daemon/add.js +24 -3
- package/dist/host/daemon/child-files.d.ts +20 -0
- package/dist/host/daemon/child-files.js +45 -0
- package/dist/host/daemon/child.d.ts +10 -4
- package/dist/host/daemon/child.js +63 -37
- package/dist/host/daemon/daemon-files.d.ts +3 -0
- package/dist/host/daemon/daemon-files.js +5 -1
- package/dist/host/daemon/daemon.d.ts +1 -0
- package/dist/host/daemon/daemon.js +21 -6
- package/dist/host/daemon/gate.d.ts +3 -0
- package/dist/host/daemon/gate.js +19 -0
- package/dist/host/daemon/guard.d.ts +2 -1
- package/dist/host/daemon/guard.js +16 -4
- package/dist/host/daemon/health-routes.d.ts +17 -0
- package/dist/host/daemon/health-routes.js +61 -0
- package/dist/host/daemon/host-token.d.ts +6 -0
- package/dist/host/daemon/host-token.js +28 -0
- package/dist/host/daemon/last-words.d.ts +2 -0
- package/dist/host/daemon/last-words.js +28 -0
- package/dist/host/daemon/limits.d.ts +4 -0
- package/dist/host/daemon/limits.js +7 -0
- package/dist/host/daemon/ops.js +4 -1
- package/dist/host/daemon/pending.d.ts +1 -1
- package/dist/host/daemon/proxy.d.ts +1 -1
- package/dist/host/daemon/proxy.js +16 -8
- package/dist/host/daemon/reload-marker.d.ts +8 -0
- package/dist/host/daemon/reload-marker.js +56 -0
- package/dist/host/daemon/reload-route.d.ts +4 -0
- package/dist/host/daemon/reload-route.js +21 -0
- package/dist/host/daemon/reload.d.ts +10 -0
- package/dist/host/daemon/reload.js +73 -0
- package/dist/host/daemon/restart.d.ts +14 -0
- package/dist/host/daemon/restart.js +59 -0
- package/dist/host/daemon/routes.d.ts +2 -10
- package/dist/host/daemon/routes.js +13 -31
- package/dist/host/daemon/run-lock.d.ts +1 -0
- package/dist/host/daemon/run-lock.js +15 -0
- package/dist/host/daemon/seal-reach.d.ts +2 -0
- package/dist/host/daemon/seal-reach.js +38 -0
- package/dist/host/daemon/seal.d.ts +16 -0
- package/dist/host/daemon/seal.js +71 -0
- package/dist/host/daemon/start-checks.d.ts +6 -0
- package/dist/host/daemon/start-checks.js +28 -0
- package/dist/host/daemon/supervisor.d.ts +9 -3
- package/dist/host/daemon/supervisor.js +33 -40
- package/dist/host/data-lock.d.ts +2 -1
- package/dist/host/data-lock.js +25 -6
- package/dist/host/host-env.d.ts +1 -0
- package/dist/host/host-env.js +2 -0
- package/dist/host/host-extension.d.ts +4 -0
- package/dist/host/host-extension.js +23 -43
- package/dist/host/host-parts.d.ts +25 -0
- package/dist/host/host-parts.js +75 -0
- package/dist/host/host-store.d.ts +3 -0
- package/dist/host/host-store.js +21 -2
- package/dist/host/main.js +2 -0
- package/dist/host/part-checks.d.ts +2 -0
- package/dist/host/part-checks.js +19 -0
- package/dist/host/serve-host.js +6 -3
- package/dist/manifest/parts.d.ts +3 -0
- package/dist/manifest/parts.js +3 -0
- package/dist/mcp/mcp-app.d.ts +4 -0
- package/dist/mcp/mcp-app.js +11 -11
- package/dist/runtime/part-mounts.d.ts +29 -0
- package/dist/runtime/part-mounts.js +52 -0
- package/dist/runtime/part-runners.d.ts +2 -15
- package/dist/runtime/part-runners.js +13 -58
- package/dist/server/app.d.ts +3 -0
- package/dist/server/app.js +16 -16
- package/dist/tool/check.d.ts +2 -0
- package/dist/tool/check.js +23 -8
- package/dist/tool/container-parts.d.ts +1 -1
- package/dist/tool/container-parts.js +6 -6
- package/dist/tool/format.js +15 -8
- package/dist/tool/kit-version.d.ts +2 -0
- package/dist/tool/kit-version.js +12 -0
- package/dist/worker/clock.d.ts +6 -0
- package/dist/worker/clock.js +21 -0
- package/dist/worker/scheduler.d.ts +1 -0
- package/dist/worker/scheduler.js +6 -2
- package/package.json +1 -1
- package/schemas/health.schema.json +17 -0
package/README.md
CHANGED
|
@@ -12,7 +12,9 @@ npm install @agentage/extension express zod
|
|
|
12
12
|
```
|
|
13
13
|
|
|
14
14
|
`agentage extension check [dir] --json` prints the conformance report (exit 1 when `conforms` is
|
|
15
|
-
false); `file` and `line` are there only when a problem has them
|
|
15
|
+
false); `file` and `line` are there only when a problem has them. `warnings` is there only when a
|
|
16
|
+
rule warned: an `engines.agentage` of an older kit minor from the floor `0.12` up conforms with a
|
|
17
|
+
warning; below the floor or above the running kit it is a problem:
|
|
16
18
|
|
|
17
19
|
```json
|
|
18
20
|
{
|
package/dist/health/health.d.ts
CHANGED
|
@@ -12,7 +12,9 @@ export interface HealthOptions {
|
|
|
12
12
|
checks?: Record<string, HealthCheck>;
|
|
13
13
|
instance?: string;
|
|
14
14
|
startedAt?: number;
|
|
15
|
+
parts?: ImagePartKind[];
|
|
15
16
|
now?: () => Date;
|
|
17
|
+
clockRate?: number;
|
|
16
18
|
log?: Log;
|
|
17
19
|
}
|
|
18
20
|
export declare const worstOf: (statuses: HealthStatus[]) => HealthStatus;
|
package/dist/health/health.js
CHANGED
|
@@ -36,9 +36,11 @@ export const healthBody = async (options) => {
|
|
|
36
36
|
const now = (options.now ?? (() => new Date()))();
|
|
37
37
|
const checks = await runChecks(options.checks ?? {});
|
|
38
38
|
const status = worstOf(Object.values(checks));
|
|
39
|
-
const { extension, part, version, build, instance } = options;
|
|
39
|
+
const { extension, part, parts, version, build, instance } = options;
|
|
40
40
|
const uptimeSeconds = Math.max(0, Math.floor((now.getTime() - options.startedAt) / 1000));
|
|
41
|
-
const
|
|
41
|
+
const clock = options.clockRate && options.clockRate !== 1 ? { clockRate: options.clockRate } : {};
|
|
42
|
+
const listed = parts ? { parts } : {};
|
|
43
|
+
const data = { status, extension, part, ...listed, version, ...build, instance, ...clock };
|
|
42
44
|
return {
|
|
43
45
|
success: status !== 'unavailable',
|
|
44
46
|
data: { ...data, uptimeSeconds, checkedAt: isoSeconds(now), checks },
|
|
@@ -21,9 +21,18 @@ export declare const HealthSchema: z.ZodObject<{
|
|
|
21
21
|
worker: "worker";
|
|
22
22
|
store: "store";
|
|
23
23
|
}>;
|
|
24
|
+
parts: z.ZodOptional<z.ZodArray<z.ZodEnum<{
|
|
25
|
+
pages: "pages";
|
|
26
|
+
ui: "ui";
|
|
27
|
+
api: "api";
|
|
28
|
+
mcp: "mcp";
|
|
29
|
+
worker: "worker";
|
|
30
|
+
store: "store";
|
|
31
|
+
}>>>;
|
|
24
32
|
version: z.ZodString;
|
|
25
33
|
commit: z.ZodString;
|
|
26
34
|
buildTime: z.ZodISODateTime;
|
|
35
|
+
clockRate: z.ZodOptional<z.ZodNumber>;
|
|
27
36
|
instance: z.ZodString;
|
|
28
37
|
uptimeSeconds: z.ZodInt;
|
|
29
38
|
checkedAt: z.ZodISODateTime;
|
|
@@ -9,9 +9,12 @@ export const HealthSchema = z.strictObject({
|
|
|
9
9
|
status: HealthStatusSchema,
|
|
10
10
|
extension: ExtensionIdSchema,
|
|
11
11
|
part: DeployedPartKindSchema,
|
|
12
|
+
// A host process that runs several parts (the daemon's child, the one container) lists them.
|
|
13
|
+
parts: z.array(DeployedPartKindSchema).optional(),
|
|
12
14
|
version: VersionSchema,
|
|
13
15
|
commit: z.string().regex(/^[0-9a-f]{7,40}$/),
|
|
14
16
|
buildTime: z.iso.datetime(),
|
|
17
|
+
clockRate: z.number().optional(),
|
|
15
18
|
instance: z.string().regex(/^[0-9a-f]{8,32}$/),
|
|
16
19
|
uptimeSeconds: z.int().min(0),
|
|
17
20
|
checkedAt: z.iso.datetime(),
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const startHostClock: (env: Record<string, string | undefined>) => number;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { createLog } from '../log/log.js';
|
|
2
|
+
import { CLOCK_RATE_ENV, parseClockRate, setHostClockRate } from '../worker/clock.js';
|
|
3
|
+
// Only the kit host child reads the test clock from env; a bad value stops the boot.
|
|
4
|
+
export const startHostClock = (env) => {
|
|
5
|
+
const rate = parseClockRate(env[CLOCK_RATE_ENV]);
|
|
6
|
+
setHostClockRate(rate);
|
|
7
|
+
if (rate !== 1) {
|
|
8
|
+
const log = createLog({ extension: 'host', part: 'api' });
|
|
9
|
+
log.warn('test clock on: job times run faster, for tests only', { clockRate: rate });
|
|
10
|
+
}
|
|
11
|
+
return rate;
|
|
12
|
+
};
|
package/dist/host/daemon/add.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
2
|
+
import { rm } from 'node:fs/promises';
|
|
1
3
|
import { isAbsolute } from 'node:path';
|
|
2
4
|
import { z } from 'zod';
|
|
3
5
|
import { fail } from '../../envelope/envelope.js';
|
|
@@ -7,7 +9,9 @@ import { readManifest } from '../../manifest/read-manifest.js';
|
|
|
7
9
|
import { persist, summary } from './entries.js';
|
|
8
10
|
import { runInstaller } from './installer-call.js';
|
|
9
11
|
import {} from './installation.js';
|
|
10
|
-
import {
|
|
12
|
+
import { clearRunDir, dataDirOf } from './daemon-files.js';
|
|
13
|
+
import { needsSecret } from './start-checks.js';
|
|
14
|
+
import { startEntry, startFailed } from './supervisor.js';
|
|
11
15
|
const RESERVED_ID = 'host';
|
|
12
16
|
// enabled: false records the extension and never starts it (a profile "off" entry).
|
|
13
17
|
const AddSchema = z.union([
|
|
@@ -45,7 +49,24 @@ const marketEntry = async (deps, entries, id, version) => {
|
|
|
45
49
|
const got = await runInstaller(deps, { id, version });
|
|
46
50
|
return { install: { id: got.id, version: got.version }, dir: got.dir, version: got.version };
|
|
47
51
|
};
|
|
48
|
-
//
|
|
52
|
+
// C6: a new id that did not start leaves no row; only a data folder this start made goes too.
|
|
53
|
+
const rollBack = async (deps, entries, entry, fresh) => {
|
|
54
|
+
entries.delete(entry.id);
|
|
55
|
+
await persist(deps, entry.id);
|
|
56
|
+
await clearRunDir(deps.configDir, entry.id);
|
|
57
|
+
if (fresh)
|
|
58
|
+
await rm(dataDirOf(deps.configDir, entry.id), { recursive: true, force: true });
|
|
59
|
+
};
|
|
60
|
+
// The first start; refused and rolled back unless it waits for a secret or the daemon stops (kept).
|
|
61
|
+
const firstStart = async (deps, entries, entry) => {
|
|
62
|
+
const fresh = !existsSync(dataDirOf(deps.configDir, entry.id));
|
|
63
|
+
const err = await startEntry(deps, entry);
|
|
64
|
+
if (!err || needsSecret(err) || deps.stopping.signal.aborted)
|
|
65
|
+
return;
|
|
66
|
+
await rollBack(deps, entries, entry, fresh);
|
|
67
|
+
throw startFailed(entry, err);
|
|
68
|
+
};
|
|
69
|
+
// POST: installs (or links a folder), records it, then starts it (C6: a failed start is refused).
|
|
49
70
|
export const addExtension = async (deps, entries, body) => {
|
|
50
71
|
const spec = parse(AddSchema, body, 'Invalid body');
|
|
51
72
|
const got = 'source' in spec
|
|
@@ -58,6 +79,6 @@ export const addExtension = async (deps, entries, body) => {
|
|
|
58
79
|
const entry = { ...got, id: install.id, install, state: 'disabled' };
|
|
59
80
|
entries.set(entry.id, entry);
|
|
60
81
|
if (!off)
|
|
61
|
-
await
|
|
82
|
+
await firstStart(deps, entries, entry);
|
|
62
83
|
return summary(entry);
|
|
63
84
|
};
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
interface RunSpec {
|
|
2
|
+
id: string;
|
|
3
|
+
dir: string;
|
|
4
|
+
dataDir: string;
|
|
5
|
+
secrets: Record<string, string>;
|
|
6
|
+
}
|
|
7
|
+
export interface RunFolders {
|
|
8
|
+
runDir: string;
|
|
9
|
+
secretsDir: string;
|
|
10
|
+
tmpDir: string;
|
|
11
|
+
made: {
|
|
12
|
+
run: boolean;
|
|
13
|
+
data: boolean;
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
export declare const runDirFor: (spec: Pick<RunSpec, "id" | "dataDir">) => string;
|
|
17
|
+
export declare const makeRun: (spec: RunSpec) => Promise<RunFolders>;
|
|
18
|
+
export declare const fillRun: (run: RunFolders, spec: RunSpec) => Promise<void>;
|
|
19
|
+
export declare const undoRun: ({ runDir, made }: RunFolders, dataDir: string) => Promise<void>;
|
|
20
|
+
export {};
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { mkdir, rm, rmdir, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { dirname, join } from 'node:path';
|
|
3
|
+
import { secretNames } from '../../manifest/parts.js';
|
|
4
|
+
import { SecretNameSchema } from '../../manifest/primitives.schema.js';
|
|
5
|
+
import { readManifest } from '../../manifest/read-manifest.js';
|
|
6
|
+
import { clearOldLock } from '../data-lock.js';
|
|
7
|
+
import { runDirOf } from './daemon-files.js';
|
|
8
|
+
import { clearRunLock } from './run-lock.js';
|
|
9
|
+
// The supervisor's dataDir is <configDir>/data/{id}, so run/{id} sits beside data/ (C2).
|
|
10
|
+
export const runDirFor = (spec) => runDirOf(dirname(dirname(spec.dataDir)), spec.id);
|
|
11
|
+
// Only the names the package declares now: a row can still hold one an older version declared.
|
|
12
|
+
const declared = async (spec) => {
|
|
13
|
+
const names = new Set(secretNames(await readManifest(spec.dir)));
|
|
14
|
+
return Object.entries(spec.secrets).filter(([name]) => names.has(name));
|
|
15
|
+
};
|
|
16
|
+
// The folders first, so undoRun knows what this launch made; data/{id} before the fork (PGlite).
|
|
17
|
+
export const makeRun = async (spec) => {
|
|
18
|
+
const runDir = runDirFor(spec);
|
|
19
|
+
const run = await mkdir(runDir, { recursive: true, mode: 0o700 });
|
|
20
|
+
const data = await mkdir(spec.dataDir, { recursive: true }).catch(async (err) => {
|
|
21
|
+
if (run !== undefined)
|
|
22
|
+
await rm(runDir, { recursive: true, force: true });
|
|
23
|
+
throw err;
|
|
24
|
+
});
|
|
25
|
+
const made = { run: run !== undefined, data: data !== undefined };
|
|
26
|
+
return { runDir, secretsDir: join(runDir, 'secrets'), tmpDir: join(runDir, 'tmp'), made };
|
|
27
|
+
};
|
|
28
|
+
// Fresh secrets and tmp; the old lock beside data/{id} and a left-over run lock are cleared.
|
|
29
|
+
export const fillRun = async (run, spec) => {
|
|
30
|
+
for (const dir of [run.secretsDir, run.tmpDir]) {
|
|
31
|
+
await rm(dir, { recursive: true, force: true });
|
|
32
|
+
await mkdir(dir, { mode: 0o700 });
|
|
33
|
+
}
|
|
34
|
+
await clearOldLock(`${spec.dataDir}.lock`);
|
|
35
|
+
await clearRunLock(join(run.runDir, 'store.lock'), run.runDir);
|
|
36
|
+
for (const [name, value] of await declared(spec))
|
|
37
|
+
await writeFile(join(run.secretsDir, SecretNameSchema.parse(name)), value, { mode: 0o600 });
|
|
38
|
+
};
|
|
39
|
+
// A child that never reported its port: what this launch made goes; data/{id} only while empty.
|
|
40
|
+
export const undoRun = async ({ runDir, made }, dataDir) => {
|
|
41
|
+
if (made.run)
|
|
42
|
+
await rm(runDir, { recursive: true, force: true });
|
|
43
|
+
if (made.data)
|
|
44
|
+
await rmdir(dataDir).catch(() => undefined);
|
|
45
|
+
};
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type Seal } from './seal.js';
|
|
1
2
|
interface LaunchSpec {
|
|
2
3
|
id: string;
|
|
3
4
|
dir: string;
|
|
@@ -10,6 +11,7 @@ interface LaunchSpec {
|
|
|
10
11
|
export interface Exit {
|
|
11
12
|
code: number | null;
|
|
12
13
|
signal: string | null;
|
|
14
|
+
words?: string;
|
|
13
15
|
}
|
|
14
16
|
export interface Child {
|
|
15
17
|
port: number;
|
|
@@ -17,7 +19,11 @@ export interface Child {
|
|
|
17
19
|
exited: Promise<Exit>;
|
|
18
20
|
stop(): Promise<void>;
|
|
19
21
|
}
|
|
20
|
-
export type Launch = (spec: LaunchSpec) => Promise<Child
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
22
|
+
export type Launch = ((spec: LaunchSpec) => Promise<Child>) & {
|
|
23
|
+
clockRate?: number;
|
|
24
|
+
seal?: Seal;
|
|
25
|
+
node?: string;
|
|
26
|
+
};
|
|
27
|
+
export declare const childEnv: (spec: LaunchSpec, secretsDir: string, runDir?: string) => Record<string, string>;
|
|
28
|
+
export { lastWords } from './last-words.js';
|
|
29
|
+
export declare const forkLaunch: (main?: string, startMs?: number, rate?: number, node?: string) => Launch;
|
|
@@ -1,46 +1,28 @@
|
|
|
1
1
|
import { fork } from 'node:child_process';
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import { join } from 'node:path';
|
|
2
|
+
import { rm } from 'node:fs/promises';
|
|
3
|
+
import { dirname } from 'node:path';
|
|
5
4
|
import { fileURLToPath } from 'node:url';
|
|
6
|
-
import {
|
|
5
|
+
import { CLOCK_RATE_ENV, parseClockRate } from '../../worker/clock.js';
|
|
6
|
+
import { fillRun, makeRun, undoRun } from './child-files.js';
|
|
7
|
+
import { lastWords } from './last-words.js';
|
|
7
8
|
import { LIMITS } from './limits.js';
|
|
9
|
+
import { permissionFlag, sealFlags, sealOf } from './seal.js';
|
|
8
10
|
const HOST_MAIN = fileURLToPath(new URL('../main.js', import.meta.url));
|
|
9
11
|
const STOP_MS = 5_000;
|
|
10
12
|
const PASSED = ['PATH', 'HOME', 'TMPDIR', 'LANG', 'NODE_EXTRA_CA_CERTS'];
|
|
11
|
-
// Handed over as 0600 files in a 0700 folder, removed once the child has read them.
|
|
12
|
-
const secretFiles = async (spec) => {
|
|
13
|
-
const dir = await mkdtemp(join(tmpdir(), `agentage-${spec.id}-`));
|
|
14
|
-
for (const [name, value] of Object.entries(spec.secrets))
|
|
15
|
-
await writeFile(join(dir, SecretNameSchema.parse(name)), value, { mode: 0o600 });
|
|
16
|
-
return dir;
|
|
17
|
-
};
|
|
18
13
|
// What dist/host/main.js reads (docs/part-image.md), on a port the OS picks.
|
|
19
|
-
export const childEnv = (spec, secretsDir) => ({
|
|
14
|
+
export const childEnv = (spec, secretsDir, runDir) => ({
|
|
20
15
|
PORT: '0',
|
|
21
16
|
AGENTAGE_EXTENSION_DIR: spec.dir,
|
|
22
17
|
AGENTAGE_DATA_DIR: spec.dataDir,
|
|
23
18
|
AGENTAGE_SETTINGS: JSON.stringify(spec.settings),
|
|
24
19
|
AGENTAGE_SECRETS_DIR: secretsDir,
|
|
25
20
|
AGENTAGE_ORIGIN: spec.origin,
|
|
21
|
+
...(runDir && { AGENTAGE_RUN_DIR: runDir }),
|
|
26
22
|
...(spec.storeOpenMs && { AGENTAGE_STORE_OPEN_MS: String(spec.storeOpenMs) }),
|
|
27
23
|
});
|
|
24
|
+
export { lastWords } from './last-words.js';
|
|
28
25
|
const passedEnv = () => Object.fromEntries(PASSED.flatMap((k) => (process.env[k] ? [[k, process.env[k]]] : [])));
|
|
29
|
-
// The child's last stderr line, its msg when it is a log row: why it did not start.
|
|
30
|
-
const lastWords = (tail, how) => {
|
|
31
|
-
const lines = tail
|
|
32
|
-
.trim()
|
|
33
|
-
.split('\n')
|
|
34
|
-
.filter((l) => !/^Node\.js v\d/.test(l));
|
|
35
|
-
const line = lines.at(-1) ?? '';
|
|
36
|
-
try {
|
|
37
|
-
const msg = String(JSON.parse(line).msg ?? line);
|
|
38
|
-
return msg.replace(/^[A-Za-z]*Error: /, '');
|
|
39
|
-
}
|
|
40
|
-
catch {
|
|
41
|
-
return line || `exited with ${how.signal ? `signal ${how.signal}` : `code ${how.code}`}`;
|
|
42
|
-
}
|
|
43
|
-
};
|
|
44
26
|
const captured = (child) => {
|
|
45
27
|
let tail = '';
|
|
46
28
|
child.stdout?.pipe(process.stdout);
|
|
@@ -50,6 +32,17 @@ const captured = (child) => {
|
|
|
50
32
|
});
|
|
51
33
|
return () => tail;
|
|
52
34
|
};
|
|
35
|
+
// 'exit' can come before the last stderr chunk: wait for the stream end, at most 500 ms.
|
|
36
|
+
const flushed = (child) => new Promise((resolve) => {
|
|
37
|
+
if (!child.stderr || child.stderr.readableEnded)
|
|
38
|
+
return resolve();
|
|
39
|
+
child.stderr.once('end', resolve);
|
|
40
|
+
setTimeout(resolve, 500).unref();
|
|
41
|
+
});
|
|
42
|
+
const exitOf = (child, tail) => new Promise((resolve) => child.once('exit', (code, signal) => {
|
|
43
|
+
const how = { code, signal };
|
|
44
|
+
void flushed(child).then(() => resolve({ ...how, words: lastWords(tail(), how) }));
|
|
45
|
+
}));
|
|
53
46
|
const portOf = (msg) => {
|
|
54
47
|
const { type, port } = (msg ?? {});
|
|
55
48
|
return type === 'ready' && typeof port === 'number' ? port : undefined;
|
|
@@ -82,19 +75,52 @@ const stopOf = (child, exited) => async () => {
|
|
|
82
75
|
await exited;
|
|
83
76
|
clearTimeout(kill);
|
|
84
77
|
};
|
|
85
|
-
//
|
|
86
|
-
|
|
87
|
-
|
|
78
|
+
// The daemon's own node flags (a loader, --input-type) are never the child's; C2 where Node has --permission.
|
|
79
|
+
const execArgvOf = (node, main, spec, run) => {
|
|
80
|
+
if (!permissionFlag(node))
|
|
81
|
+
return [];
|
|
82
|
+
const configDir = dirname(dirname(spec.dataDir));
|
|
83
|
+
const { id, dir, dataDir } = spec;
|
|
84
|
+
return sealFlags({ id, main, dir, configDir, runDir: run.runDir, dataDir });
|
|
85
|
+
};
|
|
86
|
+
// The listed env of the daemon, then the child's own: TMPDIR in run/{id}, the test clock when not 1.
|
|
87
|
+
const envOf = (spec, run, clockRate) => ({
|
|
88
|
+
...passedEnv(),
|
|
89
|
+
...childEnv(spec, run.secretsDir, run.runDir),
|
|
90
|
+
TMPDIR: run.tmpDir,
|
|
91
|
+
...(clockRate === 1 ? {} : { [CLOCK_RATE_ENV]: String(clockRate) }),
|
|
92
|
+
});
|
|
93
|
+
const started = async (at, spec, run) => {
|
|
94
|
+
const execArgv = execArgvOf(at.node, at.main, spec, run);
|
|
95
|
+
await fillRun(run, spec);
|
|
88
96
|
const stdio = ['ignore', 'pipe', 'pipe', 'ipc'];
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
97
|
+
const child = fork(at.main, [], {
|
|
98
|
+
env: envOf(spec, run, at.clockRate),
|
|
99
|
+
execArgv,
|
|
100
|
+
stdio: [...stdio],
|
|
101
|
+
});
|
|
102
|
+
const tail = captured(child);
|
|
103
|
+
const exited = exitOf(child, tail);
|
|
104
|
+
const port = await readyOf(child, tail, at.startMs);
|
|
105
|
+
return { port, pid: child.pid ?? 0, exited, stop: stopOf(child, exited) };
|
|
106
|
+
};
|
|
107
|
+
// Anything before the port (files, the seal check, the start) undoes the folders this launch made.
|
|
108
|
+
const launchAt = (at) => async (spec) => {
|
|
109
|
+
const run = await makeRun(spec);
|
|
93
110
|
try {
|
|
94
|
-
|
|
95
|
-
|
|
111
|
+
return await started(at, spec, run);
|
|
112
|
+
}
|
|
113
|
+
catch (err) {
|
|
114
|
+
await undoRun(run, spec.dataDir);
|
|
115
|
+
throw err;
|
|
96
116
|
}
|
|
97
117
|
finally {
|
|
98
|
-
await rm(secretsDir, { recursive: true, force: true });
|
|
118
|
+
await rm(run.secretsDir, { recursive: true, force: true });
|
|
99
119
|
}
|
|
100
120
|
};
|
|
121
|
+
// One child process per extension on a port the OS picks; node: the version the seal gate reads.
|
|
122
|
+
export const forkLaunch = (main = HOST_MAIN, startMs = LIMITS.startMs, rate, node = process.versions.node) => {
|
|
123
|
+
const clockRate = parseClockRate(rate);
|
|
124
|
+
const launch = launchAt({ main, startMs, clockRate, node });
|
|
125
|
+
return Object.assign(launch, { clockRate, seal: sealOf(node), node });
|
|
126
|
+
};
|
|
@@ -5,10 +5,13 @@ interface DaemonFile {
|
|
|
5
5
|
version: string;
|
|
6
6
|
protocol: number;
|
|
7
7
|
startedBy: string;
|
|
8
|
+
hostToken: string;
|
|
8
9
|
}
|
|
9
10
|
export declare const writeDaemonFile: (configDir: string, file: DaemonFile) => Promise<void>;
|
|
10
11
|
export declare const removeDaemonFile: (configDir: string) => Promise<void>;
|
|
11
12
|
export declare const dataDirOf: (configDir: string, id: string) => string;
|
|
13
|
+
export declare const runDirOf: (configDir: string, id: string) => string;
|
|
14
|
+
export declare const clearRunDir: (configDir: string, id: string) => Promise<void>;
|
|
12
15
|
export declare const purgeData: (configDir: string, id: string) => Promise<void>;
|
|
13
16
|
type ValueKind = 'settings' | 'secrets';
|
|
14
17
|
type Values = Record<string, unknown>;
|
|
@@ -3,9 +3,13 @@ import { join } from 'node:path';
|
|
|
3
3
|
import { readJsonFile, withFileLock, writeJsonFile } from './json-file.js';
|
|
4
4
|
const DAEMON_FILE = 'daemon.json';
|
|
5
5
|
export const DAEMON_PROTOCOL = 1;
|
|
6
|
-
export const writeDaemonFile = (configDir, file) => writeJsonFile(join(configDir, DAEMON_FILE), file);
|
|
6
|
+
export const writeDaemonFile = (configDir, file) => writeJsonFile(join(configDir, DAEMON_FILE), file, 0o600);
|
|
7
7
|
export const removeDaemonFile = (configDir) => unlink(join(configDir, DAEMON_FILE)).catch(() => undefined);
|
|
8
8
|
export const dataDirOf = (configDir, id) => join(configDir, 'data', id);
|
|
9
|
+
// C2: the folder only this child reads and writes (secrets, TMPDIR, the store lock).
|
|
10
|
+
export const runDirOf = (configDir, id) => join(configDir, 'run', id);
|
|
11
|
+
// No user data in it: removed with the extension; each start makes its secrets and tmp anew.
|
|
12
|
+
export const clearRunDir = (configDir, id) => rm(runDirOf(configDir, id), { recursive: true, force: true });
|
|
9
13
|
export const purgeData = (configDir, id) => rm(dataDirOf(configDir, id), { recursive: true, force: true });
|
|
10
14
|
const fileOf = (configDir, kind) => join(configDir, `${kind}.json`);
|
|
11
15
|
export const readValues = async (configDir, kind, id) => (await readJsonFile(fileOf(configDir, kind), {}))[id] ?? {};
|
|
@@ -8,12 +8,15 @@ import { removeDaemonFile, writeDaemonFile, DAEMON_PROTOCOL } from './daemon-fil
|
|
|
8
8
|
import { assertNoOtherDaemon } from './daemon-owner.js';
|
|
9
9
|
import { bootInstallation, updateInstallation } from './installation.js';
|
|
10
10
|
import {} from './entries.js';
|
|
11
|
+
import { newHostToken } from './host-token.js';
|
|
12
|
+
import { sealOffReason } from './seal.js';
|
|
11
13
|
import { limitsOf } from './limits.js';
|
|
12
14
|
import { pendingChanges } from './pending.js';
|
|
13
15
|
import { serialQueue } from './queue.js';
|
|
14
16
|
import { launchUnlessStopping, stopAll, stoppingOf } from './stopping.js';
|
|
15
17
|
import { daemonApp } from './routes.js';
|
|
16
18
|
import { runInstaller } from './installer-call.js';
|
|
19
|
+
import { repairReload } from './reload-marker.js';
|
|
17
20
|
import { halt, startEntry } from './supervisor.js';
|
|
18
21
|
export const DAEMON_PORT = 4243;
|
|
19
22
|
const warnOf = (deps) => (err) => deps.log.warn('a daemon file was not cleaned at boot', { reason: err.message });
|
|
@@ -42,6 +45,8 @@ const boot = async (deps, entries) => {
|
|
|
42
45
|
const off = all.filter((e) => e.state === 'disabled');
|
|
43
46
|
const on = all.filter((e) => e.state !== 'disabled');
|
|
44
47
|
const ordered = [...on.filter((e) => e.install.source), ...on.filter((e) => !e.install.source)];
|
|
48
|
+
for (const entry of all)
|
|
49
|
+
await repairReload(deps.configDir, entry, deps.log).catch(warnOf(deps));
|
|
45
50
|
for (const entry of ordered)
|
|
46
51
|
await startEntry(deps, entry);
|
|
47
52
|
for (const entry of off)
|
|
@@ -58,13 +63,20 @@ const stopper = (server, entries, deps, life) => {
|
|
|
58
63
|
};
|
|
59
64
|
return () => (stopped ??= stop());
|
|
60
65
|
};
|
|
61
|
-
// C4: how a client finds this daemon.
|
|
62
|
-
const announce = ({ configDir, version, startedBy }, port) => writeDaemonFile(configDir, {
|
|
66
|
+
// C4: how a client finds this daemon; D11: the host token, only in this 0600 file.
|
|
67
|
+
const announce = ({ configDir, version, startedBy }, port, hostToken) => writeDaemonFile(configDir, {
|
|
63
68
|
pid: process.pid,
|
|
64
69
|
port,
|
|
65
70
|
version,
|
|
66
71
|
protocol: DAEMON_PROTOCOL,
|
|
67
72
|
startedBy,
|
|
73
|
+
hostToken,
|
|
74
|
+
});
|
|
75
|
+
// One source: the launch that forks the children (its test clock, its seal).
|
|
76
|
+
const launchMarks = (launch) => ({
|
|
77
|
+
...(launch.clockRate && launch.clockRate !== 1 && { clockRate: launch.clockRate }),
|
|
78
|
+
...(launch.seal && { seal: launch.seal }),
|
|
79
|
+
...(launch.seal === 'off' && { sealError: sealOffReason(launch.node ?? process.versions.node) }),
|
|
68
80
|
});
|
|
69
81
|
const depsOf = (opts, launch, origin, stopping) => ({
|
|
70
82
|
configDir: opts.configDir,
|
|
@@ -87,13 +99,15 @@ export const startDaemon = async (opts, launch) => {
|
|
|
87
99
|
const life = new AbortController();
|
|
88
100
|
const deps = depsOf(opts, launch, () => `http://127.0.0.1:${port}`, stoppingOf(life.signal));
|
|
89
101
|
const { entries, ...file } = await loadEntries(deps);
|
|
90
|
-
const
|
|
91
|
-
const
|
|
102
|
+
const self = { version: opts.version, pid: process.pid, protocol: DAEMON_PROTOCOL };
|
|
103
|
+
const info = { ...launchMarks(launch), ...self, ...file };
|
|
104
|
+
const hostToken = newHostToken();
|
|
105
|
+
const app = daemonApp(deps, entries, () => port, info, hostToken);
|
|
92
106
|
const server = await listen(app, port, '127.0.0.1');
|
|
93
107
|
port = server.address().port;
|
|
94
108
|
const stop = stopper(server, entries, deps, life);
|
|
95
109
|
try {
|
|
96
|
-
await announce(opts, port);
|
|
110
|
+
await announce(opts, port, hostToken);
|
|
97
111
|
await deps.queue(() => boot(deps, entries));
|
|
98
112
|
}
|
|
99
113
|
catch (err) {
|
|
@@ -103,4 +117,5 @@ export const startDaemon = async (opts, launch) => {
|
|
|
103
117
|
return { port, stop };
|
|
104
118
|
};
|
|
105
119
|
// One daemon on 127.0.0.1, one child process for each extension (D1).
|
|
106
|
-
|
|
120
|
+
// A bad clockRate rejects the promise, like every other refusal of this function.
|
|
121
|
+
export const createDaemon = async (opts) => startDaemon(opts, forkLaunch(undefined, opts.startMs, opts.clockRate));
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { retire } from './lane.js';
|
|
2
|
+
import { cancelRestart } from './restart.js';
|
|
3
|
+
import {} from './supervisor.js';
|
|
4
|
+
// New requests of the extension wait here (the proxy gives up after gateMs) until release.
|
|
5
|
+
export const hold = (entry) => {
|
|
6
|
+
let release = () => undefined;
|
|
7
|
+
entry.gate = new Promise((resolve) => (release = resolve));
|
|
8
|
+
return () => {
|
|
9
|
+
entry.gate = undefined;
|
|
10
|
+
release();
|
|
11
|
+
};
|
|
12
|
+
};
|
|
13
|
+
// Detached first, so its exit is not a failure; then drained and stopped.
|
|
14
|
+
export const halt = async (entry, drainMs) => {
|
|
15
|
+
cancelRestart(entry);
|
|
16
|
+
const lane = entry.lane;
|
|
17
|
+
entry.lane = undefined;
|
|
18
|
+
await retire(lane, drainMs);
|
|
19
|
+
};
|
|
@@ -1,2 +1,3 @@
|
|
|
1
1
|
import { type RequestHandler } from 'express';
|
|
2
|
-
export declare const localOnly: (port?: () => number) => RequestHandler;
|
|
2
|
+
export declare const localOnly: (port?: () => number, more?: number[]) => RequestHandler;
|
|
3
|
+
export declare const loopbackPorts: (origin: string | undefined) => number[];
|
|
@@ -2,10 +2,11 @@ import {} from 'express';
|
|
|
2
2
|
import { fail } from '../../envelope/envelope.js';
|
|
3
3
|
// What a browser says of a request another site started (an <img>, a link, a form).
|
|
4
4
|
const FOREIGN = ['cross-site', 'same-site'];
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
const
|
|
5
|
+
const hostsAt = (port) => [`127.0.0.1:${port}`, `localhost:${port}`];
|
|
6
|
+
// Only this machine by name (DNS rebinding, a cross-site form); more: other local ports, as the daemon's.
|
|
7
|
+
export const localOnly = (port, more = []) => (req, _res, next) => {
|
|
8
|
+
const at = port?.() ?? req.socket.localPort ?? 0;
|
|
9
|
+
const hosts = [at, ...more].flatMap(hostsAt);
|
|
9
10
|
const origin = req.get('origin');
|
|
10
11
|
const hostOk = hosts.includes(req.get('host') ?? '');
|
|
11
12
|
const originOk = origin === undefined || hosts.some((host) => origin === `http://${host}`);
|
|
@@ -14,3 +15,14 @@ export const localOnly = (port) => (req, _res, next) => {
|
|
|
14
15
|
throw fail('FORBIDDEN', 'Only this machine may call this server');
|
|
15
16
|
next();
|
|
16
17
|
};
|
|
18
|
+
// The port of a loopback origin (the daemon's AGENTAGE_ORIGIN); none for any other origin.
|
|
19
|
+
export const loopbackPorts = (origin) => {
|
|
20
|
+
try {
|
|
21
|
+
const url = new URL(origin ?? '');
|
|
22
|
+
const local = url.protocol === 'http:' && ['127.0.0.1', 'localhost'].includes(url.hostname);
|
|
23
|
+
return local && url.port ? [Number(url.port)] : [];
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
return [];
|
|
27
|
+
}
|
|
28
|
+
};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { type Express } from 'express';
|
|
2
|
+
import { type Entries } from './entries.js';
|
|
3
|
+
import { type Seal } from './seal.js';
|
|
4
|
+
import { type SupervisorDeps } from './supervisor.js';
|
|
5
|
+
export interface DaemonInfo {
|
|
6
|
+
version: string;
|
|
7
|
+
pid: number;
|
|
8
|
+
protocol: number;
|
|
9
|
+
invalid: boolean;
|
|
10
|
+
unreadable?: string;
|
|
11
|
+
notJson?: boolean;
|
|
12
|
+
clockRate?: number;
|
|
13
|
+
seal?: Seal;
|
|
14
|
+
sealError?: string;
|
|
15
|
+
}
|
|
16
|
+
export declare const HOST_DISCOVERY_PATH = "/.well-known/agentage-host.json";
|
|
17
|
+
export declare const healthRoutes: (app: Express, deps: SupervisorDeps, entries: Entries, info: DaemonInfo) => void;
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import {} from 'express';
|
|
2
|
+
import { hostParts } from '../../manifest/parts.js';
|
|
3
|
+
import { readManifest } from '../../manifest/read-manifest.js';
|
|
4
|
+
import { summary } from './entries.js';
|
|
5
|
+
import { restartsOf } from './restart.js';
|
|
6
|
+
import {} from './seal.js';
|
|
7
|
+
import {} from './supervisor.js';
|
|
8
|
+
// What /health says of the daemon itself: the values of daemon.json, so a client can prove it.
|
|
9
|
+
const DAEMON_SERVICE = 'agentage-daemon';
|
|
10
|
+
// Read at each call: a reload can change the package in its folder.
|
|
11
|
+
const partsOf = async ({ dir }) => dir ? readManifest(dir).then(hostParts, () => []) : [];
|
|
12
|
+
const reported = async (entry, info) => ({
|
|
13
|
+
...summary(entry),
|
|
14
|
+
parts: await partsOf(entry),
|
|
15
|
+
seal: info.seal ?? 'off',
|
|
16
|
+
restarts: restartsOf(entry),
|
|
17
|
+
});
|
|
18
|
+
const installationOf = ({ invalid, unreadable, notJson }) => {
|
|
19
|
+
if (unreadable)
|
|
20
|
+
return { installation: 'unreadable', installationError: unreadable };
|
|
21
|
+
return invalid || notJson ? { installation: 'invalid' } : {};
|
|
22
|
+
};
|
|
23
|
+
const sealMark = ({ seal, sealError }) => seal === 'off' ? { seal, sealError: sealError ?? 'seal off' } : {};
|
|
24
|
+
const statusOf = (deps, entries, info) => {
|
|
25
|
+
const settled = [...entries.values()].every((e) => ['running', 'disabled'].includes(e.state));
|
|
26
|
+
const clean = !info.invalid && !info.unreadable && !info.notJson && info.seal !== 'off';
|
|
27
|
+
return settled && !deps.unsynced.size && clean ? 'ok' : 'degraded';
|
|
28
|
+
};
|
|
29
|
+
const healthOf = async (deps, entries, info) => {
|
|
30
|
+
const self = { service: DAEMON_SERVICE, pid: info.pid, protocol: info.protocol };
|
|
31
|
+
const extensions = await Promise.all([...entries.values()].map((e) => reported(e, info)));
|
|
32
|
+
const changing = deps.pending.list();
|
|
33
|
+
const marks = {
|
|
34
|
+
...(changing.length && { pending: changing }),
|
|
35
|
+
...(info.clockRate && { clockRate: info.clockRate }),
|
|
36
|
+
...(deps.unsynced.size && { unsynced: [...deps.unsynced] }),
|
|
37
|
+
...installationOf(info),
|
|
38
|
+
...sealMark(info),
|
|
39
|
+
};
|
|
40
|
+
const status = statusOf(deps, entries, info);
|
|
41
|
+
return { status, version: info.version, ...self, extensions, ...marks };
|
|
42
|
+
};
|
|
43
|
+
// C10 (D10): where each running extension answers, and its parts; anonymous, bare JSON.
|
|
44
|
+
const discoveryOf = async (entries) => {
|
|
45
|
+
const running = [...entries.values()].filter((e) => e.state === 'running');
|
|
46
|
+
const listed = running.map(async (e) => ({
|
|
47
|
+
id: e.id,
|
|
48
|
+
version: e.version,
|
|
49
|
+
parts: await partsOf(e),
|
|
50
|
+
}));
|
|
51
|
+
return { host: 'local', extensions: await Promise.all(listed) };
|
|
52
|
+
};
|
|
53
|
+
export const HOST_DISCOVERY_PATH = '/.well-known/agentage-host.json';
|
|
54
|
+
export const healthRoutes = (app, deps, entries, info) => {
|
|
55
|
+
app.get('/health', async (_req, res) => {
|
|
56
|
+
res.set('Cache-Control', 'no-store').json(await healthOf(deps, entries, info));
|
|
57
|
+
});
|
|
58
|
+
app.get(HOST_DISCOVERY_PATH, async (_req, res) => {
|
|
59
|
+
res.set('Cache-Control', 'no-store').json(await discoveryOf(entries));
|
|
60
|
+
});
|
|
61
|
+
};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { type IncomingHttpHeaders } from 'node:http';
|
|
2
|
+
import { type RequestHandler } from 'express';
|
|
3
|
+
export declare const newHostToken: () => string;
|
|
4
|
+
export declare const carriesHostToken: (headers: IncomingHttpHeaders, token: string) => boolean;
|
|
5
|
+
export declare const NO_TOKEN = "host token required: this cli is older than the daemon, update @agentage/cli or run \"agentage daemon restart\"";
|
|
6
|
+
export declare const requireHostToken: (token: string) => RequestHandler;
|