@agentage/extension 0.12.3 → 0.14.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.
Files changed (119) hide show
  1. package/dist/api/openapi-doc.js +2 -1
  2. package/dist/api/routes.js +1 -1
  3. package/dist/context/context.d.ts +1 -0
  4. package/dist/context/context.js +3 -3
  5. package/dist/context/secrets.d.ts +1 -0
  6. package/dist/context/secrets.js +7 -5
  7. package/dist/context/settings.d.ts +4 -0
  8. package/dist/context/settings.js +6 -5
  9. package/dist/discovery/discovery.d.ts +1 -0
  10. package/dist/discovery/discovery.schema.d.ts +2 -0
  11. package/dist/discovery/discovery.schema.js +30 -12
  12. package/dist/discovery/openapi.d.ts +2 -1
  13. package/dist/discovery/openapi.js +3 -1
  14. package/dist/host/daemon/add.d.ts +9 -0
  15. package/dist/host/daemon/add.js +63 -0
  16. package/dist/host/daemon/child.d.ts +23 -0
  17. package/dist/host/daemon/child.js +100 -0
  18. package/dist/host/daemon/daemon-files.d.ts +17 -0
  19. package/dist/host/daemon/daemon-files.js +27 -0
  20. package/dist/host/daemon/daemon-owner.d.ts +1 -0
  21. package/dist/host/daemon/daemon-owner.js +32 -0
  22. package/dist/host/daemon/daemon.d.ts +17 -0
  23. package/dist/host/daemon/daemon.js +106 -0
  24. package/dist/host/daemon/entries.d.ts +21 -0
  25. package/dist/host/daemon/entries.js +24 -0
  26. package/dist/host/daemon/guard.d.ts +2 -0
  27. package/dist/host/daemon/guard.js +16 -0
  28. package/dist/host/daemon/installation.d.ts +36 -0
  29. package/dist/host/daemon/installation.js +92 -0
  30. package/dist/host/daemon/installer-call.d.ts +21 -0
  31. package/dist/host/daemon/installer-call.js +48 -0
  32. package/dist/host/daemon/json-file.d.ts +4 -0
  33. package/dist/host/daemon/json-file.js +62 -0
  34. package/dist/host/daemon/lane.d.ts +9 -0
  35. package/dist/host/daemon/lane.js +24 -0
  36. package/dist/host/daemon/limits.d.ts +11 -0
  37. package/dist/host/daemon/limits.js +22 -0
  38. package/dist/host/daemon/ops.d.ts +12 -0
  39. package/dist/host/daemon/ops.js +89 -0
  40. package/dist/host/daemon/patch-values.d.ts +6 -0
  41. package/dist/host/daemon/patch-values.js +39 -0
  42. package/dist/host/daemon/pending.d.ts +15 -0
  43. package/dist/host/daemon/pending.js +18 -0
  44. package/dist/host/daemon/proxy.d.ts +6 -0
  45. package/dist/host/daemon/proxy.js +89 -0
  46. package/dist/host/daemon/queue.d.ts +3 -0
  47. package/dist/host/daemon/queue.js +27 -0
  48. package/dist/host/daemon/routes.d.ts +13 -0
  49. package/dist/host/daemon/routes.js +98 -0
  50. package/dist/host/daemon/stopping.d.ts +10 -0
  51. package/dist/host/daemon/stopping.js +28 -0
  52. package/dist/host/daemon/supervisor.d.ts +54 -0
  53. package/dist/host/daemon/supervisor.js +115 -0
  54. package/dist/host/daemon/write-all.d.ts +8 -0
  55. package/dist/host/daemon/write-all.js +45 -0
  56. package/dist/host/data-lock.d.ts +3 -0
  57. package/dist/host/data-lock.js +121 -0
  58. package/dist/host/host-env.d.ts +18 -0
  59. package/dist/host/host-env.js +42 -0
  60. package/dist/host/host-extension.d.ts +29 -0
  61. package/dist/host/host-extension.js +91 -0
  62. package/dist/host/host-store.d.ts +11 -0
  63. package/dist/host/host-store.js +49 -0
  64. package/dist/host/index.d.ts +7 -0
  65. package/dist/host/index.js +7 -0
  66. package/dist/host/main.d.ts +2 -0
  67. package/dist/host/main.js +10 -0
  68. package/dist/host/serve-host.d.ts +17 -0
  69. package/dist/host/serve-host.js +64 -0
  70. package/dist/runtime/part-runners.d.ts +1 -0
  71. package/dist/runtime/part-runners.js +10 -1
  72. package/dist/runtime/run-part.js +2 -0
  73. package/dist/server/app.d.ts +6 -1
  74. package/dist/server/app.js +29 -19
  75. package/dist/server/request-line.d.ts +1 -1
  76. package/dist/server/request-line.js +4 -4
  77. package/dist/server/serve.d.ts +3 -0
  78. package/dist/server/serve.js +17 -4
  79. package/dist/store/pglite-store.d.ts +25 -0
  80. package/dist/store/pglite-store.js +59 -0
  81. package/dist/store/test-store.d.ts +2 -3
  82. package/dist/store/test-store.js +3 -38
  83. package/dist/testing/test-server.d.ts +2 -0
  84. package/dist/testing/test-server.js +1 -1
  85. package/dist/tool/build.d.ts +3 -0
  86. package/dist/tool/build.js +42 -27
  87. package/dist/tool/capabilities.d.ts +1 -0
  88. package/dist/tool/capabilities.js +8 -0
  89. package/dist/tool/container-parts.d.ts +7 -0
  90. package/dist/tool/container-parts.js +10 -0
  91. package/dist/tool/container-recipe.d.ts +4 -0
  92. package/dist/tool/container-recipe.js +55 -0
  93. package/dist/tool/container-stage.d.ts +3 -0
  94. package/dist/tool/container-stage.js +51 -0
  95. package/dist/tool/container.d.ts +73 -0
  96. package/dist/tool/container.js +28 -0
  97. package/dist/tool/docker.d.ts +5 -0
  98. package/dist/tool/docker.js +15 -0
  99. package/dist/tool/format.js +12 -5
  100. package/dist/tool/index.d.ts +2 -0
  101. package/dist/tool/index.js +2 -0
  102. package/dist/tool/kit-version.d.ts +1 -0
  103. package/dist/tool/kit-version.js +16 -2
  104. package/dist/tool/labels.d.ts +1 -1
  105. package/dist/tool/labels.js +4 -2
  106. package/dist/tool/main.js +10 -1
  107. package/dist/tool/record-extras.js +2 -2
  108. package/dist/tool/rules/surface.js +6 -6
  109. package/dist/tool/stage.d.ts +1 -0
  110. package/dist/tool/stage.js +1 -1
  111. package/dist/tool/up/gateway.d.ts +6 -2
  112. package/dist/tool/up/gateway.js +10 -7
  113. package/dist/tool/up/local-record.d.ts +1 -0
  114. package/dist/tool/up/token.js +1 -1
  115. package/dist/tool/up/up.js +2 -2
  116. package/dist/vendor/logs/events-client.js +1 -1
  117. package/package.json +5 -1
  118. package/schemas/extension-discovery.schema.json +8 -1
  119. package/schemas/extension-record.schema.json +8 -1
