@agentage/extension 0.12.2 → 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.
Files changed (96) hide show
  1. package/README.md +5 -0
  2. package/dist/api/openapi-doc.js +2 -1
  3. package/dist/api/routes.js +1 -1
  4. package/dist/context/context.d.ts +1 -0
  5. package/dist/context/context.js +3 -3
  6. package/dist/context/package-extension.d.ts +2 -0
  7. package/dist/context/package-extension.js +5 -4
  8. package/dist/context/secrets.d.ts +5 -2
  9. package/dist/context/secrets.js +22 -6
  10. package/dist/context/settings.d.ts +4 -0
  11. package/dist/context/settings.js +6 -5
  12. package/dist/context/test-context.js +3 -2
  13. package/dist/discovery/discovery.d.ts +1 -0
  14. package/dist/discovery/discovery.js +7 -3
  15. package/dist/discovery/discovery.schema.d.ts +6 -0
  16. package/dist/discovery/discovery.schema.js +23 -6
  17. package/dist/discovery/openapi.d.ts +2 -1
  18. package/dist/discovery/openapi.js +3 -1
  19. package/dist/host/daemon/child.d.ts +21 -0
  20. package/dist/host/daemon/child.js +92 -0
  21. package/dist/host/daemon/daemon-files.d.ts +19 -0
  22. package/dist/host/daemon/daemon-files.js +23 -0
  23. package/dist/host/daemon/daemon.d.ts +18 -0
  24. package/dist/host/daemon/daemon.js +84 -0
  25. package/dist/host/daemon/guard.d.ts +2 -0
  26. package/dist/host/daemon/guard.js +15 -0
  27. package/dist/host/daemon/installation.d.ts +23 -0
  28. package/dist/host/daemon/installation.js +48 -0
  29. package/dist/host/daemon/installer-call.d.ts +7 -0
  30. package/dist/host/daemon/installer-call.js +22 -0
  31. package/dist/host/daemon/json-file.d.ts +3 -0
  32. package/dist/host/daemon/json-file.js +51 -0
  33. package/dist/host/daemon/lane.d.ts +11 -0
  34. package/dist/host/daemon/lane.js +29 -0
  35. package/dist/host/daemon/ops.d.ts +36 -0
  36. package/dist/host/daemon/ops.js +149 -0
  37. package/dist/host/daemon/proxy.d.ts +5 -0
  38. package/dist/host/daemon/proxy.js +67 -0
  39. package/dist/host/daemon/queue.d.ts +2 -0
  40. package/dist/host/daemon/queue.js +8 -0
  41. package/dist/host/daemon/routes.d.ts +11 -0
  42. package/dist/host/daemon/routes.js +48 -0
  43. package/dist/host/daemon/secret-names.d.ts +1 -0
  44. package/dist/host/daemon/secret-names.js +14 -0
  45. package/dist/host/daemon/setting-values.d.ts +1 -0
  46. package/dist/host/daemon/setting-values.js +26 -0
  47. package/dist/host/daemon/supervisor.d.ts +52 -0
  48. package/dist/host/daemon/supervisor.js +116 -0
  49. package/dist/host/data-lock.d.ts +2 -0
  50. package/dist/host/data-lock.js +81 -0
  51. package/dist/host/host-env.d.ts +17 -0
  52. package/dist/host/host-env.js +36 -0
  53. package/dist/host/host-extension.d.ts +25 -0
  54. package/dist/host/host-extension.js +86 -0
  55. package/dist/host/host-store.d.ts +4 -0
  56. package/dist/host/host-store.js +35 -0
  57. package/dist/host/index.d.ts +3 -0
  58. package/dist/host/index.js +3 -0
  59. package/dist/host/main.d.ts +2 -0
  60. package/dist/host/main.js +10 -0
  61. package/dist/host/serve-host.d.ts +16 -0
  62. package/dist/host/serve-host.js +61 -0
  63. package/dist/manifest/manifest.schema.d.ts +9 -1
  64. package/dist/manifest/manifest.schema.js +13 -2
  65. package/dist/manifest/parts.d.ts +6 -0
  66. package/dist/manifest/parts.js +8 -0
  67. package/dist/manifest/primitives.schema.d.ts +7 -0
  68. package/dist/manifest/primitives.schema.js +2 -0
  69. package/dist/runtime/part-runners.d.ts +1 -0
  70. package/dist/runtime/part-runners.js +10 -1
  71. package/dist/runtime/run-part.js +3 -2
  72. package/dist/server/app.d.ts +4 -0
  73. package/dist/server/app.js +28 -18
  74. package/dist/server/request-line.d.ts +1 -1
  75. package/dist/server/request-line.js +4 -4
  76. package/dist/server/serve.js +11 -3
  77. package/dist/store/pglite-store.d.ts +25 -0
  78. package/dist/store/pglite-store.js +59 -0
  79. package/dist/store/test-store.d.ts +2 -3
  80. package/dist/store/test-store.js +3 -38
  81. package/dist/testing/test-server.d.ts +2 -0
  82. package/dist/testing/test-server.js +1 -1
  83. package/dist/tool/record-extras.js +2 -2
  84. package/dist/tool/rules/surface.js +6 -6
  85. package/dist/tool/up/compose.js +3 -2
  86. package/dist/tool/up/gateway.d.ts +6 -2
  87. package/dist/tool/up/gateway.js +10 -7
  88. package/dist/tool/up/local-record.d.ts +1 -0
  89. package/dist/tool/up/secrets.js +2 -1
  90. package/dist/tool/up/token.js +1 -1
  91. package/dist/tool/up/up.js +2 -2
  92. package/dist/vendor/logs/events-client.js +1 -1
  93. package/package.json +5 -1
  94. package/schemas/extension-discovery.schema.json +1 -1
  95. package/schemas/extension-package.schema.json +35 -3
  96. package/schemas/extension-record.schema.json +21 -1
