@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.
Files changed (79) 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.schema.js +8 -2
  10. package/dist/discovery/openapi.d.ts +2 -1
  11. package/dist/discovery/openapi.js +3 -1
  12. package/dist/host/daemon/child.d.ts +21 -0
  13. package/dist/host/daemon/child.js +92 -0
  14. package/dist/host/daemon/daemon-files.d.ts +19 -0
  15. package/dist/host/daemon/daemon-files.js +23 -0
  16. package/dist/host/daemon/daemon.d.ts +18 -0
  17. package/dist/host/daemon/daemon.js +84 -0
  18. package/dist/host/daemon/guard.d.ts +2 -0
  19. package/dist/host/daemon/guard.js +15 -0
  20. package/dist/host/daemon/installation.d.ts +23 -0
  21. package/dist/host/daemon/installation.js +48 -0
  22. package/dist/host/daemon/installer-call.d.ts +7 -0
  23. package/dist/host/daemon/installer-call.js +22 -0
  24. package/dist/host/daemon/json-file.d.ts +3 -0
  25. package/dist/host/daemon/json-file.js +51 -0
  26. package/dist/host/daemon/lane.d.ts +11 -0
  27. package/dist/host/daemon/lane.js +29 -0
  28. package/dist/host/daemon/ops.d.ts +36 -0
  29. package/dist/host/daemon/ops.js +149 -0
  30. package/dist/host/daemon/proxy.d.ts +5 -0
  31. package/dist/host/daemon/proxy.js +67 -0
  32. package/dist/host/daemon/queue.d.ts +2 -0
  33. package/dist/host/daemon/queue.js +8 -0
  34. package/dist/host/daemon/routes.d.ts +11 -0
  35. package/dist/host/daemon/routes.js +48 -0
  36. package/dist/host/daemon/secret-names.d.ts +1 -0
  37. package/dist/host/daemon/secret-names.js +14 -0
  38. package/dist/host/daemon/setting-values.d.ts +1 -0
  39. package/dist/host/daemon/setting-values.js +26 -0
  40. package/dist/host/daemon/supervisor.d.ts +52 -0
  41. package/dist/host/daemon/supervisor.js +116 -0
  42. package/dist/host/data-lock.d.ts +2 -0
  43. package/dist/host/data-lock.js +81 -0
  44. package/dist/host/host-env.d.ts +17 -0
  45. package/dist/host/host-env.js +36 -0
  46. package/dist/host/host-extension.d.ts +25 -0
  47. package/dist/host/host-extension.js +86 -0
  48. package/dist/host/host-store.d.ts +4 -0
  49. package/dist/host/host-store.js +35 -0
  50. package/dist/host/index.d.ts +3 -0
  51. package/dist/host/index.js +3 -0
  52. package/dist/host/main.d.ts +2 -0
  53. package/dist/host/main.js +10 -0
  54. package/dist/host/serve-host.d.ts +16 -0
  55. package/dist/host/serve-host.js +61 -0
  56. package/dist/runtime/part-runners.d.ts +1 -0
  57. package/dist/runtime/part-runners.js +10 -1
  58. package/dist/runtime/run-part.js +2 -0
  59. package/dist/server/app.d.ts +4 -0
  60. package/dist/server/app.js +28 -18
  61. package/dist/server/request-line.d.ts +1 -1
  62. package/dist/server/request-line.js +4 -4
  63. package/dist/server/serve.js +11 -3
  64. package/dist/store/pglite-store.d.ts +25 -0
  65. package/dist/store/pglite-store.js +59 -0
  66. package/dist/store/test-store.d.ts +2 -3
  67. package/dist/store/test-store.js +3 -38
  68. package/dist/testing/test-server.d.ts +2 -0
  69. package/dist/testing/test-server.js +1 -1
  70. package/dist/tool/record-extras.js +2 -2
  71. package/dist/tool/rules/surface.js +6 -6
  72. package/dist/tool/up/gateway.d.ts +6 -2
  73. package/dist/tool/up/gateway.js +10 -7
  74. package/dist/tool/up/token.js +1 -1
  75. package/dist/tool/up/up.js +2 -2
  76. package/dist/vendor/logs/events-client.js +1 -1
  77. package/package.json +5 -1
  78. package/schemas/extension-discovery.schema.json +1 -1
  79. package/schemas/extension-record.schema.json +1 -1