@@ -0,0 +1,121 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { rmSync } from 'node:fs';
3
+ import { link, readFile, unlink, writeFile } from 'node:fs/promises';
4
+ import { setTimeout as sleep } from 'node:timers/promises';
5
+ export const DATA_DIR_LOCKED = 'DATA_DIR_LOCKED';
6
+ // The locks of this process: our own pid in a lock not in here is stale (a container is pid 1 again).
7
+ const held = new Set();
8
+ const alive = (pid) => {
9
+ try {
10
+ return process.kill(pid, 0);
11
+ }
12
+ catch (err) {
13
+ return err.code === 'EPERM';
14
+ }
15
+ };
16
+ // A lock made with wx is empty until its pid is written (slow on a network volume): being written
17
+ // for EMPTY_LOCK_MS, then stale.
18
+ export const EMPTY_LOCK_MS = 1_000;
19
+ const pidIn = (file) => readFile(file, 'utf8').catch(() => '0');
20
+ const holder = async (file) => {
21
+ const until = Date.now() + EMPTY_LOCK_MS;
22
+ let pid = await pidIn(file);
23
+ while (pid === '' && Date.now() < until) {
24
+ await sleep(25);
25
+ pid = await pidIn(file);
26
+ }
27
+ return Number(pid);
28
+ };
29
+ const live = (lock, pid) => pid === process.pid ? held.has(lock) : pid > 0 && alive(pid);
30
+ const locked = (lock, pid) => Object.assign(new Error(`${lock.slice(0, -5)} is open in process ${pid}`), {
31
+ code: DATA_DIR_LOCKED,
32
+ pid,
33
+ });
34
+ const exists = (err) => err.code === 'EEXIST';
35
+ // No hard links on the volume (some network or FUSE mounts): an exclusive create, then the pid.
36
+ const create = async (lock, pid) => {
37
+ try {
38
+ await writeFile(lock, String(pid), { flag: 'wx' });
39
+ return true;
40
+ }
41
+ catch (err) {
42
+ if (!exists(err))
43
+ throw err;
44
+ return false;
45
+ }
46
+ };
47
+ // The lock file at once (a link of a full file), or by create where links fail; false: it exists.
48
+ const place = async (from, lock, pid) => {
49
+ try {
50
+ await link(from, lock);
51
+ return true;
52
+ }
53
+ catch (err) {
54
+ return exists(err) ? false : create(lock, pid);
55
+ }
56
+ };
57
+ const unique = (file) => `${file}.${process.pid}.${randomBytes(4).toString('hex')}`;
58
+ // A full lock file appears at once or not at all: written aside, then linked (fails if one exists).
59
+ const take = async (lock) => {
60
+ const tmp = unique(lock);
61
+ await writeFile(tmp, String(process.pid));
62
+ try {
63
+ const taken = await place(tmp, lock, process.pid);
64
+ if (taken)
65
+ held.add(lock);
66
+ return taken;
67
+ }
68
+ finally {
69
+ await unlink(tmp).catch(() => undefined);
70
+ }
71
+ };
72
+ // A guard left by a breaker that died is removed and taken once more.
73
+ const takeDeadGuard = async (guard) => {
74
+ if (live(guard, await holder(guard)))
75
+ return false;
76
+ await unlink(guard).catch(() => undefined);
77
+ return take(guard);
78
+ };
79
+ // One breaker at a time (<lock>.break): the lock is removed only while it still names the dead pid.
80
+ const breakStale = async (lock, pid) => {
81
+ const guard = `${lock}.break`;
82
+ if (!(await take(guard)) && !(await takeDeadGuard(guard)))
83
+ throw locked(lock, await holder(guard));
84
+ try {
85
+ if ((await holder(lock)) === pid)
86
+ await unlink(lock).catch(() => undefined);
87
+ }
88
+ finally {
89
+ rmSync(guard, { force: true });
90
+ held.delete(guard);
91
+ }
92
+ };
93
+ const turns = new Map();
94
+ // One taker per lock in this process: none sees our pid in the file before it is in held.
95
+ const inTurn = (lock, fn) => {
96
+ const run = (turns.get(lock) ?? Promise.resolve()).then(fn, fn);
97
+ const tail = run.catch(() => undefined);
98
+ turns.set(lock, tail);
99
+ void tail.then(() => turns.get(lock) === tail && turns.delete(lock));
100
+ return run;
101
+ };
102
+ const acquire = async (lock) => {
103
+ if (await take(lock))
104
+ return;
105
+ const pid = await holder(lock);
106
+ if (live(lock, pid))
107
+ throw locked(lock, pid);
108
+ await breakStale(lock, pid);
109
+ if (!(await take(lock)))
110
+ throw locked(lock, await holder(lock));
111
+ };
112
+ // PGlite has one writer per folder: <dataDir>.lock holds the pid; a dead holder's lock is taken over.
113
+ export const lockDataDir = async (dataDir) => {
114
+ const lock = `${dataDir}.lock`;
115
+ await inTurn(lock, () => acquire(lock));
116
+ // Sync, so no other taker in this process sees the file without its entry in held.
117
+ return async () => {
118
+ rmSync(lock, { force: true });
119
+ held.delete(lock);
120
+ };
121
+ };
@@ -0,0 +1,18 @@
1
+ import { type Env } from '../runtime/build-info.js';
2
+ import { type HostExtras } from './host-extension.js';
3
+ export declare const BIND_REFUSED = "AGENTAGE_HOST_BIND=all needs a token check (AGENTAGE_ISSUER, AGENTAGE_AUDIENCE, AGENTAGE_ORIGIN) or AGENTAGE_HOST_AUTH=off";
4
+ export declare const hostEnvOf: (env: Env) => {
5
+ dir: string;
6
+ port: number;
7
+ bind: string;
8
+ dataDir: string;
9
+ settings: Record<string, unknown>;
10
+ secretsDir: string;
11
+ origin: string;
12
+ drainMs: number;
13
+ storeOpenMs: number;
14
+ };
15
+ export declare const guardOf: (env: Env, { bind, dir }: {
16
+ bind: string;
17
+ dir: string;
18
+ }) => HostExtras["guard"];
@@ -0,0 +1,42 @@
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 { GRACE_MS } from '../server/serve.js';
9
+ import { CONTAINER_PORT } from '../tool/container-recipe.js';
10
+ import {} from './host-extension.js';
11
+ import { STORE_OPEN_MS } from './host-store.js';
12
+ export const BIND_REFUSED = 'AGENTAGE_HOST_BIND=all needs a token check (AGENTAGE_ISSUER, AGENTAGE_AUDIENCE, AGENTAGE_ORIGIN) or AGENTAGE_HOST_AUTH=off';
13
+ const TOKEN_ENV = ['AGENTAGE_ISSUER', 'AGENTAGE_AUDIENCE', 'AGENTAGE_ORIGIN'];
14
+ // A limit: a positive integer of ms, else the default.
15
+ const msOf = (value = '', fallback) => /^[1-9][0-9]*$/.test(value) ? Number(value) : fallback;
16
+ // The entry's env with its defaults: port 8080, the current folder, loopback.
17
+ export const hostEnvOf = (env) => {
18
+ const port = portFromEnv(env, CONTAINER_PORT);
19
+ return {
20
+ dir: env['AGENTAGE_EXTENSION_DIR'] || process.cwd(),
21
+ port,
22
+ bind: env['AGENTAGE_HOST_BIND'] === 'all' ? '0.0.0.0' : '127.0.0.1',
23
+ dataDir: env['AGENTAGE_DATA_DIR'] ?? '',
24
+ settings: env['AGENTAGE_SETTINGS'] ? parseObject(env['AGENTAGE_SETTINGS']) : {},
25
+ secretsDir: env['AGENTAGE_SECRETS_DIR'] || SECRETS_DIR,
26
+ origin: env['AGENTAGE_ORIGIN'] || `http://127.0.0.1${port ? `:${port}` : ''}`,
27
+ drainMs: msOf(env['AGENTAGE_DRAIN_MS'], GRACE_MS),
28
+ storeOpenMs: msOf(env['AGENTAGE_STORE_OPEN_MS'], STORE_OPEN_MS),
29
+ };
30
+ };
31
+ // Loopback: no token check. Every address: the cloud part's check, or an explicit AGENTAGE_HOST_AUTH=off.
32
+ export const guardOf = (env, { bind, dir }) => {
33
+ if (bind === '127.0.0.1' || env['AGENTAGE_HOST_AUTH'] === 'off')
34
+ return undefined;
35
+ if (TOKEN_ENV.some((key) => !env[key]))
36
+ throw new Error(BIND_REFUSED);
37
+ return async (pkg, log) => {
38
+ const { id } = pkg.agentage;
39
+ const scopes = declaredScopes(id, await readOpenapi(dir));
40
+ return partAuth(env, id, log, scopes);
41
+ };
42
+ };
@@ -0,0 +1,29 @@
1
+ import { type Express } from 'express';
2
+ import { type BuildInfo } from '../discovery/discovery.js';
3
+ import { type HealthBody } from '../health/health.schema.js';
4
+ import { type Log } from '../log/log.js';
5
+ import { type ExtensionPackage } from '../manifest/manifest.schema.js';
6
+ import { type PartAppBase } from '../server/app.js';
7
+ export interface HostOptions {
8
+ dataDir: string;
9
+ settings?: Record<string, unknown>;
10
+ secrets?: Record<string, string>;
11
+ onExit?: () => void;
12
+ origin?: string;
13
+ localOnly?: boolean;
14
+ storeOpenMs?: number;
15
+ }
16
+ export interface HostedExtension {
17
+ id: string;
18
+ version: string;
19
+ app: Express;
20
+ stop(): Promise<void>;
21
+ health(): Promise<HealthBody>;
22
+ }
23
+ export interface HostExtras {
24
+ secretsDir?: string;
25
+ guard?: (pkg: ExtensionPackage, log: Log) => Promise<Partial<PartAppBase>>;
26
+ build?: BuildInfo;
27
+ }
28
+ export declare const hostWith: (dir: string, opts: HostOptions, extras: HostExtras) => Promise<HostedExtension>;
29
+ export declare const hostExtension: (dir: string, opts: HostOptions) => Promise<HostedExtension>;
@@ -0,0 +1,91 @@
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 {} from '../discovery/discovery.js';
7
+ import { readOpenapi } from '../discovery/openapi.js';
8
+ import { healthBody } from '../health/health.js';
9
+ import {} from '../health/health.schema.js';
10
+ import { createLog } from '../log/log.js';
11
+ import {} from '../manifest/manifest.schema.js';
12
+ import { normalizeParts } from '../manifest/parts.js';
13
+ import { readManifest } from '../manifest/read-manifest.js';
14
+ import { buildInfoFromEnv } from '../runtime/build-info.js';
15
+ import { RUNNERS } from '../runtime/part-runners.js';
16
+ import { createPartApp } from '../server/app.js';
17
+ import { storeCheck } from '../store/store.js';
18
+ import {} from '../store/pglite-store.js';
19
+ import { localOnly } from './daemon/guard.js';
20
+ import { openHostStore, STORE_OPEN_MS } from './host-store.js';
21
+ const once = (fn) => {
22
+ let done = false;
23
+ return () => {
24
+ if (done)
25
+ return;
26
+ done = true;
27
+ fn();
28
+ };
29
+ };
30
+ const secretsOf = ({ pkg, opts, extras }) => extras.secretsDir
31
+ ? readSecrets(pkg, 'api', extras.secretsDir)
32
+ : secretsFrom(pkg, 'api', async (name) => opts.secrets?.[name] ?? '');
33
+ // createContext with the host's values: settings and secrets as given, no platform.
34
+ const contextOf = async (h, checks) => createContext({
35
+ pkg: h.pkg,
36
+ part: 'api',
37
+ origin: h.opts.origin ?? 'http://127.0.0.1',
38
+ commit: h.build.commit,
39
+ log: h.log,
40
+ settings: settingsOf(h.pkg, h.opts.settings ?? {}, h.log),
41
+ store: h.store,
42
+ secrets: await secretsOf(h),
43
+ checks,
44
+ onExit: h.onExit,
45
+ });
46
+ // The api part of the package; a package without one serves /health only.
47
+ const appOf = async (h, base) => {
48
+ if (!normalizeParts(h.pkg.agentage.parts).code.api)
49
+ return createPartApp({ ...base, part: 'api', mount: () => undefined });
50
+ const ctx = await contextOf(h, base.checks ?? {});
51
+ const openapi = await readOpenapi(h.dir);
52
+ return (await RUNNERS.api({ dir: h.dir, pkg: h.pkg, env: {}, ctx: () => ctx, base, openapi }))
53
+ .app;
54
+ };
55
+ const baseOf = async (h) => {
56
+ const guard = (await h.extras.guard?.(h.pkg, h.log)) ?? {};
57
+ const checks = { ...(h.store && { store: storeCheck(h.store) }), ...guard.checks };
58
+ const resolved = { instance: randomBytes(4).toString('hex'), startedAt: Date.now() };
59
+ const guards = h.opts.localOnly ? [localOnly()] : undefined;
60
+ const { pkg, log, build, onExit } = h;
61
+ return { pkg, log, build, onExit, guards, ...guard, checks, ...resolved };
62
+ };
63
+ const hostedOf = (h, app, base) => {
64
+ const { id } = h.pkg.agentage;
65
+ const { version } = h.pkg;
66
+ const { instance = '', startedAt = 0, build, checks } = base;
67
+ const health = () => healthBody({ extension: id, part: 'api', version, build, checks, instance, startedAt });
68
+ let stopped;
69
+ const stop = () => (stopped ??= h.store ? h.store.close() : Promise.resolve());
70
+ return { id, version, app, health, stop };
71
+ };
72
+ // hostExtension with the extras of the entry (dist/host/main.js).
73
+ export const hostWith = async (dir, opts, extras) => {
74
+ const pkg = await readManifest(dir);
75
+ const log = createLog({ extension: pkg.agentage.id, part: 'api', version: pkg.version });
76
+ const openMs = opts.storeOpenMs ?? STORE_OPEN_MS;
77
+ const store = await openHostStore(pkg, { dir, dataDir: opts.dataDir, openMs }, log);
78
+ const onExit = once(opts.onExit ?? (() => undefined));
79
+ const build = extras.build ?? buildInfoFromEnv({});
80
+ const h = { dir, pkg, log, opts, extras, store, onExit, build };
81
+ try {
82
+ const base = await baseOf(h);
83
+ return hostedOf(h, await appOf(h, base), base);
84
+ }
85
+ catch (err) {
86
+ await store?.close();
87
+ throw err;
88
+ }
89
+ };
90
+ // One extension in this process: its api at /api/{id}/*, no token check, its own settings, secrets, store and log.
91
+ export const hostExtension = (dir, opts) => hostWith(dir, opts, {});
@@ -0,0 +1,11 @@
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 STORE_OPEN_MS = 120000;
5
+ interface StoreAt {
6
+ dir: string;
7
+ dataDir: string;
8
+ openMs: number;
9
+ }
10
+ export declare const openHostStore: (pkg: ExtensionPackage, at: StoreAt, log: Log) => Promise<PgliteStore | undefined>;
11
+ export {};
@@ -0,0 +1,49 @@
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
+ // How long the host waits for the store to open (and to close); the daemon sets its healthMs.
10
+ export const STORE_OPEN_MS = 120_000;
11
+ const within = (work, ms) => Promise.race([
12
+ work,
13
+ new Promise((resolve) => setTimeout(() => resolve('late'), ms).unref()),
14
+ ]);
15
+ // A close past openMs keeps the data lock: PGlite may still write there until the process exits.
16
+ const closer = (store, release, openMs) => async () => {
17
+ const closed = await within(store.close().catch(() => undefined), openMs);
18
+ if (closed !== 'late')
19
+ await release();
20
+ };
21
+ // Locks dataDir, then opens PGlite in it and migrates; past openMs the part starts, /health says not ready.
22
+ const open = async (at, log) => {
23
+ const { dir, dataDir, openMs } = at;
24
+ if (dataDir)
25
+ await mkdir(dataDir, { recursive: true });
26
+ const release = dataDir ? await lockDataDir(dataDir) : unlocked;
27
+ const store = createPgliteStore((s) => migrate(s, dir, log), {
28
+ dataDir: dataDir || undefined,
29
+ from: dir,
30
+ });
31
+ const close = closer(store, release, openMs);
32
+ const opened = store.query('select 1').catch(async (err) => {
33
+ await close();
34
+ throw err;
35
+ });
36
+ if ((await within(opened, openMs)) === 'late') {
37
+ opened.catch(() => undefined);
38
+ log.warn('the store did not open in time: /health says unavailable until it does', { openMs });
39
+ }
40
+ return { query: store.query, close };
41
+ };
42
+ // A postgres store as PGlite with its files in dataDir; none set keeps it in memory.
43
+ export const openHostStore = async (pkg, at, log) => {
44
+ if (!hasStore(pkg, 'postgres'))
45
+ return undefined;
46
+ if (!at.dataDir)
47
+ log.warn('no data folder: the store is in memory and lost on exit');
48
+ return open(at, log);
49
+ };
@@ -0,0 +1,7 @@
1
+ export { capabilities } from '../tool/capabilities.js';
2
+ export { localOnly } from './daemon/guard.js';
3
+ export { createDaemon, DAEMON_PORT, type Daemon, type DaemonOptions } from './daemon/daemon.js';
4
+ export { type Installer, type State } from './daemon/supervisor.js';
5
+ export { withFileLock } from './daemon/json-file.js';
6
+ export { updateInstallation, type InstallEntry, type Installation } from './daemon/installation.js';
7
+ export { hostExtension, type HostedExtension, type HostOptions } from './host-extension.js';
@@ -0,0 +1,7 @@
1
+ export { capabilities } from '../tool/capabilities.js';
2
+ export { localOnly } from './daemon/guard.js';
3
+ export { createDaemon, DAEMON_PORT } from './daemon/daemon.js';
4
+ export {} from './daemon/supervisor.js';
5
+ export { withFileLock } from './daemon/json-file.js';
6
+ export { updateInstallation } from './daemon/installation.js';
7
+ export { hostExtension } from './host-extension.js';
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -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,17 @@
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
+ 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>;
17
+ export {};
@@ -0,0 +1,64 @@
1
+ import {} from 'node:http';
2
+ import {} from 'node:net';
3
+ import { setTimeout as sleep } from 'node:timers/promises';
4
+ import { createLog } from '../log/log.js';
5
+ import { buildInfoFromEnv } from '../runtime/build-info.js';
6
+ import { listen, shutdownOn } from '../server/serve.js';
7
+ import { guardOf, hostEnvOf } from './host-env.js';
8
+ import { hostWith } from './host-extension.js';
9
+ export const ORPHAN_MS = 10_000;
10
+ // The port to the daemon; its IPC channel closed: drain, and exit within ORPHAN_MS in any case.
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, graceMs) => {
34
+ const log = createLog({ extension: host.id, part: 'api', version: host.version });
35
+ const exit = deps.exit ?? ((code) => process.exit(code));
36
+ // A store close that hangs gets graceMs too, so the process always exits.
37
+ const closed = () => Promise.race([host.stop(), sleep(graceMs, undefined, { ref: false })]);
38
+ const done = (code) => void closed().finally(() => exit(code));
39
+ const stop = shutdownOn(server, {
40
+ app: host.app,
41
+ port: 0,
42
+ log,
43
+ exit: done,
44
+ signals: deps.signals,
45
+ graceMs,
46
+ });
47
+ return { log, stop };
48
+ };
49
+ // The child of the daemon and the one container: one package, /health, a SIGTERM drain.
50
+ export const serveHost = async (env, deps = {}) => {
51
+ const at = hostEnvOf(env);
52
+ const guard = guardOf(env, at);
53
+ const hook = exitHook();
54
+ const { dataDir, settings, origin, secretsDir, storeOpenMs } = at;
55
+ const opts = { dataDir, settings, origin, storeOpenMs, onExit: hook.onExit };
56
+ const host = await hostWith(at.dir, opts, { secretsDir, guard, build: buildInfoFromEnv(env) });
57
+ const server = await listen(host.app, at.port, at.bind);
58
+ const { log, stop } = drainOn(server, host, deps, at.drainMs);
59
+ const { port } = server.address();
60
+ log.info('listening', { port, bind: at.bind });
61
+ (deps.ready ?? announce)(port, stop);
62
+ hook.arm(stop);
63
+ return { server, host, stop };
64
+ };
@@ -13,6 +13,7 @@ export interface RunnerInput {
13
13
  base: PartAppBase;
14
14
  openapi: Record<string, unknown> | null;
15
15
  importModule?: ImportModule;
16
+ apiAliases?: string[];
16
17
  }