@@ -0,0 +1,116 @@
1
+ import { fail } from '../../envelope/envelope.js';
2
+ import {} from '../../log/log.js';
3
+ import { readManifest } from '../../manifest/read-manifest.js';
4
+ import {} from './child.js';
5
+ import { dataDirOf, readValues } from './daemon-files.js';
6
+ import {} from './installation.js';
7
+ import { laneOf, retire } from './lane.js';
8
+ import { runInstaller } from './installer-call.js';
9
+ import {} from './queue.js';
10
+ export const GATE_MS = 30_000;
11
+ export const DRAIN_MS = 10_000;
12
+ export const HEALTH_MS = 60_000;
13
+ export const valuesOf = async (configDir, id) => ({
14
+ settings: await readValues(configDir, 'settings', id),
15
+ secrets: (await readValues(configDir, 'secrets', id)),
16
+ });
17
+ // The package folder: the source itself, the folder an install gave, or the installer again.
18
+ const dirOf = async (deps, entry, install, given) => {
19
+ if (given)
20
+ return given;
21
+ if (install.source)
22
+ return install.source;
23
+ if (entry.dir && install.version === entry.install.version)
24
+ return entry.dir;
25
+ return (await runInstaller(deps, { id: entry.id, version: install.version })).dir;
26
+ };
27
+ // Healthy before it gets the route: the child's own /health answers 200.
28
+ const healthy = async (port, ms) => {
29
+ const signal = AbortSignal.timeout(ms);
30
+ const res = await fetch(`http://127.0.0.1:${port}/health`, { signal }).catch(() => {
31
+ throw new Error(`health did not answer in ${ms} ms`);
32
+ });
33
+ if (res.status !== 200)
34
+ throw new Error(`health answered ${res.status}`);
35
+ };
36
+ // A new child for install with values, healthy; the entry learns the version the package has.
37
+ export const launchFor = async (deps, entry, install, values, given) => {
38
+ const dir = await dirOf(deps, entry, install, given);
39
+ const pkg = await readManifest(dir);
40
+ const spec = { id: entry.id, dir, dataDir: dataDirOf(deps.configDir, entry.id), ...values };
41
+ const child = await deps.launch({ ...spec, origin: deps.origin() });
42
+ await healthy(child.port, deps.healthMs).catch(async (err) => {
43
+ await child.stop();
44
+ throw err;
45
+ });
46
+ Object.assign(entry, { dir, version: pkg.version });
47
+ const lane = laneOf(child, pkg.version);
48
+ void child.exited.then((how) => exitedEarly(deps, entry, lane, how));
49
+ return lane;
50
+ };
51
+ // A child that exits while it is the route is failed; a retired one was detached first.
52
+ const exitedEarly = (deps, entry, lane, how) => {
53
+ if (entry.lane !== lane)
54
+ return;
55
+ const why = how.signal ? `signal ${how.signal}` : `code ${how.code}`;
56
+ Object.assign(entry, { lane: undefined, state: 'failed', error: `the process exited (${why})` });
57
+ deps.log.warn('extension process exited', { id: entry.id });
58
+ };
59
+ const failed = (deps, entry, err) => {
60
+ Object.assign(entry, { state: 'failed', error: err.message });
61
+ deps.log.warn('extension failed to start', { id: entry.id, reason: entry.error });
62
+ };
63
+ // The install and values of installation.json, as they are on disk.
64
+ export const startEntry = async (deps, entry) => {
65
+ entry.state = 'starting';
66
+ try {
67
+ const values = await valuesOf(deps.configDir, entry.id);
68
+ entry.lane = await launchFor(deps, entry, entry.install, values);
69
+ Object.assign(entry, { state: 'running', error: undefined });
70
+ }
71
+ catch (err) {
72
+ failed(deps, entry, err);
73
+ }
74
+ };
75
+ // New requests of the extension wait here (the proxy gives up after GATE_MS) until release.
76
+ const hold = (entry) => {
77
+ let release = () => undefined;
78
+ entry.gate = new Promise((resolve) => (release = resolve));
79
+ return () => {
80
+ entry.gate = undefined;
81
+ release();
82
+ };
83
+ };
84
+ // The old install again after a refused change; a disabled one stays stopped.
85
+ const restore = async (deps, entry) => {
86
+ if (entry.install.enabled === false)
87
+ entry.state = 'disabled';
88
+ else
89
+ await startEntry(deps, entry);
90
+ };
91
+ export const startFailed = (entry, err) => fail('VALIDATION_ERROR', `${entry.id} failed to start with this change: ${err.message}`, {
92
+ code: 'START_FAILED',
93
+ });
94
+ // One writer per data folder, so one sequence for every extension, running or not: hold, drain
95
+ // and stop the old child, start the new one, release. A refusal restores the old one and is a 400.
96
+ export const swap = async (deps, entry, to) => {
97
+ const release = hold(entry);
98
+ try {
99
+ await halt(entry, deps.drainMs);
100
+ entry.lane = await launchFor(deps, entry, to.install, to.values, to.dir);
101
+ Object.assign(entry, { state: 'running', error: undefined });
102
+ }
103
+ catch (err) {
104
+ await restore(deps, entry);
105
+ throw startFailed(entry, err);
106
+ }
107
+ finally {
108
+ release();
109
+ }
110
+ };
111
+ // Detached first, so its exit is not a failure; then drained and stopped.
112
+ export const halt = async (entry, drainMs) => {
113
+ const lane = entry.lane;
114
+ entry.lane = undefined;
115
+ await retire(lane, drainMs);
116
+ };
@@ -0,0 +1,2 @@
1
+ export declare const DATA_DIR_LOCKED = "DATA_DIR_LOCKED";
2
+ export declare const lockDataDir: (dataDir: string) => Promise<() => Promise<void>>;
@@ -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,3 @@
1
+ export { createDaemon, DAEMON_PORT, type Daemon, type DaemonOptions } from './daemon/daemon.js';
2
+ export { type Installer, type State } from './daemon/supervisor.js';
3
+ export { hostExtension, type HostedExtension, type HostOptions } from './host-extension.js';
@@ -0,0 +1,3 @@
1
+ export { createDaemon, DAEMON_PORT } from './daemon/daemon.js';
2
+ export {} from './daemon/supervisor.js';
3
+ 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,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
+ };
@@ -117,7 +117,15 @@ export declare const PackageSchema: z.ZodObject<{
117
117
  enum: z.ZodOptional<z.ZodArray<z.ZodString>>;
118
118
  description: z.ZodOptional<z.ZodString>;
119
119
  }, z.core.$strict>>>;
