@agentage/extension 0.12.3 → 0.13.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/dist/api/openapi-doc.js +2 -1
- package/dist/api/routes.js +1 -1
- package/dist/context/context.d.ts +1 -0
- package/dist/context/context.js +3 -3
- package/dist/context/secrets.d.ts +1 -0
- package/dist/context/secrets.js +7 -5
- package/dist/context/settings.d.ts +4 -0
- package/dist/context/settings.js +6 -5
- package/dist/discovery/discovery.schema.js +8 -2
- package/dist/discovery/openapi.d.ts +2 -1
- package/dist/discovery/openapi.js +3 -1
- package/dist/host/daemon/child.d.ts +21 -0
- package/dist/host/daemon/child.js +92 -0
- package/dist/host/daemon/daemon-files.d.ts +19 -0
- package/dist/host/daemon/daemon-files.js +23 -0
- package/dist/host/daemon/daemon.d.ts +18 -0
- package/dist/host/daemon/daemon.js +84 -0
- package/dist/host/daemon/guard.d.ts +2 -0
- package/dist/host/daemon/guard.js +15 -0
- package/dist/host/daemon/installation.d.ts +23 -0
- package/dist/host/daemon/installation.js +48 -0
- package/dist/host/daemon/installer-call.d.ts +7 -0
- package/dist/host/daemon/installer-call.js +22 -0
- package/dist/host/daemon/json-file.d.ts +3 -0
- package/dist/host/daemon/json-file.js +51 -0
- package/dist/host/daemon/lane.d.ts +11 -0
- package/dist/host/daemon/lane.js +29 -0
- package/dist/host/daemon/ops.d.ts +36 -0
- package/dist/host/daemon/ops.js +149 -0
- package/dist/host/daemon/proxy.d.ts +5 -0
- package/dist/host/daemon/proxy.js +67 -0
- package/dist/host/daemon/queue.d.ts +2 -0
- package/dist/host/daemon/queue.js +8 -0
- package/dist/host/daemon/routes.d.ts +11 -0
- package/dist/host/daemon/routes.js +48 -0
- package/dist/host/daemon/secret-names.d.ts +1 -0
- package/dist/host/daemon/secret-names.js +14 -0
- package/dist/host/daemon/setting-values.d.ts +1 -0
- package/dist/host/daemon/setting-values.js +26 -0
- package/dist/host/daemon/supervisor.d.ts +52 -0
- package/dist/host/daemon/supervisor.js +116 -0
- package/dist/host/data-lock.d.ts +2 -0
- package/dist/host/data-lock.js +81 -0
- package/dist/host/host-env.d.ts +17 -0
- package/dist/host/host-env.js +36 -0
- package/dist/host/host-extension.d.ts +25 -0
- package/dist/host/host-extension.js +86 -0
- package/dist/host/host-store.d.ts +4 -0
- package/dist/host/host-store.js +35 -0
- package/dist/host/index.d.ts +3 -0
- package/dist/host/index.js +3 -0
- package/dist/host/main.d.ts +2 -0
- package/dist/host/main.js +10 -0
- package/dist/host/serve-host.d.ts +16 -0
- package/dist/host/serve-host.js +61 -0
- package/dist/runtime/part-runners.d.ts +1 -0
- package/dist/runtime/part-runners.js +10 -1
- package/dist/runtime/run-part.js +2 -0
- package/dist/server/app.d.ts +4 -0
- package/dist/server/app.js +28 -18
- package/dist/server/request-line.d.ts +1 -1
- package/dist/server/request-line.js +4 -4
- package/dist/server/serve.js +11 -3
- package/dist/store/pglite-store.d.ts +25 -0
- package/dist/store/pglite-store.js +59 -0
- package/dist/store/test-store.d.ts +2 -3
- package/dist/store/test-store.js +3 -38
- package/dist/testing/test-server.d.ts +2 -0
- package/dist/testing/test-server.js +1 -1
- package/dist/tool/record-extras.js +2 -2
- package/dist/tool/rules/surface.js +6 -6
- package/dist/tool/up/gateway.d.ts +6 -2
- package/dist/tool/up/gateway.js +10 -7
- package/dist/tool/up/token.js +1 -1
- package/dist/tool/up/up.js +2 -2
- package/dist/vendor/logs/events-client.js +1 -1
- package/package.json +5 -1
- package/schemas/extension-discovery.schema.json +1 -1
- package/schemas/extension-record.schema.json +1 -1
package/dist/api/openapi-doc.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { scopeOf } from '../auth/token-check.js';
|
|
2
|
+
import { apiPrefix } from '../discovery/openapi.js';
|
|
2
3
|
import {} from '../envelope/codes.js';
|
|
3
4
|
import { ErrorEnvelopeSchema } from '../envelope/envelope.schema.js';
|
|
4
5
|
import {} from '../manifest/manifest.schema.js';
|
|
@@ -94,7 +95,7 @@ export const generatedOpenapi = (pkg, routes) => {
|
|
|
94
95
|
const { id } = pkg.agentage;
|
|
95
96
|
const paths = {};
|
|
96
97
|
for (const entry of routes) {
|
|
97
|
-
const at =
|
|
98
|
+
const at = `${apiPrefix(id)}${entry.path}`;
|
|
98
99
|
paths[at] = { ...paths[at], [entry.method]: operation(id, entry) };
|
|
99
100
|
}
|
|
100
101
|
return {
|
package/dist/api/routes.js
CHANGED
|
@@ -9,7 +9,7 @@ const problemOf = (routes, { method, path, spec }) => {
|
|
|
9
9
|
if (!ROUTE_METHODS.includes(method))
|
|
10
10
|
return `method ${String(method)}: one of get, post, put, patch, delete`;
|
|
11
11
|
if (!PATH.test(path))
|
|
12
|
-
return 'path: /segments and {param} segments under /api/
|
|
12
|
+
return 'path: /segments and {param} segments under /api/{id}';
|
|
13
13
|
if (routes.some((r) => r.method === method && r.path === path))
|
|
14
14
|
return 'is registered twice';
|
|
15
15
|
if (!spec.summary)
|
package/dist/context/context.js
CHANGED
|
@@ -15,12 +15,12 @@ export const healthRegistrar = (checks) => (name, check) => {
|
|
|
15
15
|
checks[name] = check;
|
|
16
16
|
};
|
|
17
17
|
// Inside a request: after its answer (server/request-line.ts); outside one: now.
|
|
18
|
-
const exitAfterAnswer = () => {
|
|
18
|
+
const exitAfterAnswer = (onExit = sigtermOnce) => () => {
|
|
19
19
|
const scope = requestScope.getStore();
|
|
20
20
|
if (scope)
|
|
21
21
|
scope.exit = true;
|
|
22
22
|
else
|
|
23
|
-
|
|
23
|
+
onExit();
|
|
24
24
|
};
|
|
25
25
|
// ctx.store is always there; without a store part in the manifest it says so on first use.
|
|
26
26
|
export const NO_STORE = {
|
|
@@ -55,7 +55,7 @@ export const createContext = (input) => {
|
|
|
55
55
|
store: store ?? NO_STORE,
|
|
56
56
|
secrets,
|
|
57
57
|
platform,
|
|
58
|
-
exit: exitAfterAnswer,
|
|
58
|
+
exit: exitAfterAnswer(input.onExit),
|
|
59
59
|
health: healthRegistrar(input.checks ?? {}),
|
|
60
60
|
});
|
|
61
61
|
};
|
|
@@ -3,5 +3,6 @@ import { type ImagePartKind as Part } from '../manifest/primitives.schema.js';
|
|
|
3
3
|
export interface Secrets {
|
|
4
4
|
}
|
|
5
5
|
export declare const SECRETS_DIR = "/run/secrets";
|
|
6
|
+
export declare const secretsFrom: (pkg: ExtensionPackage, part: Part, value: (name: string) => Promise<string>) => Promise<Readonly<Record<string, string>>>;
|
|
6
7
|
export declare const readSecrets: (pkg: ExtensionPackage, part: Part, dir: string) => Promise<Readonly<Record<string, string>>>;
|
|
7
8
|
export declare const withAbsent: (values: Record<string, string>, part: Part, pkg?: ExtensionPackage) => Record<string, string>;
|
package/dist/context/secrets.js
CHANGED
|
@@ -10,11 +10,11 @@ const valueOf = (file, refused) => readFile(file, 'utf8').then((text) => text.re
|
|
|
10
10
|
return '';
|
|
11
11
|
throw new Error(`${refused} cannot be read: ${err.code ?? 'unknown'}`);
|
|
12
12
|
});
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
const refused = (
|
|
17
|
-
const read =
|
|
13
|
+
const refusal = (part) => (name) => `${part} refused to start: secret ${name}`;
|
|
14
|
+
// Each name the part mounts, from value(name); an empty value stops the part, named, never valued.
|
|
15
|
+
export const secretsFrom = async (pkg, part, value) => {
|
|
16
|
+
const refused = refusal(part);
|
|
17
|
+
const read = mountedIn(pkg, part).map(async (name) => [name, await value(name)]);
|
|
18
18
|
const pairs = await Promise.all(read);
|
|
19
19
|
const missing = pairs.find(([, value]) => value === '');
|
|
20
20
|
if (missing)
|
|
@@ -22,6 +22,8 @@ export const readSecrets = async (pkg, part, dir) => {
|
|
|
22
22
|
const secrets = Object.fromEntries(pairs.map(([name, value]) => [camelName(name), value]));
|
|
23
23
|
return Object.freeze(withAbsent(secrets, part, pkg));
|
|
24
24
|
};
|
|
25
|
+
// Each declared name from its mounted file; a missing or empty file stops the part, named, never valued.
|
|
26
|
+
export const readSecrets = (pkg, part, dir) => secretsFrom(pkg, part, (name) => valueOf(join(dir, name), refusal(part)(name)));
|
|
25
27
|
// A secret of other parts throws on read, never reads empty; spread and keys skip it.
|
|
26
28
|
export const withAbsent = (values, part, pkg) => {
|
|
27
29
|
for (const name of unmountedIn(pkg, part))
|
|
@@ -2,4 +2,8 @@ import { type Log } from '../log/log.js';
|
|
|
2
2
|
import { type ExtensionPackage } from '../manifest/manifest.schema.js';
|
|
3
3
|
import { type Env } from '../runtime/build-info.js';
|
|
4
4
|
import { type SettingValue } from './context.js';
|
|
5
|
+
export type Setting = NonNullable<ExtensionPackage['agentage']['settings']>[string];
|
|
6
|
+
export declare const fits: (setting: Setting, value: unknown) => value is SettingValue;
|
|
7
|
+
export declare const parseObject: (text: string) => Record<string, unknown>;
|
|
8
|
+
export declare const settingsOf: (pkg: ExtensionPackage, given: Record<string, unknown>, log: Log) => Record<string, SettingValue>;
|
|
5
9
|
export declare const settingsFromEnv: (pkg: ExtensionPackage, env: Env, log: Log) => Record<string, SettingValue>;
|
package/dist/context/settings.js
CHANGED
|
@@ -2,22 +2,21 @@ import {} from '../log/log.js';
|
|
|
2
2
|
import {} from '../manifest/manifest.schema.js';
|
|
3
3
|
import {} from '../runtime/build-info.js';
|
|
4
4
|
import { settingDefaults } from './context.js';
|
|
5
|
-
const fits = (setting, value) => {
|
|
5
|
+
export const fits = (setting, value) => {
|
|
6
6
|
if (setting.type === 'integer' ? !Number.isInteger(value) : typeof value !== setting.type)
|
|
7
7
|
return false;
|
|
8
8
|
return !setting.enum || setting.enum.includes(String(value));
|
|
9
9
|
};
|
|
10
|
-
const parseObject = (text) => {
|
|
10
|
+
export const parseObject = (text) => {
|
|
11
11
|
const value = JSON.parse(text);
|
|
12
12
|
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
|
13
13
|
throw new Error('AGENTAGE_SETTINGS is not a JSON object');
|
|
14
14
|
}
|
|
15
15
|
return value;
|
|
16
16
|
};
|
|
17
|
-
// The host's values
|
|
18
|
-
export const
|
|
17
|
+
// The host's values over the defaults; a wrong type stops the start.
|
|
18
|
+
export const settingsOf = (pkg, given, log) => {
|
|
19
19
|
const declared = pkg.agentage.settings ?? {};
|
|
20
|
-
const given = env['AGENTAGE_SETTINGS'] ? parseObject(env['AGENTAGE_SETTINGS']) : {};
|
|
21
20
|
const values = settingDefaults(pkg);
|
|
22
21
|
for (const [key, value] of Object.entries(given)) {
|
|
23
22
|
const setting = declared[key];
|
|
@@ -30,3 +29,5 @@ export const settingsFromEnv = (pkg, env, log) => {
|
|
|
30
29
|
}
|
|
31
30
|
return values;
|
|
32
31
|
};
|
|
32
|
+
// The values as AGENTAGE_SETTINGS (JSON) of the image gives them.
|
|
33
|
+
export const settingsFromEnv = (pkg, env, log) => settingsOf(pkg, env['AGENTAGE_SETTINGS'] ? parseObject(env['AGENTAGE_SETTINGS']) : {}, log);
|
|
@@ -39,9 +39,10 @@ const recordShape = {
|
|
|
39
39
|
commit: CommitSchema,
|
|
40
40
|
buildTime: z.iso.datetime(),
|
|
41
41
|
parts: PartsRecordSchema,
|
|
42
|
+
// /api/v{N}: an extension still on a kit before 0.13, read by a newer one; it goes in phase 4.
|
|
42
43
|
openapi: z
|
|
43
44
|
.string()
|
|
44
|
-
.regex(/^\/api\/v[
|
|
45
|
+
.regex(/^\/api\/(?:v[0-9]+|[a-z][a-z0-9-]*)\/openapi\.json$/)
|
|
45
46
|
.optional(),
|
|
46
47
|
tools: z.array(ToolRecordSchema).min(1).optional(),
|
|
47
48
|
widgets: z.array(WidgetSchema).min(1).optional(),
|
|
@@ -52,6 +53,9 @@ const imagesNameTheirExtension = (doc) => IMAGE_PART_KINDS.every((kind) => {
|
|
|
52
53
|
return image === undefined || image.includes(`/${doc.id}-${kind}@sha256:`);
|
|
53
54
|
});
|
|
54
55
|
const IMAGE_RULE = { message: 'every image is {id}-{part}', path: ['parts'] };
|
|
56
|
+
// The api prefix is /api/{id}, or the old /api/v{N}: never another extension's id.
|
|
57
|
+
const openapiNamesItsExtension = ({ id, openapi }) => !openapi || /^\/api\/v[0-9]+\//.test(openapi) || openapi === `/api/${id}/openapi.json`;
|
|
58
|
+
const OPENAPI_RULE = { message: 'openapi is /api/{id}/openapi.json', path: ['openapi'] };
|
|
55
59
|
// A scoped name lives only in secretParts, so an estate that does not read it mounts nothing.
|
|
56
60
|
const scoped = (name) => `secret ${name}: one or more parts, none repeated, and never also in secrets`;
|
|
57
61
|
// The build record: written by `build --push` into the package and the release asset; no host.
|
|
@@ -63,6 +67,7 @@ export const ExtensionRecordSchema = z
|
|
|
63
67
|
secretParts: z.record(SecretNameSchema, z.array(SecretPartSchema)).optional(),
|
|
64
68
|
})
|
|
65
69
|
.refine(imagesNameTheirExtension, IMAGE_RULE)
|
|
70
|
+
.refine(openapiNamesItsExtension, OPENAPI_RULE)
|
|
66
71
|
.superRefine((doc, ctx) => {
|
|
67
72
|
for (const [name, parts] of Object.entries(doc.secretParts ?? {}))
|
|
68
73
|
if (!parts.length || new Set(parts).size !== parts.length || doc.secrets?.includes(name))
|
|
@@ -71,4 +76,5 @@ export const ExtensionRecordSchema = z
|
|
|
71
76
|
// What a deployment serves at /.well-known/agentage-extension.json: the record plus its host.
|
|
72
77
|
export const DiscoveryDocumentSchema = z
|
|
73
78
|
.strictObject({ ...recordShape, host: OriginSchema })
|
|
74
|
-
.refine(imagesNameTheirExtension, IMAGE_RULE)
|
|
79
|
+
.refine(imagesNameTheirExtension, IMAGE_RULE)
|
|
80
|
+
.refine(openapiNamesItsExtension, OPENAPI_RULE);
|
|
@@ -1,3 +1,4 @@
|
|
|
1
1
|
export declare const OPENAPI_FILE = "openapi.json";
|
|
2
|
-
export declare const
|
|
2
|
+
export declare const apiPrefix: (id: string) => string;
|
|
3
|
+
export declare const openapiPath: (id: string) => string;
|
|
3
4
|
export declare const readOpenapi: (dir: string) => Promise<Record<string, unknown> | null>;
|
|
@@ -2,7 +2,9 @@ import { join } from 'node:path';
|
|
|
2
2
|
import { z } from 'zod';
|
|
3
3
|
import { readJsonIfExists } from '../manifest/read-manifest.js';
|
|
4
4
|
export const OPENAPI_FILE = 'openapi.json';
|
|
5
|
-
|
|
5
|
+
// The api part's URL prefix: the extension id, no version (D3 of S1.1.1).
|
|
6
|
+
export const apiPrefix = (id) => `/api/${id}`;
|
|
7
|
+
export const openapiPath = (id) => `${apiPrefix(id)}/openapi.json`;
|
|
6
8
|
const OpenapiSchema = z.looseObject({
|
|
7
9
|
openapi: z.string().regex(/^3\.1\.[0-9]+$/, { message: 'OpenAPI 3.1' }),
|
|
8
10
|
paths: z.record(z.string(), z.unknown()),
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
export interface LaunchSpec {
|
|
2
|
+
id: string;
|
|
3
|
+
dir: string;
|
|
4
|
+
dataDir: string;
|
|
5
|
+
settings: Record<string, unknown>;
|
|
6
|
+
secrets: Record<string, string>;
|
|
7
|
+
origin: string;
|
|
8
|
+
}
|
|
9
|
+
export interface Exit {
|
|
10
|
+
code: number | null;
|
|
11
|
+
signal: string | null;
|
|
12
|
+
}
|
|
13
|
+
export interface Child {
|
|
14
|
+
port: number;
|
|
15
|
+
pid: number;
|
|
16
|
+
exited: Promise<Exit>;
|
|
17
|
+
stop(): Promise<void>;
|
|
18
|
+
}
|
|
19
|
+
export type Launch = (spec: LaunchSpec) => Promise<Child>;
|
|
20
|
+
export declare const HOST_MAIN: string;
|
|
21
|
+
export declare const forkLaunch: (main?: string) => Launch;
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { fork } from 'node:child_process';
|
|
2
|
+
import { mkdtemp, rm, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
import { SecretNameSchema } from '../../manifest/primitives.schema.js';
|
|
7
|
+
export const HOST_MAIN = fileURLToPath(new URL('../main.js', import.meta.url));
|
|
8
|
+
const START_MS = 60_000;
|
|
9
|
+
const STOP_MS = 5_000;
|
|
10
|
+
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
|
+
const envOf = (spec, secretsDir) => ({
|
|
19
|
+
...Object.fromEntries(PASSED.flatMap((k) => (process.env[k] ? [[k, process.env[k]]] : []))),
|
|
20
|
+
PORT: '0',
|
|
21
|
+
AGENTAGE_EXTENSION_DIR: spec.dir,
|
|
22
|
+
AGENTAGE_DATA_DIR: spec.dataDir,
|
|
23
|
+
AGENTAGE_SETTINGS: JSON.stringify(spec.settings),
|
|
24
|
+
AGENTAGE_SECRETS_DIR: secretsDir,
|
|
25
|
+
AGENTAGE_ORIGIN: spec.origin,
|
|
26
|
+
});
|
|
27
|
+
// The child's last stderr line, its msg when it is a log row: why it did not start.
|
|
28
|
+
const lastWords = (tail, code) => {
|
|
29
|
+
const lines = tail
|
|
30
|
+
.trim()
|
|
31
|
+
.split('\n')
|
|
32
|
+
.filter((l) => !/^Node\.js v\d/.test(l));
|
|
33
|
+
const line = lines.at(-1) ?? '';
|
|
34
|
+
try {
|
|
35
|
+
const msg = String(JSON.parse(line).msg ?? line);
|
|
36
|
+
return msg.replace(/^[A-Za-z]*Error: /, '');
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
return line || `exited with code ${code}`;
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
const captured = (child) => {
|
|
43
|
+
let tail = '';
|
|
44
|
+
child.stdout?.pipe(process.stdout);
|
|
45
|
+
child.stderr?.on('data', (chunk) => {
|
|
46
|
+
process.stderr.write(chunk);
|
|
47
|
+
tail = (tail + chunk.toString()).slice(-4000);
|
|
48
|
+
});
|
|
49
|
+
return () => tail;
|
|
50
|
+
};
|
|
51
|
+
const portOf = (msg) => {
|
|
52
|
+
const { type, port } = (msg ?? {});
|
|
53
|
+
return type === 'ready' && typeof port === 'number' ? port : undefined;
|
|
54
|
+
};
|
|
55
|
+
// The port the child bound, or why it exited first; a child silent for START_MS is killed.
|
|
56
|
+
const readyOf = (child, tail) => new Promise((resolve, reject) => {
|
|
57
|
+
const timer = setTimeout(() => child.kill('SIGKILL'), START_MS);
|
|
58
|
+
const settle = (fn) => {
|
|
59
|
+
clearTimeout(timer);
|
|
60
|
+
fn();
|
|
61
|
+
};
|
|
62
|
+
child.on('message', (msg) => {
|
|
63
|
+
const port = portOf(msg);
|
|
64
|
+
if (port)
|
|
65
|
+
settle(() => resolve(port));
|
|
66
|
+
});
|
|
67
|
+
child.once('exit', (code) => settle(() => reject(new Error(lastWords(tail(), code)))));
|
|
68
|
+
});
|
|
69
|
+
// SIGTERM drains; a child still there after STOP_MS (a request that never ends) gets SIGKILL.
|
|
70
|
+
const stopOf = (child, exited) => async () => {
|
|
71
|
+
if (child.exitCode === null && child.signalCode === null)
|
|
72
|
+
child.kill('SIGTERM');
|
|
73
|
+
const kill = setTimeout(() => child.kill('SIGKILL'), STOP_MS);
|
|
74
|
+
await exited;
|
|
75
|
+
clearTimeout(kill);
|
|
76
|
+
};
|
|
77
|
+
// One child process per extension: node dist/host/main.js on a port the OS picks.
|
|
78
|
+
export const forkLaunch = (main = HOST_MAIN) => async (spec) => {
|
|
79
|
+
const secretsDir = await secretFiles(spec);
|
|
80
|
+
const stdio = ['ignore', 'pipe', 'pipe', 'ipc'];
|
|
81
|
+
// execArgv []: the daemon's own node flags (a loader, --input-type) are not the child's.
|
|
82
|
+
const env = envOf(spec, secretsDir);
|
|
83
|
+
const child = fork(main, [], { env, execArgv: [], stdio: [...stdio] });
|
|
84
|
+
const exited = new Promise((resolve) => child.once('exit', (code, signal) => resolve({ code, signal })));
|
|
85
|
+
try {
|
|
86
|
+
const port = await readyOf(child, captured(child));
|
|
87
|
+
return { port, pid: child.pid ?? 0, exited, stop: stopOf(child, exited) };
|
|
88
|
+
}
|
|
89
|
+
finally {
|
|
90
|
+
await rm(secretsDir, { recursive: true, force: true });
|
|
91
|
+
}
|
|
92
|
+
};
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export declare const DAEMON_FILE = "daemon.json";
|
|
2
|
+
export declare const DAEMON_PROTOCOL = 1;
|
|
3
|
+
export interface DaemonFile {
|
|
4
|
+
pid: number;
|
|
5
|
+
port: number;
|
|
6
|
+
version: string;
|
|
7
|
+
protocol: number;
|
|
8
|
+
startedBy: string;
|
|
9
|
+
}
|
|
10
|
+
export declare const writeDaemonFile: (configDir: string, file: DaemonFile) => Promise<void>;
|
|
11
|
+
export declare const removeDaemonFile: (configDir: string) => Promise<void>;
|
|
12
|
+
export declare const dataDirOf: (configDir: string, id: string) => string;
|
|
13
|
+
export declare const purgeData: (configDir: string, id: string) => Promise<void>;
|
|
14
|
+
export type ValueKind = 'settings' | 'secrets';
|
|
15
|
+
type Values = Record<string, unknown>;
|
|
16
|
+
export declare const readValues: (configDir: string, kind: ValueKind, id: string) => Promise<Values>;
|
|
17
|
+
export declare const writeValues: (configDir: string, kind: ValueKind, id: string, values?: Values) => Promise<void>;
|
|
18
|
+
export declare const ensureConfigDir: (configDir: string) => Promise<string | undefined>;
|
|
19
|
+
export {};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { mkdir, rm, unlink } from 'node:fs/promises';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { readJsonFile, withFileLock, writeJsonFile } from './json-file.js';
|
|
4
|
+
export const DAEMON_FILE = 'daemon.json';
|
|
5
|
+
export const DAEMON_PROTOCOL = 1;
|
|
6
|
+
export const writeDaemonFile = (configDir, file) => writeJsonFile(join(configDir, DAEMON_FILE), file);
|
|
7
|
+
export const removeDaemonFile = (configDir) => unlink(join(configDir, DAEMON_FILE)).catch(() => undefined);
|
|
8
|
+
export const dataDirOf = (configDir, id) => join(configDir, 'data', id);
|
|
9
|
+
export const purgeData = (configDir, id) => rm(dataDirOf(configDir, id), { recursive: true, force: true });
|
|
10
|
+
const fileOf = (configDir, kind) => join(configDir, `${kind}.json`);
|
|
11
|
+
export const readValues = async (configDir, kind, id) => (await readJsonFile(fileOf(configDir, kind), {}))[id] ?? {};
|
|
12
|
+
export const writeValues = (configDir, kind, id, values) => {
|
|
13
|
+
const file = fileOf(configDir, kind);
|
|
14
|
+
return withFileLock(file, async () => {
|
|
15
|
+
const all = await readJsonFile(file, {});
|
|
16
|
+
if (values)
|
|
17
|
+
all[id] = values;
|
|
18
|
+
else
|
|
19
|
+
delete all[id];
|
|
20
|
+
await writeJsonFile(file, all, kind === 'secrets' ? 0o600 : 0o644);
|
|
21
|
+
});
|
|
22
|
+
};
|
|
23
|
+
export const ensureConfigDir = (configDir) => mkdir(configDir, { recursive: true });
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { type Launch } from './child.js';
|
|
2
|
+
import { type Installer } from './supervisor.js';
|
|
3
|
+
export interface DaemonOptions {
|
|
4
|
+
configDir: string;
|
|
5
|
+
port?: number;
|
|
6
|
+
install?: Installer;
|
|
7
|
+
version: string;
|
|
8
|
+
startedBy: string;
|
|
9
|
+
drainMs?: number;
|
|
10
|
+
healthMs?: number;
|
|
11
|
+
}
|
|
12
|
+
export interface Daemon {
|
|
13
|
+
port: number;
|
|
14
|
+
stop(): Promise<void>;
|
|
15
|
+
}
|
|
16
|
+
export declare const DAEMON_PORT = 4243;
|
|
17
|
+
export declare const startDaemon: (opts: DaemonOptions, launch: Launch) => Promise<Daemon>;
|
|
18
|
+
export declare const createDaemon: (opts: DaemonOptions) => Promise<Daemon>;
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import {} from 'node:http';
|
|
2
|
+
import {} from 'node:net';
|
|
3
|
+
import { createLog } from '../../log/log.js';
|
|
4
|
+
import { listen } from '../../server/serve.js';
|
|
5
|
+
import { forkLaunch } from './child.js';
|
|
6
|
+
import { ensureConfigDir, removeDaemonFile, writeDaemonFile, DAEMON_PROTOCOL, } from './daemon-files.js';
|
|
7
|
+
import { keepBadCopy, readInstallation } from './installation.js';
|
|
8
|
+
import {} from './ops.js';
|
|
9
|
+
import { serialQueue } from './queue.js';
|
|
10
|
+
import { daemonApp } from './routes.js';
|
|
11
|
+
import { DRAIN_MS, HEALTH_MS, halt, startEntry, } from './supervisor.js';
|
|
12
|
+
export const DAEMON_PORT = 4243;
|
|
13
|
+
// The valid rows of installation.json; a bad file is kept aside and reported in /health.
|
|
14
|
+
const loadEntries = async (configDir) => {
|
|
15
|
+
const { doc, invalid } = await readInstallation(configDir);
|
|
16
|
+
if (invalid)
|
|
17
|
+
await keepBadCopy(configDir).catch(() => undefined);
|
|
18
|
+
const entries = new Map();
|
|
19
|
+
for (const install of doc.extensions) {
|
|
20
|
+
const state = install.enabled === false ? 'disabled' : 'starting';
|
|
21
|
+
entries.set(install.id, { id: install.id, install, state, version: install.version ?? '' });
|
|
22
|
+
}
|
|
23
|
+
return { entries, invalid };
|
|
24
|
+
};
|
|
25
|
+
// One at a time, so the installer is never called twice at once; a failed one stops no other.
|
|
26
|
+
const boot = async (deps, entries) => {
|
|
27
|
+
for (const entry of entries.values())
|
|
28
|
+
if (entry.state === 'starting')
|
|
29
|
+
await startEntry(deps, entry);
|
|
30
|
+
};
|
|
31
|
+
const close = (server) => new Promise((resolve) => {
|
|
32
|
+
server.close(() => resolve());
|
|
33
|
+
server.closeAllConnections();
|
|
34
|
+
});
|
|
35
|
+
const stopper = (server, entries, deps) => {
|
|
36
|
+
let stopped;
|
|
37
|
+
const stop = async () => {
|
|
38
|
+
await Promise.all([...entries.values()].map((entry) => halt(entry, deps.drainMs)));
|
|
39
|
+
await close(server);
|
|
40
|
+
await removeDaemonFile(deps.configDir);
|
|
41
|
+
};
|
|
42
|
+
return () => (stopped ??= stop());
|
|
43
|
+
};
|
|
44
|
+
// C4: how a client finds this daemon.
|
|
45
|
+
const announce = ({ configDir, version, startedBy }, port) => writeDaemonFile(configDir, {
|
|
46
|
+
pid: process.pid,
|
|
47
|
+
port,
|
|
48
|
+
version,
|
|
49
|
+
protocol: DAEMON_PROTOCOL,
|
|
50
|
+
startedBy,
|
|
51
|
+
});
|
|
52
|
+
const depsOf = (opts, launch, origin) => ({
|
|
53
|
+
configDir: opts.configDir,
|
|
54
|
+
launch,
|
|
55
|
+
install: opts.install,
|
|
56
|
+
log: createLog({ extension: 'host', part: 'api', version: opts.version }),
|
|
57
|
+
origin,
|
|
58
|
+
drainMs: opts.drainMs ?? DRAIN_MS,
|
|
59
|
+
healthMs: opts.healthMs ?? HEALTH_MS,
|
|
60
|
+
queue: serialQueue(),
|
|
61
|
+
});
|
|
62
|
+
// Read and check the file, listen, write daemon.json, start the children; a failed boot undoes it.
|
|
63
|
+
export const startDaemon = async (opts, launch) => {
|
|
64
|
+
await ensureConfigDir(opts.configDir);
|
|
65
|
+
let port = opts.port ?? DAEMON_PORT;
|
|
66
|
+
const deps = depsOf(opts, launch, () => `http://127.0.0.1:${port}`);
|
|
67
|
+
const { entries, invalid } = await loadEntries(opts.configDir);
|
|
68
|
+
const info = { version: opts.version, pid: process.pid, protocol: DAEMON_PROTOCOL, invalid };
|
|
69
|
+
const app = daemonApp(deps, entries, () => port, info);
|
|
70
|
+
const server = await listen(app, port, '127.0.0.1');
|
|
71
|
+
port = server.address().port;
|
|
72
|
+
const stop = stopper(server, entries, deps);
|
|
73
|
+
try {
|
|
74
|
+
await announce(opts, port);
|
|
75
|
+
await deps.queue(() => boot(deps, entries));
|
|
76
|
+
}
|
|
77
|
+
catch (err) {
|
|
78
|
+
await stop();
|
|
79
|
+
throw err;
|
|
80
|
+
}
|
|
81
|
+
return { port, stop };
|
|
82
|
+
};
|
|
83
|
+
// One daemon on 127.0.0.1, one child process for each extension (D1).
|
|
84
|
+
export const createDaemon = (opts) => startDaemon(opts, forkLaunch());
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import {} from 'express';
|
|
2
|
+
import { fail } from '../../envelope/envelope.js';
|
|
3
|
+
// What a browser says of a request another site started (an <img>, a link, a form).
|
|
4
|
+
const FOREIGN = ['cross-site', 'same-site'];
|
|
5
|
+
// Only this machine, by name: a page elsewhere (DNS rebinding, a cross-site form or GET) gets 403.
|
|
6
|
+
export const localOnly = (port) => (req, _res, next) => {
|
|
7
|
+
const hosts = [`127.0.0.1:${port()}`, `localhost:${port()}`];
|
|
8
|
+
const origin = req.get('origin');
|
|
9
|
+
const hostOk = hosts.includes(req.get('host') ?? '');
|
|
10
|
+
const originOk = origin === undefined || hosts.some((host) => origin === `http://${host}`);
|
|
11
|
+
const siteOk = !FOREIGN.includes(req.get('sec-fetch-site') ?? '');
|
|
12
|
+
if (!hostOk || !originOk || !siteOk)
|
|
13
|
+
throw fail('FORBIDDEN', 'Only this machine may call the daemon');
|
|
14
|
+
next();
|
|
15
|
+
};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
declare const InstallEntrySchema: z.ZodObject<{
|
|
3
|
+
id: z.ZodString;
|
|
4
|
+
version: z.ZodOptional<z.ZodString>;
|
|
5
|
+
source: z.ZodOptional<z.ZodString>;
|
|
6
|
+
enabled: z.ZodOptional<z.ZodBoolean>;
|
|
7
|
+
}, z.core.$loose>;
|
|
8
|
+
export type InstallEntry = z.infer<typeof InstallEntrySchema>;
|
|
9
|
+
export interface Installation {
|
|
10
|
+
host: string;
|
|
11
|
+
extensions: InstallEntry[];
|
|
12
|
+
[key: string]: unknown;
|
|
13
|
+
}
|
|
14
|
+
export interface CheckedInstallation {
|
|
15
|
+
doc: Installation;
|
|
16
|
+
invalid: boolean;
|
|
17
|
+
}
|
|
18
|
+
export declare const INSTALLATION_FILE = "installation.json";
|
|
19
|
+
export declare const readInstallation: (configDir: string) => Promise<CheckedInstallation>;
|
|
20
|
+
export declare const keepBadCopy: (configDir: string) => Promise<void>;
|
|
21
|
+
export declare const updateInstallation: (configDir: string, change: (doc: Installation) => Installation) => Promise<Installation>;
|
|
22
|
+
export declare const withEntry: (doc: Installation, id: string, entry?: InstallEntry) => Installation;
|
|
23
|
+
export {};
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { copyFile } from 'node:fs/promises';
|
|
2
|
+
import { isAbsolute, join } from 'node:path';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
import { ExtensionIdSchema } from '../../manifest/primitives.schema.js';
|
|
5
|
+
import { readJsonFile, withFileLock, writeJsonFile } from './json-file.js';
|
|
6
|
+
// One extension in installation.json (C3): a version, or a source folder; other keys round-trip.
|
|
7
|
+
const InstallEntrySchema = z.looseObject({
|
|
8
|
+
id: ExtensionIdSchema,
|
|
9
|
+
version: z.string().min(1).optional(),
|
|
10
|
+
source: z.string().refine(isAbsolute).optional(),
|
|
11
|
+
enabled: z.boolean().optional(),
|
|
12
|
+
});
|
|
13
|
+
const InstallationSchema = z.looseObject({
|
|
14
|
+
host: z.string().default('local'),
|
|
15
|
+
extensions: z.array(z.unknown()),
|
|
16
|
+
});
|
|
17
|
+
export const INSTALLATION_FILE = 'installation.json';
|
|
18
|
+
const EMPTY = { host: 'local', extensions: [] };
|
|
19
|
+
const checked = (raw) => {
|
|
20
|
+
const top = InstallationSchema.safeParse(raw);
|
|
21
|
+
if (!top.success)
|
|
22
|
+
return { doc: EMPTY, invalid: true };
|
|
23
|
+
const rows = top.data.extensions.map((row) => InstallEntrySchema.safeParse(row));
|
|
24
|
+
const extensions = rows.flatMap((row) => (row.success ? [row.data] : []));
|
|
25
|
+
return { doc: { ...top.data, extensions }, invalid: extensions.length < rows.length };
|
|
26
|
+
};
|
|
27
|
+
export const readInstallation = async (configDir) => checked(await readJsonFile(join(configDir, INSTALLATION_FILE), EMPTY).catch(() => null));
|
|
28
|
+
// A bad file is kept as installation.json.bad before the daemon writes the valid rows over it.
|
|
29
|
+
export const keepBadCopy = (configDir) => copyFile(join(configDir, INSTALLATION_FILE), join(configDir, `${INSTALLATION_FILE}.bad`));
|
|
30
|
+
// Read, change and write under the lock: the daemon is the only writer.
|
|
31
|
+
export const updateInstallation = (configDir, change) => {
|
|
32
|
+
const file = join(configDir, INSTALLATION_FILE);
|
|
33
|
+
return withFileLock(file, async () => {
|
|
34
|
+
const next = change((await readInstallation(configDir)).doc);
|
|
35
|
+
await writeJsonFile(file, next);
|
|
36
|
+
return next;
|
|
37
|
+
});
|
|
38
|
+
};
|
|
39
|
+
// The entry of id replaced (or added), the order kept; undefined removes it.
|
|
40
|
+
export const withEntry = (doc, id, entry) => {
|
|
41
|
+
const at = doc.extensions.findIndex((e) => e.id === id);
|
|
42
|
+
const rest = doc.extensions.filter((e) => e.id !== id);
|
|
43
|
+
if (!entry)
|
|
44
|
+
return { ...doc, extensions: rest };
|
|
45
|
+
if (at < 0)
|
|
46
|
+
return { ...doc, extensions: [...rest, entry] };
|
|
47
|
+
return { ...doc, extensions: doc.extensions.map((e) => (e.id === id ? entry : e)) };
|
|
48
|
+
};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { type Installer, type SupervisorDeps } from './supervisor.js';
|
|
2
|
+
export declare const NO_INSTALLER = "this daemon has no installer: install a folder with { source }";
|
|
3
|
+
export declare const runInstaller: (deps: SupervisorDeps, spec: Parameters<Installer>[0]) => Promise<{
|
|
4
|
+
id: string;
|
|
5
|
+
version: string;
|
|
6
|
+
dir: string;
|
|
7
|
+
}>;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { fail } from '../../envelope/envelope.js';
|
|
2
|
+
import {} from './supervisor.js';
|
|
3
|
+
export const NO_INSTALLER = 'this daemon has no installer: install a folder with { source }';
|
|
4
|
+
// 501 as C5 says, in the envelope; the closed code set has no NOT_IMPLEMENTED.
|
|
5
|
+
const noInstaller = () => Object.assign(fail('UNAVAILABLE', NO_INSTALLER), { status: 501, retryAfter: undefined });
|
|
6
|
+
const BASE = { 400: 'VALIDATION_ERROR', 404: 'NOT_FOUND', 502: 'UNAVAILABLE' };
|
|
7
|
+
// An installer error with a string code is the client's envelope; any other stays a 500.
|
|
8
|
+
const answerOf = (err) => {
|
|
9
|
+
const { code, status, message } = (err ?? {});
|
|
10
|
+
if (typeof code !== 'string' || !code)
|
|
11
|
+
return err;
|
|
12
|
+
const at = status === 404 || status === 502 ? status : 400;
|
|
13
|
+
const failure = fail(BASE[at], typeof message === 'string' && message ? message : code);
|
|
14
|
+
return Object.assign(failure, { code, status: at, retryAfter: undefined });
|
|
15
|
+
};
|
|
16
|
+
export const runInstaller = async (deps, spec) => {
|
|
17
|
+
if (!deps.install)
|
|
18
|
+
throw noInstaller();
|
|
19
|
+
return deps.install(spec).catch((err) => {
|
|
20
|
+
throw answerOf(err);
|
|
21
|
+
});
|
|
22
|
+
};
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
import { chmod, open, readFile, rename } from 'node:fs/promises';
|
|
3
|
+
import { DATA_DIR_LOCKED, lockDataDir } from '../data-lock.js';
|
|
4
|
+
export const readJsonFile = async (file, fallback) => {
|
|
5
|
+
try {
|
|
6
|
+
return JSON.parse(await readFile(file, 'utf8'));
|
|
7
|
+
}
|
|
8
|
+
catch (err) {
|
|
9
|
+
if (err.code === 'ENOENT')
|
|
10
|
+
return fallback;
|
|
11
|
+
throw err;
|
|
12
|
+
}
|
|
13
|
+
};
|
|
14
|
+
// A reader sees the old file or the new one, never half of one, also after a power loss.
|
|
15
|
+
export const writeJsonFile = async (file, value, mode = 0o644) => {
|
|
16
|
+
const tmp = `${file}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
|
|
17
|
+
const handle = await open(tmp, 'w', mode);
|
|
18
|
+
try {
|
|
19
|
+
await handle.writeFile(`${JSON.stringify(value, null, 2)}\n`);
|
|
20
|
+
await handle.sync();
|
|
21
|
+
}
|
|
22
|
+
finally {
|
|
23
|
+
await handle.close();
|
|
24
|
+
}
|
|
25
|
+
await chmod(tmp, mode);
|
|
26
|
+
await rename(tmp, file);
|
|
27
|
+
};
|
|
28
|
+
const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
29
|
+
// The pid lock of data-lock.ts: a dead holder's lock is taken over, a live one is waited for.
|
|
30
|
+
const acquire = async (file) => {
|
|
31
|
+
for (let tries = 0;; tries += 1) {
|
|
32
|
+
try {
|
|
33
|
+
return await lockDataDir(file);
|
|
34
|
+
}
|
|
35
|
+
catch (err) {
|
|
36
|
+
if (err.code !== DATA_DIR_LOCKED || tries >= 200)
|
|
37
|
+
throw err;
|
|
38
|
+
await pause(25);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
// One writer at a time across processes: an exclusive lock file (<file>.lock) beside the file.
|
|
43
|
+
export const withFileLock = async (file, fn) => {
|
|
44
|
+
const release = await acquire(file);
|
|
45
|
+
try {
|
|
46
|
+
return await fn();
|
|
47
|
+
}
|
|
48
|
+
finally {
|
|
49
|
+
await release();
|
|
50
|
+
}
|
|
51
|
+
};
|