17
18
  export interface Running {
18
19
  app: Express;
@@ -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 { app: createApiApp({ ...input.base, router, routes, openapi, wellKnown: documents }) };
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();
@@ -89,6 +89,8 @@ const inputFor = async (options, start) => {
89
89
  base,
90
90
  openapi,
91
91
  importModule: options.importModule,
92
+ // The old prefix as a second mount, so next stays green; it goes in phase 4.
93
+ apiAliases: ['/api/v1'],
92
94
  };
93
95
  };
94
96
  let running;
@@ -1,5 +1,5 @@
1
1
  import { type CorsOptions } from 'cors';
2
- import { type Express } from 'express';
2
+ import { type Express, type RequestHandler } from 'express';
3
3
  import { type HelmetOptions } from 'helmet';
4
4
  import { type WellKnownEntry } from '../api/well-known.js';
5
5
  import { type TokenCheck } from '../auth/token-check.js';
@@ -20,6 +20,10 @@ 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;
26
+ guards?: RequestHandler[];
23
27
  }
24
28
  export interface PartAppOptions extends PartAppBase {
25
29
  part: ImagePartKind;
@@ -34,6 +38,7 @@ export interface ApiAppOptions extends PartAppBase {
34
38
  method: string;
35
39
  path: string;
36
40
  }[];
41
+ aliases?: string[];
37
42
  }
