@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,23 @@
1
+ import { z } from 'zod';
2
+ declare const InstallEntrySchema: z.ZodObject<{
3
+ id: z.ZodString;
4
+ version: z.ZodOptional<z.ZodString>;
5
+ source: z.ZodOptional<z.ZodString>;
6
+ enabled: z.ZodOptional<z.ZodBoolean>;
7
+ }, z.core.$loose>;
8
+ export type InstallEntry = z.infer<typeof InstallEntrySchema>;
9
+ export interface Installation {
10
+ host: string;
11
+ extensions: InstallEntry[];
12
+ [key: string]: unknown;
13
+ }
14
+ export interface CheckedInstallation {
15
+ doc: Installation;
16
+ invalid: boolean;
17
+ }
18
+ export declare const INSTALLATION_FILE = "installation.json";
19
+ export declare const readInstallation: (configDir: string) => Promise<CheckedInstallation>;
20
+ export declare const keepBadCopy: (configDir: string) => Promise<void>;
21
+ export declare const updateInstallation: (configDir: string, change: (doc: Installation) => Installation) => Promise<Installation>;
22
+ export declare const withEntry: (doc: Installation, id: string, entry?: InstallEntry) => Installation;
23
+ export {};
@@ -0,0 +1,48 @@
1
+ import { copyFile } from 'node:fs/promises';
2
+ import { isAbsolute, join } from 'node:path';
3
+ import { z } from 'zod';
4
+ import { ExtensionIdSchema } from '../../manifest/primitives.schema.js';
5
+ import { readJsonFile, withFileLock, writeJsonFile } from './json-file.js';
6
+ // One extension in installation.json (C3): a version, or a source folder; other keys round-trip.
7
+ const InstallEntrySchema = z.looseObject({
8
+ id: ExtensionIdSchema,
9
+ version: z.string().min(1).optional(),
10
+ source: z.string().refine(isAbsolute).optional(),
11
+ enabled: z.boolean().optional(),
12
+ });
13
+ const InstallationSchema = z.looseObject({
14
+ host: z.string().default('local'),
15
+ extensions: z.array(z.unknown()),
16
+ });
17
+ export const INSTALLATION_FILE = 'installation.json';
18
+ const EMPTY = { host: 'local', extensions: [] };
19
+ const checked = (raw) => {
20
+ const top = InstallationSchema.safeParse(raw);
21
+ if (!top.success)
22
+ return { doc: EMPTY, invalid: true };
23
+ const rows = top.data.extensions.map((row) => InstallEntrySchema.safeParse(row));
24
+ const extensions = rows.flatMap((row) => (row.success ? [row.data] : []));
25
+ return { doc: { ...top.data, extensions }, invalid: extensions.length < rows.length };
26
+ };
27
+ export const readInstallation = async (configDir) => checked(await readJsonFile(join(configDir, INSTALLATION_FILE), EMPTY).catch(() => null));
28
+ // A bad file is kept as installation.json.bad before the daemon writes the valid rows over it.
29
+ export const keepBadCopy = (configDir) => copyFile(join(configDir, INSTALLATION_FILE), join(configDir, `${INSTALLATION_FILE}.bad`));
30
+ // Read, change and write under the lock: the daemon is the only writer.
31
+ export const updateInstallation = (configDir, change) => {
32
+ const file = join(configDir, INSTALLATION_FILE);
33
+ return withFileLock(file, async () => {
34
+ const next = change((await readInstallation(configDir)).doc);
35
+ await writeJsonFile(file, next);
36
+ return next;
37
+ });
38
+ };
39
+ // The entry of id replaced (or added), the order kept; undefined removes it.
40
+ export const withEntry = (doc, id, entry) => {
41
+ const at = doc.extensions.findIndex((e) => e.id === id);
42
+ const rest = doc.extensions.filter((e) => e.id !== id);
43
+ if (!entry)
44
+ return { ...doc, extensions: rest };
45
+ if (at < 0)
46
+ return { ...doc, extensions: [...rest, entry] };
47
+ return { ...doc, extensions: doc.extensions.map((e) => (e.id === id ? entry : e)) };
48
+ };
@@ -0,0 +1,7 @@
1
+ import { type Installer, type SupervisorDeps } from './supervisor.js';
2
+ export declare const NO_INSTALLER = "this daemon has no installer: install a folder with { source }";
3
+ export declare const runInstaller: (deps: SupervisorDeps, spec: Parameters<Installer>[0]) => Promise<{
4
+ id: string;
5
+ version: string;
6
+ dir: string;
7
+ }>;
@@ -0,0 +1,22 @@
1
+ import { fail } from '../../envelope/envelope.js';
2
+ import {} from './supervisor.js';
3
+ export const NO_INSTALLER = 'this daemon has no installer: install a folder with { source }';
4
+ // 501 as C5 says, in the envelope; the closed code set has no NOT_IMPLEMENTED.
5
+ const noInstaller = () => Object.assign(fail('UNAVAILABLE', NO_INSTALLER), { status: 501, retryAfter: undefined });
6
+ const BASE = { 400: 'VALIDATION_ERROR', 404: 'NOT_FOUND', 502: 'UNAVAILABLE' };
7
+ // An installer error with a string code is the client's envelope; any other stays a 500.
8
+ const answerOf = (err) => {
9
+ const { code, status, message } = (err ?? {});
10
+ if (typeof code !== 'string' || !code)
11
+ return err;
12
+ const at = status === 404 || status === 502 ? status : 400;
13
+ const failure = fail(BASE[at], typeof message === 'string' && message ? message : code);
14
+ return Object.assign(failure, { code, status: at, retryAfter: undefined });
15
+ };
16
+ export const runInstaller = async (deps, spec) => {
17
+ if (!deps.install)
18
+ throw noInstaller();
19
+ return deps.install(spec).catch((err) => {
20
+ throw answerOf(err);
21
+ });
22
+ };
@@ -0,0 +1,3 @@
1
+ export declare const readJsonFile: <T>(file: string, fallback: T) => Promise<T>;
2
+ export declare const writeJsonFile: (file: string, value: unknown, mode?: number) => Promise<void>;
3
+ export declare const withFileLock: <T>(file: string, fn: () => Promise<T>) => Promise<T>;
@@ -0,0 +1,51 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { chmod, open, readFile, rename } from 'node:fs/promises';
3
+ import { DATA_DIR_LOCKED, lockDataDir } from '../data-lock.js';
4
+ export const readJsonFile = async (file, fallback) => {
5
+ try {
6
+ return JSON.parse(await readFile(file, 'utf8'));
7
+ }
8
+ catch (err) {
9
+ if (err.code === 'ENOENT')
10
+ return fallback;
11
+ throw err;
12
+ }
13
+ };
14
+ // A reader sees the old file or the new one, never half of one, also after a power loss.
15
+ export const writeJsonFile = async (file, value, mode = 0o644) => {
16
+ const tmp = `${file}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
17
+ const handle = await open(tmp, 'w', mode);
18
+ try {
19
+ await handle.writeFile(`${JSON.stringify(value, null, 2)}\n`);
20
+ await handle.sync();
21
+ }
22
+ finally {
23
+ await handle.close();
24
+ }
25
+ await chmod(tmp, mode);
26
+ await rename(tmp, file);
27
+ };
28
+ const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
29
+ // The pid lock of data-lock.ts: a dead holder's lock is taken over, a live one is waited for.
30
+ const acquire = async (file) => {
31
+ for (let tries = 0;; tries += 1) {
32
+ try {
33
+ return await lockDataDir(file);
34
+ }
35
+ catch (err) {
36
+ if (err.code !== DATA_DIR_LOCKED || tries >= 200)
37
+ throw err;
38
+ await pause(25);
39
+ }
40
+ }
41
+ };
42
+ // One writer at a time across processes: an exclusive lock file (<file>.lock) beside the file.
43
+ export const withFileLock = async (file, fn) => {
44
+ const release = await acquire(file);
45
+ try {
46
+ return await fn();
47
+ }
48
+ finally {
49
+ await release();
50
+ }
51
+ };
@@ -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>;