@@ -0,0 +1,11 @@
1
+ import { type Child } from './child.js';
2
+ export interface Lane {
3
+ child: Child;
4
+ version: string;
5
+ open: number;
6
+ idle: (() => void)[];
7
+ }
8
+ export declare const laneOf: (child: Child, version: string) => Lane;
9
+ export declare const enter: (lane: Lane) => (() => void);
10
+ export declare const drained: (lane: Lane) => Promise<void>;
11
+ export declare const retire: (lane: Lane | undefined, drainMs: number) => Promise<void>;
@@ -0,0 +1,29 @@
1
+ import {} from './child.js';
2
+ export const laneOf = (child, version) => ({
3
+ child,
4
+ version,
5
+ open: 0,
6
+ idle: [],
7
+ });
8
+ // Counts one request until leave() is called (once).
9
+ export const enter = (lane) => {
10
+ lane.open += 1;
11
+ let left = false;
12
+ return () => {
13
+ if (left)
14
+ return;
15
+ left = true;
16
+ lane.open -= 1;
17
+ if (lane.open === 0)
18
+ lane.idle.splice(0).forEach((resolve) => resolve());
19
+ };
20
+ };
21
+ export const drained = (lane) => lane.open === 0 ? Promise.resolve() : new Promise((resolve) => lane.idle.push(resolve));
22
+ const waited = (ms) => new Promise((resolve) => setTimeout(resolve, ms).unref());
23
+ // Waits for the open requests (at most drainMs, so a hung one blocks nothing), then stops the child.
24
+ export const retire = async (lane, drainMs) => {
25
+ if (!lane)
26
+ return;
27
+ await Promise.race([drained(lane), waited(drainMs)]);
28
+ await lane.child.stop();
29
+ };
@@ -0,0 +1,36 @@
1
+ import { type Entry, type SupervisorDeps } from './supervisor.js';
2
+ export declare const RESERVED_ID = "host";
3
+ export type Entries = Map<string, Entry>;
4
+ export declare const summary: ({ id, version, state, error, lane }: Entry) => {
5
+ error?: string | undefined;
6
+ pid?: number | undefined;
7
+ id: string;
8
+ version: string;
9
+ state: import("./supervisor.js").State;
10
+ };
11
+ export declare const listed: (entry: Entry) => {
12
+ source: string;
13
+ enabled: boolean;
14
+ error?: string | undefined;
15
+ pid?: number | undefined;
16
+ id: string;
17
+ version: string;
18
+ state: import("./supervisor.js").State;
19
+ };
20
+ export declare const addExtension: (deps: SupervisorDeps, entries: Entries, body: unknown) => Promise<{
21
+ error?: string | undefined;
22
+ pid?: number | undefined;
23
+ id: string;
24
+ version: string;
25
+ state: import("./supervisor.js").State;
26
+ }>;
27
+ export declare const changeExtension: (deps: SupervisorDeps, entries: Entries, id: string, body: unknown) => Promise<{
28
+ error?: string | undefined;
29
+ pid?: number | undefined;
30
+ id: string;
31
+ version: string;
32
+ state: import("./supervisor.js").State;
33
+ }>;
34
+ export declare const removeExtension: (deps: SupervisorDeps, entries: Entries, id: string, purge: boolean) => Promise<{
35
+ id: string;
36
+ }>;
@@ -0,0 +1,149 @@
1
+ import { isAbsolute } from 'node:path';
2
+ import { z } from 'zod';
3
+ import { fail } from '../../envelope/envelope.js';
4
+ import { parse } from '../../envelope/parse.js';
5
+ import { ExtensionIdSchema, SecretNameSchema } from '../../manifest/primitives.schema.js';
6
+ import { readManifest } from '../../manifest/read-manifest.js';
7
+ import { purgeData, writeValues } from './daemon-files.js';
8
+ import { runInstaller } from './installer-call.js';
9
+ import { checkSecrets } from './secret-names.js';
10
+ import { coerceSettings } from './setting-values.js';
11
+ import { updateInstallation, withEntry } from './installation.js';
12
+ import { halt, startEntry, swap, valuesOf, } from './supervisor.js';
13
+ export const RESERVED_ID = 'host';
14
+ const AddSchema = z.union([
15
+ z.strictObject({ id: ExtensionIdSchema, version: z.string().min(1).optional() }),
16
+ z.strictObject({ source: z.string().refine(isAbsolute, 'an absolute path') }),
17
+ ]);
18
+ const PatchSchema = z.strictObject({
19
+ version: z.string().min(1).optional(),
20
+ enabled: z.boolean().optional(),
21
+ settings: z.record(z.string(), z.unknown()).optional(),
22
+ secrets: z.record(SecretNameSchema, z.string()).optional(),
23
+ });
24
+ // pid of a running child: the e2e teardown reads it.
25
+ export const summary = ({ id, version, state, error, lane }) => ({
26
+ id,
27
+ version,
28
+ state,
29
+ ...(lane && { pid: lane.child.pid }),
30
+ ...(error && { error }),
31
+ });
32
+ export const listed = (entry) => ({
33
+ ...summary(entry),
34
+ source: entry.install.source ?? 'market',
35
+ enabled: entry.install.enabled !== false,
36
+ });
37
+ const reserve = (entries, id) => {
38
+ if (id === RESERVED_ID)
39
+ throw fail('VALIDATION_ERROR', 'the id host is reserved');
40
+ if (entries.has(id))
41
+ throw fail('CONFLICT', `${id} is installed`);
42
+ };
43
+ const sourceEntry = async (source) => {
44
+ const pkg = await readManifest(source).catch((err) => {
45
+ throw fail('VALIDATION_ERROR', `${source}: ${err.message}`);
46
+ });
47
+ return { install: { id: pkg.agentage.id, source }, dir: source };
48
+ };
49
+ const marketEntry = async (deps, entries, id, version) => {
50
+ reserve(entries, id);
51
+ const got = await runInstaller(deps, { id, version });
52
+ return { install: { id: got.id, version: got.version }, dir: got.dir };
53
+ };
54
+ const persist = (deps, id, install) => updateInstallation(deps.configDir, (doc) => withEntry(doc, id, install));
55
+ // POST: installs (or links a folder), records it, starts it; a failed start stays listed as failed.
56
+ export const addExtension = async (deps, entries, body) => {
57
+ const spec = parse(AddSchema, body, 'Invalid body');
58
+ const { install, dir } = 'source' in spec
59
+ ? await sourceEntry(spec.source)
60
+ : await marketEntry(deps, entries, spec.id, spec.version);
61
+ reserve(entries, install.id);
62
+ const entry = {
63
+ id: install.id,
64
+ install,
65
+ state: 'starting',
66
+ version: '',
67
+ dir,
68
+ };
69
+ entries.set(entry.id, entry);
70
+ await persist(deps, entry.id, install);
71
+ await startEntry(deps, entry);
72
+ return summary(entry);
73
+ };
74
+ const entryOf = (entries, id) => {
75
+ const entry = entries.get(id);
76
+ if (!entry)
77
+ throw fail('NOT_FOUND', `${id} is not installed`);
78
+ return entry;
79
+ };
80
+ // The install entry a patch asks for; a new version is installed first and its folder kept aside.
81
+ const nextInstall = async (deps, entry, patch) => {
82
+ // enabled absent means true (C3), so only false is written.
83
+ const install = { ...entry.install };
84
+ delete install.enabled;
85
+ if ((patch.enabled ?? entry.install.enabled) === false)
86
+ install.enabled = false;
87
+ if (!patch.version)
88
+ return { install };
89
+ if (install.source)
90
+ throw fail('VALIDATION_ERROR', `${entry.id} runs a folder: it has no version`);
91
+ const got = await runInstaller(deps, { id: entry.id, version: patch.version });
92
+ return { install: { ...install, version: got.version }, dir: got.dir };
93
+ };
94
+ const nextOf = async (deps, entry, patch) => {
95
+ const next = await nextInstall(deps, entry, patch);
96
+ const dir = next.dir ?? entry.dir ?? entry.install.source;
97
+ await checkSecrets(dir, Object.keys(patch.secrets ?? {}), entry.id);
98
+ const given = await coerceSettings(dir, patch.settings ?? {}, entry.id);
99
+ const was = await valuesOf(deps.configDir, entry.id);
100
+ const settings = { ...was.settings, ...given };
101
+ return { ...next, values: { settings, secrets: { ...was.secrets, ...patch.secrets } } };
102
+ };
103
+ const save = async (deps, entry, to) => {
104
+ Object.assign(entry, { install: to.install }, to.dir && { dir: to.dir });
105
+ await persist(deps, entry.id, to.install);
106
+ await writeValues(deps.configDir, 'settings', entry.id, to.values.settings);
107
+ await writeValues(deps.configDir, 'secrets', entry.id, to.values.secrets);
108
+ };
109
+ // A change that could not be written stops the new child and starts the old one from the files.
110
+ const saveOrRestore = async (deps, entry, to, dir) => {
111
+ const was = entry.install;
112
+ await save(deps, entry, to).catch(async (err) => {
113
+ Object.assign(entry, { install: was, dir });
114
+ await halt(entry, deps.drainMs);
115
+ await startEntry(deps, entry);
116
+ throw err;
117
+ });
118
+ };
119
+ // Disabled: stopped. Else one rule, running or not: the swap, then the files; values persist
120
+ // only once the new child runs.
121
+ const apply = async (deps, entry, to) => {
122
+ if (to.install.enabled === false) {
123
+ await halt(entry, deps.drainMs);
124
+ entry.state = 'disabled';
125
+ return save(deps, entry, to);
126
+ }
127
+ const dir = entry.dir;
128
+ await swap(deps, entry, to);
129
+ await saveOrRestore(deps, entry, to, dir);
130
+ };
131
+ // PATCH: a refused change keeps the old one and is 400 START_FAILED.
132
+ export const changeExtension = async (deps, entries, id, body) => {
133
+ const patch = parse(PatchSchema, body, 'Invalid body');
134
+ const entry = entryOf(entries, id);
135
+ await apply(deps, entry, await nextOf(deps, entry, patch));
136
+ return summary(entry);
137
+ };
138
+ // DELETE: stops the child, forgets its settings and secrets; purge also deletes its data folder.
139
+ export const removeExtension = async (deps, entries, id, purge) => {
140
+ const entry = entryOf(entries, id);
141
+ entries.delete(id);
142
+ await halt(entry, deps.drainMs);
143
+ await persist(deps, id);
144
+ await writeValues(deps.configDir, 'settings', id);
145
+ await writeValues(deps.configDir, 'secrets', id);
146
+ if (purge)
147
+ await purgeData(deps.configDir, id);
148
+ return { id };
149
+ };
@@ -0,0 +1,5 @@
1
+ import { type IncomingHttpHeaders } from 'node:http';
2
+ import { type RequestHandler } from 'express';
3
+ import { type Entries } from './ops.js';
4
+ export declare const endToEnd: (headers: IncomingHttpHeaders) => IncomingHttpHeaders;
5
+ export declare const proxyTo: (entries: Entries, gateMs?: number) => RequestHandler;
@@ -0,0 +1,67 @@
1
+ import { request } from 'node:http';
2
+ import {} from 'express';
3
+ import { fail } from '../../envelope/envelope.js';
4
+ import { enter } from './lane.js';
5
+ import {} from './ops.js';
6
+ import { GATE_MS } from './supervisor.js';
7
+ const waited = (ms) => new Promise((resolve) => setTimeout(resolve, ms).unref());
8
+ // 404 not installed or disabled (chosen, not to retry); 503 starting, failed, or held past gateMs.
9
+ const laneFor = async (entries, id, gateMs) => {
10
+ const entry = entries.get(id);
11
+ if (!entry)
12
+ throw fail('NOT_FOUND', `${id} is not installed`);
13
+ if (entry.state === 'disabled')
14
+ throw fail('NOT_FOUND', `${id} is disabled`);
15
+ if (entry.gate)
16
+ await Promise.race([entry.gate, waited(gateMs)]);
17
+ if (!entry.lane)
18
+ throw fail('UNAVAILABLE', `${id} is ${entry.state}`, { retryAfter: 5 });
19
+ return entry.lane;
20
+ };
21
+ const HOP = [
22
+ 'connection',
23
+ 'keep-alive',
24
+ 'proxy-authenticate',
25
+ 'proxy-authorization',
26
+ 'te',
27
+ 'trailer',
28
+ 'transfer-encoding',
29
+ 'upgrade',
30
+ ];
31
+ // RFC 9110 7.6.1: hop-by-hop headers, and those the Connection header names, stay on their hop.
32
+ export const endToEnd = (headers) => {
33
+ const named = String(headers['connection'] ?? '')
34
+ .toLowerCase()
35
+ .split(',');
36
+ const drop = new Set([...HOP, ...named.map((h) => h.trim())]);
37
+ return Object.fromEntries(Object.entries(headers).filter(([key]) => !drop.has(key)));
38
+ };
39
+ const answer = (res) => (up) => {
40
+ res.writeHead(up.statusCode ?? 502, endToEnd(up.headers));
41
+ up.pipe(res);
42
+ };
43
+ // Streams the request to the child as it came (path and query kept), no pooled connection.
44
+ const forward = (req, res, next, lane) => {
45
+ const leave = enter(lane);
46
+ const { method, originalUrl: path } = req;
47
+ const headers = endToEnd(req.headers);
48
+ const options = { host: '127.0.0.1', port: lane.child.port, method, path, headers, agent: false };
49
+ const upstream = request(options, answer(res));
50
+ // A client that went away aborts the request to the child too.
51
+ res.on('close', () => {
52
+ if (!res.writableFinished)
53
+ upstream.destroy();
54
+ leave();
55
+ });
56
+ upstream.on('error', () => {
57
+ leave();
58
+ if (res.headersSent)
59
+ return void res.destroy();
60
+ next(fail('UNAVAILABLE', 'The extension did not answer', { retryAfter: 5 }));
61
+ });
62
+ req.pipe(upstream);
63
+ };
64
+ export const proxyTo = (entries, gateMs = GATE_MS) => async (req, res, next) => {
65
+ const lane = await laneFor(entries, String(req.params['id']), gateMs);
66
+ forward(req, res, next, lane);
67
+ };
@@ -0,0 +1,2 @@
1
+ export type Queue = <T>(fn: () => Promise<T>) => Promise<T>;
2
+ export declare const serialQueue: () => Queue;
@@ -0,0 +1,8 @@
1
+ export const serialQueue = () => {
2
+ let chain = Promise.resolve();
3
+ return (fn) => {
4
+ const run = chain.then(fn, fn);
5
+ chain = run.catch(() => undefined);
6
+ return run;
7
+ };
8
+ };
@@ -0,0 +1,11 @@
1
+ import { type Express } from 'express';
2
+ import { type Entries } from './ops.js';
3
+ import { type SupervisorDeps } from './supervisor.js';
4
+ export declare const DAEMON_SERVICE = "agentage-daemon";
5
+ export interface DaemonInfo {
6
+ version: string;
7
+ pid: number;
8
+ protocol: number;
9
+ invalid: boolean;
10
+ }
11
+ export declare const daemonApp: (deps: SupervisorDeps, entries: Entries, port: () => number, info: DaemonInfo) => Express;
@@ -0,0 +1,48 @@
1
+ import express, {} from 'express';
2
+ import { agcidMiddleware } from '../../agcid/scope.js';
3
+ import { ok } from '../../envelope/envelope.js';
4
+ import { BODY_LIMIT } from '../../server/app.js';
5
+ import { errorHandler, notFound } from '../../server/errors.js';
6
+ import { localOnly } from './guard.js';
7
+ import { addExtension, changeExtension, listed, removeExtension, summary, } from './ops.js';
8
+ import { proxyTo } from './proxy.js';
9
+ import {} from './supervisor.js';
10
+ // What /health says of the daemon itself: the values of daemon.json, so a client can prove it.
11
+ export const DAEMON_SERVICE = 'agentage-daemon';
12
+ const healthOf = (entries, { version, pid, protocol, invalid }) => {
13
+ const all = [...entries.values()];
14
+ const settled = !invalid && all.every((e) => e.state === 'running' || e.state === 'disabled');
15
+ const extensions = all.map(summary);
16
+ const status = settled ? 'ok' : 'degraded';
17
+ const self = { service: DAEMON_SERVICE, pid, protocol };
18
+ return { status, version, ...self, extensions, ...(invalid && { installation: 'invalid' }) };
19
+ };
20
+ const changes = (deps, entries) => {
21
+ const run = deps.queue;
22
+ const id = (params) => String(params['id']);
23
+ const add = async (req, res) => void res.status(201).json(ok(await run(() => addExtension(deps, entries, req.body))));
24
+ const change = async (req, res) => void res.json(ok(await run(() => changeExtension(deps, entries, id(req.params), req.body))));
25
+ const purge = (q) => q['purge'] === 'true';
26
+ const remove = async (req, res) => void res.json(ok(await run(() => removeExtension(deps, entries, id(req.params), purge(req.query)))));
27
+ return { add, change, remove };
28
+ };
29
+ const hostRoutes = (app, deps, entries) => {
30
+ app.get('/host/extensions', (_req, res) => void res.json(ok([...entries.values()].map(listed))));
31
+ const json = express.json({ limit: BODY_LIMIT });
32
+ const { add, change, remove } = changes(deps, entries);
33
+ app.post('/host/extensions', json, add);
34
+ app.patch('/host/extensions/:id', json, change);
35
+ app.delete('/host/extensions/:id', remove);
36
+ };
37
+ // C5: /health, /host/extensions, and /api/{id}/* to the child of that id; Host and Origin first.
38
+ export const daemonApp = (deps, entries, port, info) => {
39
+ const app = express();
40
+ app.disable('x-powered-by');
41
+ app.use(agcidMiddleware, localOnly(port));
42
+ app.use('/api/:id', proxyTo(entries));
43
+ app.get('/health', (_req, res) => void res.set('Cache-Control', 'no-store').json(healthOf(entries, info)));
44
+ hostRoutes(app, deps, entries);
45
+ app.use(notFound);
46
+ app.use(errorHandler(deps.log));
47
+ return app;
48
+ };
@@ -0,0 +1 @@
1
+ export declare const checkSecrets: (dir: string | undefined, names: string[], id: string) => Promise<void>;
@@ -0,0 +1,14 @@
1
+ import { fail } from '../../envelope/envelope.js';
2
+ import { readManifest } from '../../manifest/read-manifest.js';
3
+ const declared = (secrets = []) => secrets.map((s) => (typeof s === 'string' ? s : s.name));
4
+ // Only a secret the package declares: the name becomes a file name in the child's folder.
5
+ export const checkSecrets = async (dir, names, id) => {
6
+ if (!names.length)
7
+ return;
8
+ if (!dir)
9
+ throw fail('VALIDATION_ERROR', `${id} has no package yet: install it first`);
10
+ const known = declared((await readManifest(dir)).agentage.secrets);
11
+ const unknown = names.filter((name) => !known.includes(name));
12
+ if (unknown.length)
13
+ throw fail('VALIDATION_ERROR', `${id} declares no secret ${unknown.join(', ')}`);
14
+ };
@@ -0,0 +1 @@
1
+ export declare const coerceSettings: (dir: string | undefined, given: Record<string, unknown>, id: string) => Promise<Record<string, unknown>>;
@@ -0,0 +1,26 @@
1
+ import { fits } from '../../context/settings.js';
2
+ import { fail } from '../../envelope/envelope.js';
3
+ import { readManifest } from '../../manifest/read-manifest.js';
4
+ const PARSE = {
5
+ number: (t) => (/^-?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?$/i.test(t) ? Number(t) : t),
6
+ integer: (t) => (/^-?\d+$/.test(t) ? Number(t) : t),
7
+ boolean: (t) => (t === 'true' ? true : t === 'false' ? false : t),
8
+ };
9
+ const refused = (key, message) => fail('VALIDATION_ERROR', `setting ${key}: ${message}`, { code: 'INVALID_SETTING' });
10
+ const valueOf = (key, setting, given) => {
11
+ if (!setting)
12
+ throw refused(key, 'not declared in the manifest');
13
+ const value = typeof given === 'string' ? (PARSE[setting.type]?.(given) ?? given) : given;
14
+ if (!fits(setting, value))
15
+ throw refused(key, `${JSON.stringify(given)} is not a valid ${setting.type}`);
16
+ return value;
17
+ };
18
+ // A client sends text (`configure probe limit=5`): a string becomes the type the manifest declares.
19
+ export const coerceSettings = async (dir, given, id) => {
20
+ if (!Object.keys(given).length)
21
+ return given;
22
+ if (!dir)
23
+ throw fail('VALIDATION_ERROR', `${id} has no package yet: install it first`);
24
+ const declared = (await readManifest(dir)).agentage.settings ?? {};
25
+ return Object.fromEntries(Object.entries(given).map(([key, value]) => [key, valueOf(key, declared[key], value)]));
26
+ };
@@ -0,0 +1,52 @@
1
+ import { type Log } from '../../log/log.js';
2
+ import { type Launch } from './child.js';
3
+ import { type InstallEntry } from './installation.js';
4
+ import { type Lane } from './lane.js';
5
+ import { type Queue } from './queue.js';
6
+ export declare const GATE_MS = 30000;
7
+ export type Installer = (spec: {
8
+ id: string;
9
+ version?: string;
10
+ }) => Promise<{
11
+ id: string;
12
+ version: string;
13
+ dir: string;
14
+ }>;
15
+ export type State = 'starting' | 'running' | 'failed' | 'disabled';
16
+ export interface Entry {
17
+ id: string;
18
+ install: InstallEntry;
19
+ state: State;
20
+ version: string;
21
+ dir?: string;
22
+ error?: string;
23
+ lane?: Lane;
24
+ gate?: Promise<void>;
25
+ }
26
+ export interface Values {
27
+ settings: Record<string, unknown>;
28
+ secrets: Record<string, string>;
29
+ }
30
+ export interface Next {
31
+ install: InstallEntry;
32
+ values: Values;
33
+ dir?: string;
34
+ }
35
+ export interface SupervisorDeps {
36
+ configDir: string;
37
+ launch: Launch;
38
+ origin: () => string;
39
+ install?: Installer;
40
+ log: Log;
41
+ drainMs: number;
42
+ healthMs: number;
43
+ queue: Queue;
44
+ }
45
+ export declare const DRAIN_MS = 10000;
46
+ export declare const HEALTH_MS = 60000;
47
+ export declare const valuesOf: (configDir: string, id: string) => Promise<Values>;
48
+ export declare const launchFor: (deps: SupervisorDeps, entry: Entry, install: InstallEntry, values: Values, given?: string) => Promise<Lane>;
49
+ export declare const startEntry: (deps: SupervisorDeps, entry: Entry) => Promise<void>;
50
+ export declare const startFailed: (entry: Entry, err: unknown) => import("../../envelope/envelope.js").Failure;
51
+ export declare const swap: (deps: SupervisorDeps, entry: Entry, to: Next) => Promise<void>;
52
+ export declare const halt: (entry: Entry, drainMs: number) => Promise<void>;
@@ -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>>;