120
- secrets: z.ZodOptional<z.ZodArray<z.ZodString>>;
120
+ secrets: z.ZodOptional<z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
121
+ name: z.ZodString;
122
+ parts: z.ZodArray<z.ZodEnum<{
123
+ pages: "pages";
124
+ api: "api";
125
+ mcp: "mcp";
126
+ worker: "worker";
127
+ }>>;
128
+ }, z.core.$strict>]>>>;
121
129
  }, z.core.$strict>;
122
130
  }, z.core.$loose>;
123
131
  export type CodePart = z.infer<typeof CodePartSchema>;
@@ -1,5 +1,5 @@
1
1
  import { z } from 'zod';
2
- import { CommandNameSchema, ExtensionIdSchema, FIRST_PARTY_IDS, PackageNameSchema, PackagePathSchema, SecretNameSchema, SemverRangeSchema, SettingKeySchema, StoreKindSchema, VersionSchema, } from './primitives.schema.js';
2
+ import { camelName, CommandNameSchema, ExtensionIdSchema, FIRST_PARTY_IDS, PackageNameSchema, PackagePathSchema, SecretNameSchema, SecretPartSchema, SemverRangeSchema, SettingKeySchema, StoreKindSchema, VersionSchema, } from './primitives.schema.js';
3
3
  const CodePartSchema = z.union([
4
4
  z.boolean(),
5
5
  z.strictObject({ entry: PackagePathSchema.optional() }),
@@ -47,12 +47,17 @@ const SettingSchema = z
47
47
  .refine((setting) => !setting.enum || setting.enum.includes(String(setting.default)), {
48
48
  message: 'default is not one of enum',
49
49
  });
50
+ // A plain name goes to every part but ui; the object form to the parts it names only.
51
+ const SecretSchema = z.union([
52
+ SecretNameSchema,
53
+ z.strictObject({ name: SecretNameSchema, parts: z.array(SecretPartSchema).min(1) }),
54
+ ]);
50
55
  const AgentageBaseSchema = z.strictObject({
51
56
  id: ExtensionIdSchema,
52
57
  parts: PartsSchema,
53
58
  commands: z.array(CommandSchema).min(1).optional(),
54
59
  settings: z.record(SettingKeySchema, SettingSchema).optional(),
55
- secrets: z.array(SecretNameSchema).optional(),
60
+ secrets: z.array(SecretSchema).optional(),
56
61
  });
57
62
  const AgentageSchema = AgentageBaseSchema.superRefine(crossFieldRules);
58
63
  export const PackageSchema = z
@@ -87,6 +92,12 @@ function crossFieldRules(manifest, ctx) {
87
92
  const names = (manifest.commands ?? []).map((command) => command.name);
88
93
  if (new Set(names).size !== names.length)
89
94
  issue('command names must be unique', ['commands']);
95
+ for (const s of manifest.secrets ?? [])
96
+ if (typeof s === 'object' && s.parts.some((part) => !isOn(manifest.parts[part])))
97
+ issue(`secret ${s.name} names a part the extension does not have`, ['secrets']);
98
+ const ids = (manifest.secrets ?? []).map((s) => camelName(typeof s === 'string' ? s : s.name));
99
+ if (new Set(ids).size !== ids.length)
100
+ issue('secret names must be unique', ['secrets']);
90
101
  if (manifest.settings?.['mcp.listing'] && !isOn(manifest.parts.mcp)) {
91
102
  issue('mcp.listing needs the mcp part', ['settings', 'mcp.listing']);
92
103
  }
@@ -9,6 +9,12 @@ export interface NormalizedParts {
9
9
  export declare const normalizeParts: (parts: Parts) => NormalizedParts;
10
10
  export declare const imageParts: (pkg: ExtensionPackage) => ImagePartKind[];
11
11
  export declare const entryOf: (pkg: ExtensionPackage, part: ImagePartKind | "cli") => string;
12
+ export declare const secretNames: (pkg: ExtensionPackage) => string[];
13
+ export declare const scopedSecrets: (pkg: ExtensionPackage) => {
14
+ [k: string]: ("pages" | "api" | "mcp" | "worker")[];
15
+ };
16
+ export declare const mountedIn: (pkg: ExtensionPackage, part: ImagePartKind, names?: string[]) => string[];
17
+ export declare const unmountedIn: (pkg: ExtensionPackage | undefined, part: ImagePartKind) => string[];
12
18
  export declare const storeOf: (pkg: ExtensionPackage) => StoreKind | undefined;
13
19
  export declare const hasStore: (pkg: ExtensionPackage, kind: StoreKind) => boolean;
14
20
  export declare const migratesStore: (pkg: ExtensionPackage) => boolean;
@@ -22,6 +22,14 @@ export const imageParts = (pkg) => {
22
22
  return IMAGE_PART_KINDS.filter((kind) => code[kind] !== undefined);
23
23
  };
24
24
  export const entryOf = (pkg, part) => normalizeParts(pkg.agentage.parts).code[part]?.entry ?? `./dist/${part}/index.js`;
25
+ export const secretNames = (pkg) => (pkg.agentage.secrets ?? []).map((s) => (typeof s === 'string' ? s : s.name));
26
+ const scopedOf = (pkg) => (pkg.agentage.secrets ?? []).flatMap((s) => (typeof s === 'string' ? [] : [s]));
27
+ export const scopedSecrets = (pkg) => Object.fromEntries(scopedOf(pkg).map((s) => [s.name, s.parts]));
28
+ export const mountedIn = (pkg, part, names = secretNames(pkg)) => {
29
+ const scoped = new Map(scopedOf(pkg).map((s) => [s.name, s.parts]));
30
+ return names.filter((n) => part !== 'ui' && (scoped.get(n)?.includes(part) ?? true));
31
+ };
32
+ export const unmountedIn = (pkg, part) => pkg ? secretNames(pkg).filter((n) => !mountedIn(pkg, part).includes(n)) : [];
25
33
  export const storeOf = (pkg) => normalizeParts(pkg.agentage.parts).store;
26
34
  export const hasStore = (pkg, kind) => storeOf(pkg) === kind;
27
35
  // The migrate rule: the api image carries migrations/ and a migrate job only for such a kind.
@@ -34,4 +34,11 @@ export declare const CommitSchema: z.ZodString;
34
34
  export declare const PrefixedToolNameSchema: z.ZodString;
35
35
  export declare const IMAGE_PART_KINDS: readonly ["pages", "ui", "api", "mcp", "worker"];
36
36
  export type ImagePartKind = (typeof IMAGE_PART_KINDS)[number];
37
+ export declare const camelName: (name: string) => string;
38
+ export declare const SecretPartSchema: z.ZodEnum<{
39
+ pages: "pages";
40
+ api: "api";
41
+ mcp: "mcp";
42
+ worker: "worker";
43
+ }>;
37
44
  export type StoreKind = keyof typeof STORE_KINDS;
@@ -60,3 +60,5 @@ export const PrefixedToolNameSchema = z
60
60
  .max(64)
61
61
  .regex(/^[a-z][a-z0-9-]*__[a-z][a-z0-9_-]*$/);
62
62
  export const IMAGE_PART_KINDS = ['pages', 'ui', 'api', 'mcp', 'worker'];
63
+ export const camelName = (name) => name.replace(/-([a-z0-9])/g, (_, c) => c.toUpperCase());
64
+ export const SecretPartSchema = z.enum(['pages', 'api', 'mcp', 'worker']);
@@ -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();