38
43
  export declare const PUBLIC_CORS: CorsOptions;
39
44
  export declare const BODY_LIMIT = "1mb";
@@ -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,16 +50,18 @@ 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) => {
55
58
  const app = express();
56
59
  // The gateway calls parts over a private network; its X-Forwarded-Proto then sets req.protocol.
57
60
  app.set('trust proxy', 'loopback, linklocal, uniquelocal');
58
- app.use(dropCookie, agcidMiddleware, helmet(options.helmet));
61
+ app.use(dropCookie, agcidMiddleware, helmet(options.helmet), ...(options.guards ?? []));
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) => async (req, res, next) => {
87
- const { routes } = options;
88
- const known = routes?.find((r) => r.method === req.method.toLowerCase() && sameShape(r.path, req.path));
89
- if (known)
90
- res.locals['route'] = `/api/v1${known.path}`;
91
- if (!options.tokenCheck || (routes?.length && !known))
92
- return next();
93
- const access = routeAccess(options.openapi, req.method, `/api/v1${req.path}`);
94
- const caller = await options.tokenCheck(req.get('authorization'), access);
95
- if (caller)
96
- res.setHeader('Cache-Control', 'no-store');
97
- setCaller(req, caller);
98
- next();
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
- app.use('/api/v1', cors(PUBLIC_CORS));
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
- if (options.openapi)
108
- app.get('/api/v1/openapi.json', openapiHandler(options.openapi));
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('/api/v1', routeGuard(options), json, options.router);
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;