@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
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
import { rmSync } from 'node:fs';
|
|
3
|
+
import { link, readFile, rename, unlink, writeFile } from 'node:fs/promises';
|
|
4
|
+
export const DATA_DIR_LOCKED = 'DATA_DIR_LOCKED';
|
|
5
|
+
// The locks of this process: our own pid in a lock not in here is stale (a container is pid 1 again).
|
|
6
|
+
const held = new Set();
|
|
7
|
+
const alive = (pid) => {
|
|
8
|
+
try {
|
|
9
|
+
return process.kill(pid, 0);
|
|
10
|
+
}
|
|
11
|
+
catch (err) {
|
|
12
|
+
return err.code === 'EPERM';
|
|
13
|
+
}
|
|
14
|
+
};
|
|
15
|
+
const holder = async (file) => Number(await readFile(file, 'utf8').catch(() => '0'));
|
|
16
|
+
const live = (lock, pid) => pid === process.pid ? held.has(lock) : pid > 0 && alive(pid);
|
|
17
|
+
const locked = (lock, pid) => Object.assign(new Error(`${lock.slice(0, -5)} is open in process ${pid}`), {
|
|
18
|
+
code: DATA_DIR_LOCKED,
|
|
19
|
+
});
|
|
20
|
+
const unique = (file) => `${file}.${process.pid}.${randomBytes(4).toString('hex')}`;
|
|
21
|
+
// A full lock file appears at once or not at all: written aside, then linked (fails if one exists).
|
|
22
|
+
const take = async (lock) => {
|
|
23
|
+
const tmp = unique(lock);
|
|
24
|
+
await writeFile(tmp, String(process.pid));
|
|
25
|
+
try {
|
|
26
|
+
await link(tmp, lock);
|
|
27
|
+
held.add(lock);
|
|
28
|
+
return true;
|
|
29
|
+
}
|
|
30
|
+
catch (err) {
|
|
31
|
+
if (err.code !== 'EEXIST')
|
|
32
|
+
throw err;
|
|
33
|
+
return false;
|
|
34
|
+
}
|
|
35
|
+
finally {
|
|
36
|
+
await unlink(tmp).catch(() => undefined);
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
// Only one starter moves the stale file away; one that moved a fresh lock puts it back and refuses.
|
|
40
|
+
const clearStale = async (lock, pid) => {
|
|
41
|
+
const moved = unique(`${lock}.stale`);
|
|
42
|
+
const gone = await rename(lock, moved).then(() => false, (err) => err.code === 'ENOENT');
|
|
43
|
+
if (gone)
|
|
44
|
+
return;
|
|
45
|
+
const now = await holder(moved);
|
|
46
|
+
if (now !== pid) {
|
|
47
|
+
await link(moved, lock).catch(() => undefined);
|
|
48
|
+
await unlink(moved);
|
|
49
|
+
throw locked(lock, now);
|
|
50
|
+
}
|
|
51
|
+
await unlink(moved);
|
|
52
|
+
};
|
|
53
|
+
const turns = new Map();
|
|
54
|
+
// One taker per lock in this process: none sees our pid in the file before it is in held.
|
|
55
|
+
const inTurn = (lock, fn) => {
|
|
56
|
+
const run = (turns.get(lock) ?? Promise.resolve()).then(fn, fn);
|
|
57
|
+
const tail = run.catch(() => undefined);
|
|
58
|
+
turns.set(lock, tail);
|
|
59
|
+
void tail.then(() => turns.get(lock) === tail && turns.delete(lock));
|
|
60
|
+
return run;
|
|
61
|
+
};
|
|
62
|
+
const acquire = async (lock) => {
|
|
63
|
+
if (await take(lock))
|
|
64
|
+
return;
|
|
65
|
+
const pid = await holder(lock);
|
|
66
|
+
if (live(lock, pid))
|
|
67
|
+
throw locked(lock, pid);
|
|
68
|
+
await clearStale(lock, pid);
|
|
69
|
+
if (!(await take(lock)))
|
|
70
|
+
throw locked(lock, await holder(lock));
|
|
71
|
+
};
|
|
72
|
+
// PGlite has one writer per folder: <dataDir>.lock holds the pid; a dead holder's lock is taken over.
|
|
73
|
+
export const lockDataDir = async (dataDir) => {
|
|
74
|
+
const lock = `${dataDir}.lock`;
|
|
75
|
+
await inTurn(lock, () => acquire(lock));
|
|
76
|
+
// Sync, so no other taker in this process sees the file without its entry in held.
|
|
77
|
+
return async () => {
|
|
78
|
+
rmSync(lock, { force: true });
|
|
79
|
+
held.delete(lock);
|
|
80
|
+
};
|
|
81
|
+
};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { type Env } from '../runtime/build-info.js';
|
|
2
|
+
import { type HostExtras } from './host-extension.js';
|
|
3
|
+
export declare const HOST_PORT = 8080;
|
|
4
|
+
export declare const BIND_REFUSED = "AGENTAGE_HOST_BIND=all needs a token check (AGENTAGE_ISSUER, AGENTAGE_AUDIENCE, AGENTAGE_ORIGIN) or AGENTAGE_HOST_AUTH=off";
|
|
5
|
+
export declare const hostEnvOf: (env: Env) => {
|
|
6
|
+
dir: string;
|
|
7
|
+
port: number;
|
|
8
|
+
bind: string;
|
|
9
|
+
dataDir: string;
|
|
10
|
+
settings: Record<string, unknown>;
|
|
11
|
+
secretsDir: string;
|
|
12
|
+
origin: string;
|
|
13
|
+
};
|
|
14
|
+
export declare const guardOf: (env: Env, { bind, dir }: {
|
|
15
|
+
bind: string;
|
|
16
|
+
dir: string;
|
|
17
|
+
}) => HostExtras["guard"];
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { declaredScopes, partAuth } from '../auth/part-auth.js';
|
|
2
|
+
import { SECRETS_DIR } from '../context/secrets.js';
|
|
3
|
+
import { parseObject } from '../context/settings.js';
|
|
4
|
+
import { readOpenapi } from '../discovery/openapi.js';
|
|
5
|
+
import {} from '../log/log.js';
|
|
6
|
+
import {} from '../manifest/manifest.schema.js';
|
|
7
|
+
import { portFromEnv } from '../runtime/build-info.js';
|
|
8
|
+
import {} from './host-extension.js';
|
|
9
|
+
export const HOST_PORT = 8080;
|
|
10
|
+
export const BIND_REFUSED = 'AGENTAGE_HOST_BIND=all needs a token check (AGENTAGE_ISSUER, AGENTAGE_AUDIENCE, AGENTAGE_ORIGIN) or AGENTAGE_HOST_AUTH=off';
|
|
11
|
+
const TOKEN_ENV = ['AGENTAGE_ISSUER', 'AGENTAGE_AUDIENCE', 'AGENTAGE_ORIGIN'];
|
|
12
|
+
// The entry's env with its defaults: port 8080, the current folder, loopback.
|
|
13
|
+
export const hostEnvOf = (env) => {
|
|
14
|
+
const port = portFromEnv(env, HOST_PORT);
|
|
15
|
+
return {
|
|
16
|
+
dir: env['AGENTAGE_EXTENSION_DIR'] || process.cwd(),
|
|
17
|
+
port,
|
|
18
|
+
bind: env['AGENTAGE_HOST_BIND'] === 'all' ? '0.0.0.0' : '127.0.0.1',
|
|
19
|
+
dataDir: env['AGENTAGE_DATA_DIR'] ?? '',
|
|
20
|
+
settings: env['AGENTAGE_SETTINGS'] ? parseObject(env['AGENTAGE_SETTINGS']) : {},
|
|
21
|
+
secretsDir: env['AGENTAGE_SECRETS_DIR'] || SECRETS_DIR,
|
|
22
|
+
origin: env['AGENTAGE_ORIGIN'] || `http://127.0.0.1${port ? `:${port}` : ''}`,
|
|
23
|
+
};
|
|
24
|
+
};
|
|
25
|
+
// Loopback: no token check. Every address: the cloud part's check, or an explicit AGENTAGE_HOST_AUTH=off.
|
|
26
|
+
export const guardOf = (env, { bind, dir }) => {
|
|
27
|
+
if (bind === '127.0.0.1' || env['AGENTAGE_HOST_AUTH'] === 'off')
|
|
28
|
+
return undefined;
|
|
29
|
+
if (TOKEN_ENV.some((key) => !env[key]))
|
|
30
|
+
throw new Error(BIND_REFUSED);
|
|
31
|
+
return async (pkg, log) => {
|
|
32
|
+
const { id } = pkg.agentage;
|
|
33
|
+
const scopes = declaredScopes(id, await readOpenapi(dir));
|
|
34
|
+
return partAuth(env, id, log, scopes);
|
|
35
|
+
};
|
|
36
|
+
};
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { type Express } from 'express';
|
|
2
|
+
import { type HealthBody } from '../health/health.schema.js';
|
|
3
|
+
import { type Log } from '../log/log.js';
|
|
4
|
+
import { type ExtensionPackage } from '../manifest/manifest.schema.js';
|
|
5
|
+
import { type PartAppBase } from '../server/app.js';
|
|
6
|
+
export interface HostOptions {
|
|
7
|
+
dataDir: string;
|
|
8
|
+
settings?: Record<string, unknown>;
|
|
9
|
+
secrets?: Record<string, string>;
|
|
10
|
+
onExit?: () => void;
|
|
11
|
+
origin?: string;
|
|
12
|
+
}
|
|
13
|
+
export interface HostedExtension {
|
|
14
|
+
id: string;
|
|
15
|
+
version: string;
|
|
16
|
+
app: Express;
|
|
17
|
+
stop(): Promise<void>;
|
|
18
|
+
health(): Promise<HealthBody>;
|
|
19
|
+
}
|
|
20
|
+
export interface HostExtras {
|
|
21
|
+
secretsDir?: string;
|
|
22
|
+
guard?: (pkg: ExtensionPackage, log: Log) => Promise<Partial<PartAppBase>>;
|
|
23
|
+
}
|
|
24
|
+
export declare const hostWith: (dir: string, opts: HostOptions, extras: HostExtras) => Promise<HostedExtension>;
|
|
25
|
+
export declare const hostExtension: (dir: string, opts: HostOptions) => Promise<HostedExtension>;
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
import {} from 'express';
|
|
3
|
+
import { createContext } from '../context/context.js';
|
|
4
|
+
import { readSecrets, secretsFrom } from '../context/secrets.js';
|
|
5
|
+
import { settingsOf } from '../context/settings.js';
|
|
6
|
+
import { readOpenapi } from '../discovery/openapi.js';
|
|
7
|
+
import { healthBody } from '../health/health.js';
|
|
8
|
+
import {} from '../health/health.schema.js';
|
|
9
|
+
import { createLog } from '../log/log.js';
|
|
10
|
+
import {} from '../manifest/manifest.schema.js';
|
|
11
|
+
import { normalizeParts } from '../manifest/parts.js';
|
|
12
|
+
import { readManifest } from '../manifest/read-manifest.js';
|
|
13
|
+
import { buildInfoFromEnv } from '../runtime/build-info.js';
|
|
14
|
+
import { RUNNERS } from '../runtime/part-runners.js';
|
|
15
|
+
import { createPartApp } from '../server/app.js';
|
|
16
|
+
import { storeCheck } from '../store/store.js';
|
|
17
|
+
import {} from '../store/pglite-store.js';
|
|
18
|
+
import { openHostStore } from './host-store.js';
|
|
19
|
+
const once = (fn) => {
|
|
20
|
+
let done = false;
|
|
21
|
+
return () => {
|
|
22
|
+
if (done)
|
|
23
|
+
return;
|
|
24
|
+
done = true;
|
|
25
|
+
fn();
|
|
26
|
+
};
|
|
27
|
+
};
|
|
28
|
+
const secretsOf = ({ pkg, opts, extras }) => extras.secretsDir
|
|
29
|
+
? readSecrets(pkg, 'api', extras.secretsDir)
|
|
30
|
+
: secretsFrom(pkg, 'api', async (name) => opts.secrets?.[name] ?? '');
|
|
31
|
+
// createContext with the host's values: settings and secrets as given, no platform.
|
|
32
|
+
const contextOf = async (h, checks) => createContext({
|
|
33
|
+
pkg: h.pkg,
|
|
34
|
+
part: 'api',
|
|
35
|
+
origin: h.opts.origin ?? 'http://127.0.0.1',
|
|
36
|
+
commit: buildInfoFromEnv({}).commit,
|
|
37
|
+
log: h.log,
|
|
38
|
+
settings: settingsOf(h.pkg, h.opts.settings ?? {}, h.log),
|
|
39
|
+
store: h.store,
|
|
40
|
+
secrets: await secretsOf(h),
|
|
41
|
+
checks,
|
|
42
|
+
onExit: h.onExit,
|
|
43
|
+
});
|
|
44
|
+
// The api part of the package; a package without one serves /health only.
|
|
45
|
+
const appOf = async (h, base) => {
|
|
46
|
+
if (!normalizeParts(h.pkg.agentage.parts).code.api)
|
|
47
|
+
return createPartApp({ ...base, part: 'api', mount: () => undefined });
|
|
48
|
+
const ctx = await contextOf(h, base.checks ?? {});
|
|
49
|
+
const openapi = await readOpenapi(h.dir);
|
|
50
|
+
return (await RUNNERS.api({ dir: h.dir, pkg: h.pkg, env: {}, ctx: () => ctx, base, openapi }))
|
|
51
|
+
.app;
|
|
52
|
+
};
|
|
53
|
+
const baseOf = async (h) => {
|
|
54
|
+
const guard = (await h.extras.guard?.(h.pkg, h.log)) ?? {};
|
|
55
|
+
const checks = { ...(h.store && { store: storeCheck(h.store) }), ...guard.checks };
|
|
56
|
+
const resolved = { instance: randomBytes(4).toString('hex'), startedAt: Date.now() };
|
|
57
|
+
const build = buildInfoFromEnv({});
|
|
58
|
+
return { pkg: h.pkg, log: h.log, build, onExit: h.onExit, ...guard, checks, ...resolved };
|
|
59
|
+
};
|
|
60
|
+
const hostedOf = (h, app, base) => {
|
|
61
|
+
const { id } = h.pkg.agentage;
|
|
62
|
+
const { version } = h.pkg;
|
|
63
|
+
const { instance = '', startedAt = 0, build, checks } = base;
|
|
64
|
+
const health = () => healthBody({ extension: id, part: 'api', version, build, checks, instance, startedAt });
|
|
65
|
+
let stopped;
|
|
66
|
+
const stop = () => (stopped ??= h.store ? h.store.close() : Promise.resolve());
|
|
67
|
+
return { id, version, app, health, stop };
|
|
68
|
+
};
|
|
69
|
+
// hostExtension with the extras of the entry (dist/host/main.js).
|
|
70
|
+
export const hostWith = async (dir, opts, extras) => {
|
|
71
|
+
const pkg = await readManifest(dir);
|
|
72
|
+
const log = createLog({ extension: pkg.agentage.id, part: 'api', version: pkg.version });
|
|
73
|
+
const store = await openHostStore(dir, pkg, opts.dataDir, log);
|
|
74
|
+
const onExit = once(opts.onExit ?? (() => undefined));
|
|
75
|
+
const h = { dir, pkg, log, opts, extras, store, onExit };
|
|
76
|
+
try {
|
|
77
|
+
const base = await baseOf(h);
|
|
78
|
+
return hostedOf(h, await appOf(h, base), base);
|
|
79
|
+
}
|
|
80
|
+
catch (err) {
|
|
81
|
+
await store?.close();
|
|
82
|
+
throw err;
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
// One extension in this process: its api at /api/{id}/*, no token check, its own settings, secrets, store and log.
|
|
86
|
+
export const hostExtension = (dir, opts) => hostWith(dir, opts, {});
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { type Log } from '../log/log.js';
|
|
2
|
+
import { type ExtensionPackage } from '../manifest/manifest.schema.js';
|
|
3
|
+
import { type PgliteStore } from '../store/pglite-store.js';
|
|
4
|
+
export declare const openHostStore: (dir: string, pkg: ExtensionPackage, dataDir: string, log: Log) => Promise<PgliteStore | undefined>;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { mkdir } from 'node:fs/promises';
|
|
2
|
+
import {} from '../log/log.js';
|
|
3
|
+
import {} from '../manifest/manifest.schema.js';
|
|
4
|
+
import { hasStore } from '../manifest/parts.js';
|
|
5
|
+
import { migrate } from '../store/migrations.js';
|
|
6
|
+
import { createPgliteStore } from '../store/pglite-store.js';
|
|
7
|
+
import { lockDataDir } from './data-lock.js';
|
|
8
|
+
const unlocked = async () => undefined;
|
|
9
|
+
// Locks dataDir, then opens PGlite in it and migrates before the part starts.
|
|
10
|
+
const open = async (dir, dataDir, log) => {
|
|
11
|
+
if (dataDir)
|
|
12
|
+
await mkdir(dataDir, { recursive: true });
|
|
13
|
+
const release = dataDir ? await lockDataDir(dataDir) : unlocked;
|
|
14
|
+
const store = createPgliteStore((s) => migrate(s, dir, log), {
|
|
15
|
+
dataDir: dataDir || undefined,
|
|
16
|
+
from: dir,
|
|
17
|
+
});
|
|
18
|
+
const close = async () => {
|
|
19
|
+
await store.close().catch(() => undefined);
|
|
20
|
+
await release();
|
|
21
|
+
};
|
|
22
|
+
await store.query('select 1').catch(async (err) => {
|
|
23
|
+
await close();
|
|
24
|
+
throw err;
|
|
25
|
+
});
|
|
26
|
+
return { query: store.query, close };
|
|
27
|
+
};
|
|
28
|
+
// A postgres store as PGlite with its files in dataDir; none set keeps it in memory.
|
|
29
|
+
export const openHostStore = async (dir, pkg, dataDir, log) => {
|
|
30
|
+
if (!hasStore(pkg, 'postgres'))
|
|
31
|
+
return undefined;
|
|
32
|
+
if (!dataDir)
|
|
33
|
+
log.warn('no data folder: the store is in memory and lost on exit');
|
|
34
|
+
return open(dir, dataDir, log);
|
|
35
|
+
};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createLog } from '../log/log.js';
|
|
3
|
+
import { serveHost } from './serve-host.js';
|
|
4
|
+
// The daemon's child and the one container: `node .../dist/host/main.js`, settings from env.
|
|
5
|
+
const crash = (err) => {
|
|
6
|
+
createLog({ extension: 'unknown', part: 'api' }).error(err);
|
|
7
|
+
process.exit(1);
|
|
8
|
+
};
|
|
9
|
+
process.on('uncaughtException', crash);
|
|
10
|
+
await serveHost(process.env).catch(crash);
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { type Server } from 'node:http';
|
|
2
|
+
import { type Env } from '../runtime/build-info.js';
|
|
3
|
+
import { type HostedExtension } from './host-extension.js';
|
|
4
|
+
export interface ServeHostDeps {
|
|
5
|
+
exit?: (code: number) => void;
|
|
6
|
+
signals?: NodeJS.Signals[];
|
|
7
|
+
ready?: (port: number, stop: () => void) => void;
|
|
8
|
+
}
|
|
9
|
+
export interface ServedHost {
|
|
10
|
+
server: Server;
|
|
11
|
+
host: HostedExtension;
|
|
12
|
+
stop: () => void;
|
|
13
|
+
}
|
|
14
|
+
export declare const ORPHAN_MS = 10000;
|
|
15
|
+
export declare const announce: (port: number, stop: () => void, exit?: (code?: number | string | null) => never) => void;
|
|
16
|
+
export declare const serveHost: (env: Env, deps?: ServeHostDeps) => Promise<ServedHost>;
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import {} from 'node:http';
|
|
2
|
+
import {} from 'node:net';
|
|
3
|
+
import { createLog } from '../log/log.js';
|
|
4
|
+
import {} from '../runtime/build-info.js';
|
|
5
|
+
import { listen, shutdownOn } from '../server/serve.js';
|
|
6
|
+
import { guardOf, hostEnvOf } from './host-env.js';
|
|
7
|
+
import { hostWith } from './host-extension.js';
|
|
8
|
+
export const ORPHAN_MS = 10_000;
|
|
9
|
+
// The port to the daemon; the daemon gone (its IPC channel closed): drain and exit, no orphan,
|
|
10
|
+
// within ORPHAN_MS even with a request that never ends.
|
|
11
|
+
export const announce = (port, stop, exit = process.exit) => {
|
|
12
|
+
if (!process.send)
|
|
13
|
+
return;
|
|
14
|
+
process.send({ type: 'ready', port });
|
|
15
|
+
process.once('disconnect', () => {
|
|
16
|
+
stop();
|
|
17
|
+
setTimeout(() => exit(1), ORPHAN_MS).unref();
|
|
18
|
+
});
|
|
19
|
+
};
|
|
20
|
+
// A ctx.exit() before the server listens (in create) runs once it can drain.
|
|
21
|
+
const exitHook = () => {
|
|
22
|
+
let stop;
|
|
23
|
+
let pending = false;
|
|
24
|
+
const onExit = () => (stop ? stop() : (pending = true));
|
|
25
|
+
const arm = (fn) => {
|
|
26
|
+
stop = fn;
|
|
27
|
+
if (pending)
|
|
28
|
+
fn();
|
|
29
|
+
};
|
|
30
|
+
return { onExit, arm };
|
|
31
|
+
};
|
|
32
|
+
// SIGTERM, ctx.exit() and a gone parent drain the server, then stop the host and exit.
|
|
33
|
+
const drainOn = (server, host, deps) => {
|
|
34
|
+
const log = createLog({ extension: host.id, part: 'api', version: host.version });
|
|
35
|
+
const exit = deps.exit ?? ((code) => process.exit(code));
|
|
36
|
+
const done = (code) => void host.stop().finally(() => exit(code));
|
|
37
|
+
const stop = shutdownOn(server, {
|
|
38
|
+
app: host.app,
|
|
39
|
+
port: 0,
|
|
40
|
+
log,
|
|
41
|
+
exit: done,
|
|
42
|
+
signals: deps.signals,
|
|
43
|
+
});
|
|
44
|
+
return { log, stop };
|
|
45
|
+
};
|
|
46
|
+
// The child of the daemon and the one container: one package, /health, a SIGTERM drain.
|
|
47
|
+
export const serveHost = async (env, deps = {}) => {
|
|
48
|
+
const at = hostEnvOf(env);
|
|
49
|
+
const guard = guardOf(env, at);
|
|
50
|
+
const hook = exitHook();
|
|
51
|
+
const { dataDir, settings, origin, secretsDir } = at;
|
|
52
|
+
const opts = { dataDir, settings, origin, onExit: hook.onExit };
|
|
53
|
+
const host = await hostWith(at.dir, opts, { secretsDir, guard });
|
|
54
|
+
const server = await listen(host.app, at.port, at.bind);
|
|
55
|
+
const { log, stop } = drainOn(server, host, deps);
|
|
56
|
+
const { port } = server.address();
|
|
57
|
+
log.info('listening', { port, bind: at.bind });
|
|
58
|
+
(deps.ready ?? announce)(port, stop);
|
|
59
|
+
hook.arm(stop);
|
|
60
|
+
return { server, host, stop };
|
|
61
|
+
};
|
|
@@ -25,7 +25,16 @@ const api = async (input) => {
|
|
|
25
25
|
const { router, routes, documents } = await mountApi(ctx, (api) => callCreate(input, 'api', api));
|
|
26
26
|
// Declared routes guard at their own scope, whatever the committed file says.
|
|
27
27
|
const openapi = routes.length > 0 ? generatedOpenapi(input.pkg, routes) : input.openapi;
|
|
28
|
-
return {
|
|
28
|
+
return {
|
|
29
|
+
app: createApiApp({
|
|
30
|
+
...input.base,
|
|
31
|
+
router,
|
|
32
|
+
routes,
|
|
33
|
+
openapi,
|
|
34
|
+
wellKnown: documents,
|
|
35
|
+
aliases: input.apiAliases,
|
|
36
|
+
}),
|
|
37
|
+
};
|
|
29
38
|
};
|
|
30
39
|
const mcp = async (input) => {
|
|
31
40
|
const registry = createToolRegistry();
|
package/dist/runtime/run-part.js
CHANGED
package/dist/server/app.d.ts
CHANGED
|
@@ -20,6 +20,9 @@ export interface PartAppBase {
|
|
|
20
20
|
checks?: Record<string, HealthCheck>;
|
|
21
21
|
tokenCheck?: TokenCheck;
|
|
22
22
|
resource?: Record<string, unknown>;
|
|
23
|
+
onExit?: () => void;
|
|
24
|
+
instance?: string;
|
|
25
|
+
startedAt?: number;
|
|
23
26
|
}
|
|
24
27
|
export interface PartAppOptions extends PartAppBase {
|
|
25
28
|
part: ImagePartKind;
|
|
@@ -34,6 +37,7 @@ export interface ApiAppOptions extends PartAppBase {
|
|
|
34
37
|
method: string;
|
|
35
38
|
path: string;
|
|
36
39
|
}[];
|
|
40
|
+
aliases?: string[];
|
|
37
41
|
}
|
|
38
42
|
export declare const PUBLIC_CORS: CorsOptions;
|
|
39
43
|
export declare const BODY_LIMIT = "1mb";
|
package/dist/server/app.js
CHANGED
|
@@ -7,6 +7,7 @@ import { routeAccess, sameShape } from '../auth/route-access.js';
|
|
|
7
7
|
import { setCaller } from '../auth/token-check.js';
|
|
8
8
|
import { discoveryDocument, recordOf, } from '../discovery/discovery.js';
|
|
9
9
|
import {} from '../discovery/discovery.schema.js';
|
|
10
|
+
import { apiPrefix } from '../discovery/openapi.js';
|
|
10
11
|
import { createHealthHandler } from '../health/health.js';
|
|
11
12
|
import {} from '../log/log.js';
|
|
12
13
|
import {} from '../manifest/manifest.schema.js';
|
|
@@ -49,6 +50,8 @@ const healthHandler = (options) => createHealthHandler({
|
|
|
49
50
|
build: options.build,
|
|
50
51
|
checks: options.checks,
|
|
51
52
|
log: options.log,
|
|
53
|
+
instance: options.instance,
|
|
54
|
+
startedAt: options.startedAt,
|
|
52
55
|
});
|
|
53
56
|
// The kit app every part image runs: agcid, headers, /health, discovery, the part, the envelope.
|
|
54
57
|
export const createPartApp = (options) => {
|
|
@@ -58,7 +61,7 @@ export const createPartApp = (options) => {
|
|
|
58
61
|
app.use(dropCookie, agcidMiddleware, helmet(options.helmet));
|
|
59
62
|
app.get('/health', healthHandler(options));
|
|
60
63
|
// After /health: it is probed every few seconds and never gets a request line.
|
|
61
|
-
app.use(requestLine(options.log));
|
|
64
|
+
app.use(requestLine(options.log, options.onExit));
|
|
62
65
|
if (options.part !== 'worker') {
|
|
63
66
|
app.use('/.well-known', cors(PUBLIC_CORS));
|
|
64
67
|
app.get('/.well-known/agentage-extension.json', discoveryHandler(options));
|
|
@@ -83,30 +86,37 @@ const wellKnownHandler = (render) => async (_req, res) => {
|
|
|
83
86
|
res.json(doc);
|
|
84
87
|
};
|
|
85
88
|
// Before the body is read: each request checked for the access its OpenAPI operation declares.
|
|
86
|
-
const routeGuard = (options) =>
|
|
87
|
-
const
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
89
|
+
const routeGuard = (options) => {
|
|
90
|
+
const prefix = apiPrefix(options.pkg.agentage.id);
|
|
91
|
+
return async (req, res, next) => {
|
|
92
|
+
const { routes } = options;
|
|
93
|
+
const known = routes?.find((r) => r.method === req.method.toLowerCase() && sameShape(r.path, req.path));
|
|
94
|
+
// The mount as called (an alias too), so the row counts the callers of each prefix.
|
|
95
|
+
if (known)
|
|
96
|
+
res.locals['route'] = `${req.baseUrl.toLowerCase()}${known.path}`;
|
|
97
|
+
if (!options.tokenCheck || (routes?.length && !known))
|
|
98
|
+
return next();
|
|
99
|
+
const access = routeAccess(options.openapi, req.method, `${prefix}${req.path}`);
|
|
100
|
+
const caller = await options.tokenCheck(req.get('authorization'), access);
|
|
101
|
+
if (caller)
|
|
102
|
+
res.setHeader('Cache-Control', 'no-store');
|
|
103
|
+
setCaller(req, caller);
|
|
104
|
+
next();
|
|
105
|
+
};
|
|
99
106
|
};
|
|
100
107
|
export const createApiApp = (options) => createPartApp({
|
|
101
108
|
...options,
|
|
102
109
|
part: 'api',
|
|
103
110
|
mount: (app) => {
|
|
104
|
-
|
|
111
|
+
const prefixes = [apiPrefix(options.pkg.agentage.id), ...(options.aliases ?? [])];
|
|
112
|
+
app.use(prefixes, cors(PUBLIC_CORS));
|
|
105
113
|
for (const { name, render } of options.wellKnown ?? [])
|
|
106
114
|
app.get(`/.well-known/${name}`, wellKnownHandler(render));
|
|
107
|
-
|
|
108
|
-
|
|
115
|
+
const { openapi } = options;
|
|
116
|
+
if (openapi)
|
|
117
|
+
for (const at of prefixes)
|
|
118
|
+
app.get(`${at}/openapi.json`, openapiHandler(openapi));
|
|
109
119
|
const json = express.json({ limit: BODY_LIMIT });
|
|
110
|
-
app.use(
|
|
120
|
+
app.use(prefixes, routeGuard(options), json, options.router);
|
|
111
121
|
},
|
|
112
122
|
});
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import { type Request, type RequestHandler, type Response } from 'express';
|
|
2
2
|
import { type Log } from '../log/log.js';
|
|
3
3
|
export declare const routeOf: (req: Request, res?: Response) => string;
|
|
4
|
-
export declare const requestLine: (log: Log) => RequestHandler;
|
|
4
|
+
export declare const requestLine: (log: Log, onExit?: () => void) => RequestHandler;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {} from 'express';
|
|
2
2
|
import { requestScope, sigtermOnce } from '../agcid/current.js';
|
|
3
3
|
import {} from '../log/log.js';
|
|
4
|
-
const
|
|
4
|
+
const MOUNT = /^\/(?:api\/[^/]+|mcp|\.well-known|ui)(?=\/|$)/;
|
|
5
5
|
const ASSET = /\.(m?js|css|map|png|jpe?g|gif|svg|ico|webp|avif|woff2?|ttf)$/i;
|
|
6
6
|
// The matched route template, never the raw URL, so no id or query string reaches the log.
|
|
7
7
|
export const routeOf = (req, res) => {
|
|
@@ -9,7 +9,7 @@ export const routeOf = (req, res) => {
|
|
|
9
9
|
if (typeof known === 'string')
|
|
10
10
|
return known;
|
|
11
11
|
const url = req.originalUrl?.split('?')[0] ?? '';
|
|
12
|
-
const prefix =
|
|
12
|
+
const prefix = MOUNT.exec(url)?.[0] ?? '';
|
|
13
13
|
const path = req.route?.path;
|
|
14
14
|
if (typeof path !== 'string')
|
|
15
15
|
return '(unmatched)';
|
|
@@ -22,7 +22,7 @@ const localOf = (res, key) => {
|
|
|
22
22
|
return typeof value === 'string' ? value : undefined;
|
|
23
23
|
};
|
|
24
24
|
// One http row per request on finish; a ctx.exit() asked for in it shuts the part down after.
|
|
25
|
-
export const requestLine = (log) => (req, res, next) => {
|
|
25
|
+
export const requestLine = (log, onExit = sigtermOnce) => (req, res, next) => {
|
|
26
26
|
const start = performance.now();
|
|
27
27
|
const scope = requestScope.getStore();
|
|
28
28
|
res.on('finish', () => {
|
|
@@ -38,7 +38,7 @@ export const requestLine = (log) => (req, res, next) => {
|
|
|
38
38
|
clientInfo: localOf(res, 'clientInfo'),
|
|
39
39
|
});
|
|
40
40
|
if (scope?.exit)
|
|
41
|
-
|
|
41
|
+
onExit();
|
|
42
42
|
});
|
|
43
43
|
next();
|
|
44
44
|
};
|
package/dist/server/serve.js
CHANGED
|
@@ -7,6 +7,16 @@ export const listen = (app, port, host) => new Promise((resolve, reject) => {
|
|
|
7
7
|
const done = (err) => (err ? reject(err) : resolve(server));
|
|
8
8
|
const server = host === undefined ? app.listen(port, done) : app.listen(port, host, done);
|
|
9
9
|
});
|
|
10
|
+
// Open requests are answered; a keep-alive connection is closed once idle, not at its timeout.
|
|
11
|
+
const drain = (server, exit) => {
|
|
12
|
+
const idle = setInterval(() => server.closeIdleConnections(), 100).unref();
|
|
13
|
+
server.close((err) => {
|
|
14
|
+
clearInterval(idle);
|
|
15
|
+
exit(err ? 1 : 0);
|
|
16
|
+
});
|
|
17
|
+
server.closeIdleConnections();
|
|
18
|
+
setTimeout(() => exit(1), GRACE_MS).unref();
|
|
19
|
+
};
|
|
10
20
|
// SIGTERM drains; a close error or a drain past the grace period exits 1; a second Ctrl-C at once.
|
|
11
21
|
export const shutdownOn = (server, options) => {
|
|
12
22
|
const exitWith = options.exit ?? ((code) => process.exit(code));
|
|
@@ -24,9 +34,7 @@ export const shutdownOn = (server, options) => {
|
|
|
24
34
|
return;
|
|
25
35
|
stopping = true;
|
|
26
36
|
options.log.info('shutting down');
|
|
27
|
-
server
|
|
28
|
-
server.closeIdleConnections();
|
|
29
|
-
setTimeout(() => exit(1), GRACE_MS).unref();
|
|
37
|
+
drain(server, exit);
|
|
30
38
|
};
|
|
31
39
|
for (const signal of options.signals ?? ['SIGTERM', 'SIGINT'])
|
|
32
40
|
process.on(signal, () => stop(signal));
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { type Row, type Store } from './store.types.js';
|
|
2
|
+
interface PGliteLike {
|
|
3
|
+
query<R>(text: string, params?: unknown[]): Promise<{
|
|
4
|
+
rows: R[];
|
|
5
|
+
}>;
|
|
6
|
+
exec(text: string): Promise<{
|
|
7
|
+
rows: Row[];
|
|
8
|
+
}[]>;
|
|
9
|
+
close(): Promise<void>;
|
|
10
|
+
}
|
|
11
|
+
export interface PgliteStore extends Store {
|
|
12
|
+
close(): Promise<void>;
|
|
13
|
+
}
|
|
14
|
+
export interface StoreAt {
|
|
15
|
+
dataDir?: string;
|
|
16
|
+
from?: string;
|
|
17
|
+
}
|
|
18
|
+
type PGliteModule = {
|
|
19
|
+
PGlite: new (dataDir?: string) => PGliteLike;
|
|
20
|
+
};
|
|
21
|
+
export declare const PGLITE = "@electric-sql/pglite";
|
|
22
|
+
export declare const pgliteMissing: (tried: string[]) => string;
|
|
23
|
+
export declare const loadPglite: (from?: string, kitCopy?: () => Promise<unknown>) => Promise<PGliteModule>;
|
|
24
|
+
export declare const createPgliteStore: (prepare: (store: Store) => Promise<unknown>, at?: StoreAt) => PgliteStore;
|
|
25
|
+
export {};
|