@agentage/extension 0.13.0 → 0.15.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 (146) hide show
  1. package/README.md +3 -1
  2. package/dist/discovery/discovery.d.ts +1 -0
  3. package/dist/discovery/discovery.schema.d.ts +2 -0
  4. package/dist/discovery/discovery.schema.js +22 -10
  5. package/dist/health/health.d.ts +2 -0
  6. package/dist/health/health.js +4 -2
  7. package/dist/health/health.schema.d.ts +9 -0
  8. package/dist/health/health.schema.js +3 -0
  9. package/dist/host/clock-rate.d.ts +1 -0
  10. package/dist/host/clock-rate.js +12 -0
  11. package/dist/host/daemon/add.d.ts +9 -0
  12. package/dist/host/daemon/add.js +84 -0
  13. package/dist/host/daemon/child-files.d.ts +20 -0
  14. package/dist/host/daemon/child-files.js +45 -0
  15. package/dist/host/daemon/child.d.ts +12 -4
  16. package/dist/host/daemon/child.js +78 -44
  17. package/dist/host/daemon/daemon-files.d.ts +6 -5
  18. package/dist/host/daemon/daemon-files.js +20 -12
  19. package/dist/host/daemon/daemon-owner.d.ts +1 -0
  20. package/dist/host/daemon/daemon-owner.js +32 -0
  21. package/dist/host/daemon/daemon.d.ts +3 -3
  22. package/dist/host/daemon/daemon.js +72 -35
  23. package/dist/host/daemon/entries.d.ts +21 -0
  24. package/dist/host/daemon/entries.js +24 -0
  25. package/dist/host/daemon/gate.d.ts +3 -0
  26. package/dist/host/daemon/gate.js +19 -0
  27. package/dist/host/daemon/guard.d.ts +2 -1
  28. package/dist/host/daemon/guard.js +17 -4
  29. package/dist/host/daemon/health-routes.d.ts +17 -0
  30. package/dist/host/daemon/health-routes.js +61 -0
  31. package/dist/host/daemon/host-token.d.ts +6 -0
  32. package/dist/host/daemon/host-token.js +28 -0
  33. package/dist/host/daemon/installation.d.ts +17 -4
  34. package/dist/host/daemon/installation.js +52 -8
  35. package/dist/host/daemon/installer-call.d.ts +16 -2
  36. package/dist/host/daemon/installer-call.js +33 -7
  37. package/dist/host/daemon/json-file.d.ts +3 -2
  38. package/dist/host/daemon/json-file.js +21 -10
  39. package/dist/host/daemon/lane.d.ts +1 -3
  40. package/dist/host/daemon/lane.js +4 -9
  41. package/dist/host/daemon/last-words.d.ts +2 -0
  42. package/dist/host/daemon/last-words.js +28 -0
  43. package/dist/host/daemon/limits.d.ts +15 -0
  44. package/dist/host/daemon/limits.js +29 -0
  45. package/dist/host/daemon/ops.d.ts +2 -26
  46. package/dist/host/daemon/ops.js +46 -103
  47. package/dist/host/daemon/patch-values.d.ts +6 -0
  48. package/dist/host/daemon/patch-values.js +39 -0
  49. package/dist/host/daemon/pending.d.ts +15 -0
  50. package/dist/host/daemon/pending.js +18 -0
  51. package/dist/host/daemon/proxy.d.ts +3 -2
  52. package/dist/host/daemon/proxy.js +54 -24
  53. package/dist/host/daemon/queue.d.ts +1 -0
  54. package/dist/host/daemon/queue.js +19 -0
  55. package/dist/host/daemon/reload-marker.d.ts +8 -0
  56. package/dist/host/daemon/reload-marker.js +56 -0
  57. package/dist/host/daemon/reload-route.d.ts +4 -0
  58. package/dist/host/daemon/reload-route.js +21 -0
  59. package/dist/host/daemon/reload.d.ts +10 -0
  60. package/dist/host/daemon/reload.js +73 -0
  61. package/dist/host/daemon/restart.d.ts +14 -0
  62. package/dist/host/daemon/restart.js +59 -0
  63. package/dist/host/daemon/routes.d.ts +3 -9
  64. package/dist/host/daemon/routes.js +54 -22
  65. package/dist/host/daemon/run-lock.d.ts +1 -0
  66. package/dist/host/daemon/run-lock.js +15 -0
  67. package/dist/host/daemon/seal-reach.d.ts +2 -0
  68. package/dist/host/daemon/seal-reach.js +38 -0
  69. package/dist/host/daemon/seal.d.ts +16 -0
  70. package/dist/host/daemon/seal.js +71 -0
  71. package/dist/host/daemon/start-checks.d.ts +6 -0
  72. package/dist/host/daemon/start-checks.js +28 -0
  73. package/dist/host/daemon/stopping.d.ts +10 -0
  74. package/dist/host/daemon/stopping.js +28 -0
  75. package/dist/host/daemon/supervisor.d.ts +19 -11
  76. package/dist/host/daemon/supervisor.js +39 -47
  77. package/dist/host/daemon/write-all.d.ts +8 -0
  78. package/dist/host/daemon/write-all.js +45 -0
  79. package/dist/host/data-lock.d.ts +3 -1
  80. package/dist/host/data-lock.js +88 -29
  81. package/dist/host/host-env.d.ts +3 -1
  82. package/dist/host/host-env.js +10 -2
  83. package/dist/host/host-extension.d.ts +8 -0
  84. package/dist/host/host-extension.js +30 -45
  85. package/dist/host/host-parts.d.ts +25 -0
  86. package/dist/host/host-parts.js +75 -0
  87. package/dist/host/host-store.d.ts +11 -1
  88. package/dist/host/host-store.js +45 -12
  89. package/dist/host/index.d.ts +4 -0
  90. package/dist/host/index.js +4 -0
  91. package/dist/host/main.js +2 -0
  92. package/dist/host/part-checks.d.ts +2 -0
  93. package/dist/host/part-checks.js +19 -0
  94. package/dist/host/serve-host.d.ts +2 -1
  95. package/dist/host/serve-host.js +16 -10
  96. package/dist/manifest/parts.d.ts +3 -0
  97. package/dist/manifest/parts.js +3 -0
  98. package/dist/mcp/mcp-app.d.ts +4 -0
  99. package/dist/mcp/mcp-app.js +11 -11
  100. package/dist/runtime/part-mounts.d.ts +29 -0
  101. package/dist/runtime/part-mounts.js +52 -0
  102. package/dist/runtime/part-runners.d.ts +2 -15
  103. package/dist/runtime/part-runners.js +13 -58
  104. package/dist/server/app.d.ts +5 -1
  105. package/dist/server/app.js +17 -17
  106. package/dist/server/serve.d.ts +3 -0
  107. package/dist/server/serve.js +9 -4
  108. package/dist/tool/build.d.ts +3 -0
  109. package/dist/tool/build.js +42 -27
  110. package/dist/tool/capabilities.d.ts +1 -0
  111. package/dist/tool/capabilities.js +8 -0
  112. package/dist/tool/check.d.ts +2 -0
  113. package/dist/tool/check.js +23 -8
  114. package/dist/tool/container-parts.d.ts +7 -0
  115. package/dist/tool/container-parts.js +10 -0
  116. package/dist/tool/container-recipe.d.ts +4 -0
  117. package/dist/tool/container-recipe.js +55 -0
  118. package/dist/tool/container-stage.d.ts +3 -0
  119. package/dist/tool/container-stage.js +51 -0
  120. package/dist/tool/container.d.ts +73 -0
  121. package/dist/tool/container.js +28 -0
  122. package/dist/tool/docker.d.ts +5 -0
  123. package/dist/tool/docker.js +15 -0
  124. package/dist/tool/format.js +23 -9
  125. package/dist/tool/index.d.ts +2 -0
  126. package/dist/tool/index.js +2 -0
  127. package/dist/tool/kit-version.d.ts +3 -0
  128. package/dist/tool/kit-version.js +28 -2
  129. package/dist/tool/labels.d.ts +1 -1
  130. package/dist/tool/labels.js +4 -2
  131. package/dist/tool/main.js +10 -1
  132. package/dist/tool/stage.d.ts +1 -0
  133. package/dist/tool/stage.js +1 -1
  134. package/dist/tool/up/local-record.d.ts +1 -0
  135. package/dist/worker/clock.d.ts +6 -0
  136. package/dist/worker/clock.js +21 -0
  137. package/dist/worker/scheduler.d.ts +1 -0
  138. package/dist/worker/scheduler.js +6 -2
  139. package/package.json +1 -1
  140. package/schemas/extension-discovery.schema.json +8 -1
  141. package/schemas/extension-record.schema.json +8 -1
  142. package/schemas/health.schema.json +17 -0
  143. package/dist/host/daemon/secret-names.d.ts +0 -1
  144. package/dist/host/daemon/secret-names.js +0 -14
  145. package/dist/host/daemon/setting-values.d.ts +0 -1
  146. package/dist/host/daemon/setting-values.js +0 -26
@@ -0,0 +1,32 @@
1
+ import { join } from 'node:path';
2
+ import { fail } from '../../envelope/envelope.js';
3
+ import { readJsonFile } from './json-file.js';
4
+ const alive = (pid) => {
5
+ try {
6
+ return process.kill(pid, 0);
7
+ }
8
+ catch (err) {
9
+ return err.code === 'EPERM';
10
+ }
11
+ };
12
+ // A daemon.json of a dead or other process is stale: only one that answers as that daemon counts.
13
+ const answersAsDaemon = async (port, pid) => {
14
+ const res = await fetch(`http://127.0.0.1:${port}/health`, {
15
+ signal: AbortSignal.timeout(1_000),
16
+ });
17
+ const body = (await res.json());
18
+ return body.service === 'agentage-daemon' && body.pid === pid;
19
+ };
20
+ // installation.json belongs to the daemon that runs on configDir; its own process may write it.
21
+ export const assertNoOtherDaemon = async (configDir) => {
22
+ const file = await readJsonFile(join(configDir, 'daemon.json'), null).catch(() => null);
23
+ const { pid, port } = file ?? {};
24
+ if (!pid || !port || pid === process.pid || !alive(pid))
25
+ return;
26
+ if (!(await answersAsDaemon(port, pid).catch(() => false)))
27
+ return;
28
+ throw fail('CONFLICT', `a daemon (process ${pid}) runs on ${configDir}: change it through it`, {
29
+ code: 'DAEMON_RUNNING',
30
+ details: { pid, port },
31
+ });
32
+ };
@@ -1,13 +1,13 @@
1
1
  import { type Launch } from './child.js';
2
+ import { type Limits } from './limits.js';
2
3
  import { type Installer } from './supervisor.js';
3
- export interface DaemonOptions {
4
+ export interface DaemonOptions extends Partial<Limits> {
4
5
  configDir: string;
5
6
  port?: number;
6
7
  install?: Installer;
7
8
  version: string;
8
9
  startedBy: string;
9
- drainMs?: number;
10
- healthMs?: number;
10
+ clockRate?: number;
11
11
  }
12
12
  export interface Daemon {
13
13
  port: number;
@@ -1,77 +1,113 @@
1
+ import { mkdir } from 'node:fs/promises';
1
2
  import {} from 'node:http';
2
3
  import {} from 'node:net';
3
4
  import { createLog } from '../../log/log.js';
4
- import { listen } from '../../server/serve.js';
5
+ import { closeNow, listen } from '../../server/serve.js';
5
6
  import { forkLaunch } from './child.js';
6
- import { ensureConfigDir, removeDaemonFile, writeDaemonFile, DAEMON_PROTOCOL, } from './daemon-files.js';
7
- import { keepBadCopy, readInstallation } from './installation.js';
8
- import {} from './ops.js';
7
+ import { removeDaemonFile, writeDaemonFile, DAEMON_PROTOCOL } from './daemon-files.js';
8
+ import { assertNoOtherDaemon } from './daemon-owner.js';
9
+ import { bootInstallation, updateInstallation } from './installation.js';
10
+ import {} from './entries.js';
11
+ import { newHostToken } from './host-token.js';
12
+ import { sealOffReason } from './seal.js';
13
+ import { limitsOf } from './limits.js';
14
+ import { pendingChanges } from './pending.js';
9
15
  import { serialQueue } from './queue.js';
16
+ import { launchUnlessStopping, stopAll, stoppingOf } from './stopping.js';
10
17
  import { daemonApp } from './routes.js';
11
- import { DRAIN_MS, HEALTH_MS, halt, startEntry, } from './supervisor.js';
18
+ import { runInstaller } from './installer-call.js';
19
+ import { repairReload } from './reload-marker.js';
20
+ import { halt, startEntry } from './supervisor.js';
12
21
  export const DAEMON_PORT = 4243;
13
- // The valid rows of installation.json; a bad file is kept aside and reported in /health.
14
- const loadEntries = async (configDir) => {
15
- const { doc, invalid } = await readInstallation(configDir);
22
+ const warnOf = (deps) => (err) => deps.log.warn('a daemon file was not cleaned at boot', { reason: err.message });
23
+ // The valid rows of installation.json; a bad file is kept aside, replaced by them, and in /health.
24
+ const loadEntries = async (deps) => {
25
+ const { doc, invalid, unreadable } = await bootInstallation(deps.configDir);
16
26
  if (invalid)
17
- await keepBadCopy(configDir).catch(() => undefined);
27
+ await updateInstallation(deps.configDir, () => doc, deps.lockMs).catch(warnOf(deps));
18
28
  const entries = new Map();
19
29
  for (const install of doc.extensions) {
20
30
  const state = install.enabled === false ? 'disabled' : 'starting';
21
31
  entries.set(install.id, { id: install.id, install, state, version: install.version ?? '' });
22
32
  }
23
- return { entries, invalid };
33
+ return { entries, invalid, unreadable };
24
34
  };
25
- // One at a time, so the installer is never called twice at once; a failed one stops no other.
35
+ // A disabled entry gets its folder (configure and enable work); a failure is kept as its error.
36
+ const resolveDir = async (deps, entry) => {
37
+ const { id, install } = entry;
38
+ if (install.source)
39
+ return void (entry.dir = install.source);
40
+ await runInstaller(deps, { id, version: install.version }).then((got) => void Object.assign(entry, { dir: got.dir, version: got.version, error: undefined }), (err) => void (entry.error = err.message));
41
+ };
42
+ // Enabled folders first (no installer), then enabled versions one at a time, disabled ones last.
26
43
  const boot = async (deps, entries) => {
27
- for (const entry of entries.values())
28
- if (entry.state === 'starting')
29
- await startEntry(deps, entry);
44
+ const all = [...entries.values()];
45
+ const off = all.filter((e) => e.state === 'disabled');
46
+ const on = all.filter((e) => e.state !== 'disabled');
47
+ const ordered = [...on.filter((e) => e.install.source), ...on.filter((e) => !e.install.source)];
48
+ for (const entry of all)
49
+ await repairReload(deps.configDir, entry, deps.log).catch(warnOf(deps));
50
+ for (const entry of ordered)
51
+ await startEntry(deps, entry);
52
+ for (const entry of off)
53
+ await resolveDir(deps, entry);
30
54
  };
31
- const close = (server) => new Promise((resolve) => {
32
- server.close(() => resolve());
33
- server.closeAllConnections();
34
- });
35
- const stopper = (server, entries, deps) => {
55
+ const stopper = (server, entries, deps, life) => {
36
56
  let stopped;
37
57
  const stop = async () => {
58
+ life.abort();
38
59
  await Promise.all([...entries.values()].map((entry) => halt(entry, deps.drainMs)));
39
- await close(server);
60
+ await stopAll(deps.stopping);
61
+ await closeNow(server);
40
62
  await removeDaemonFile(deps.configDir);
41
63
  };
42
64
  return () => (stopped ??= stop());
43
65
  };
44
- // C4: how a client finds this daemon.
45
- const announce = ({ configDir, version, startedBy }, port) => writeDaemonFile(configDir, {
66
+ // C4: how a client finds this daemon; D11: the host token, only in this 0600 file.
67
+ const announce = ({ configDir, version, startedBy }, port, hostToken) => writeDaemonFile(configDir, {
46
68
  pid: process.pid,
47
69
  port,
48
70
  version,
49
71
  protocol: DAEMON_PROTOCOL,
50
72
  startedBy,
73
+ hostToken,
74
+ });
75
+ // One source: the launch that forks the children (its test clock, its seal).
76
+ const launchMarks = (launch) => ({
77
+ ...(launch.clockRate && launch.clockRate !== 1 && { clockRate: launch.clockRate }),
78
+ ...(launch.seal && { seal: launch.seal }),
79
+ ...(launch.seal === 'off' && { sealError: sealOffReason(launch.node ?? process.versions.node) }),
51
80
  });
52
- const depsOf = (opts, launch, origin) => ({
81
+ const depsOf = (opts, launch, origin, stopping) => ({
53
82
  configDir: opts.configDir,
54
- launch,
83
+ launch: launchUnlessStopping(stopping, launch),
84
+ stopping,
55
85
  install: opts.install,
56
86
  log: createLog({ extension: 'host', part: 'api', version: opts.version }),
57
87
  origin,
58
- drainMs: opts.drainMs ?? DRAIN_MS,
59
- healthMs: opts.healthMs ?? HEALTH_MS,
88
+ ...limitsOf(opts),
60
89
  queue: serialQueue(),
90
+ pending: pendingChanges(),
91
+ unsynced: new Set(),
61
92
  });
62
- // Read and check the file, listen, write daemon.json, start the children; a failed boot undoes it.
93
+ // No other daemon, read and check the file, listen, write daemon.json, start the children; a failed boot undoes it.
63
94
  export const startDaemon = async (opts, launch) => {
64
- await ensureConfigDir(opts.configDir);
95
+ await mkdir(opts.configDir, { recursive: true });
96
+ // A live daemon owns the folder: a second one fails before it writes any file there.
97
+ await assertNoOtherDaemon(opts.configDir);
65
98
  let port = opts.port ?? DAEMON_PORT;
66
- const deps = depsOf(opts, launch, () => `http://127.0.0.1:${port}`);
67
- const { entries, invalid } = await loadEntries(opts.configDir);
68
- const info = { version: opts.version, pid: process.pid, protocol: DAEMON_PROTOCOL, invalid };
69
- const app = daemonApp(deps, entries, () => port, info);
99
+ const life = new AbortController();
100
+ const deps = depsOf(opts, launch, () => `http://127.0.0.1:${port}`, stoppingOf(life.signal));
101
+ const { entries, ...file } = await loadEntries(deps);
102
+ const self = { version: opts.version, pid: process.pid, protocol: DAEMON_PROTOCOL };
103
+ const info = { ...launchMarks(launch), ...self, ...file };
104
+ const hostToken = newHostToken();
105
+ const app = daemonApp(deps, entries, () => port, info, hostToken);
70
106
  const server = await listen(app, port, '127.0.0.1');
71
107
  port = server.address().port;
72
- const stop = stopper(server, entries, deps);
108
+ const stop = stopper(server, entries, deps, life);
73
109
  try {
74
- await announce(opts, port);
110
+ await announce(opts, port, hostToken);
75
111
  await deps.queue(() => boot(deps, entries));
76
112
  }
77
113
  catch (err) {
@@ -81,4 +117,5 @@ export const startDaemon = async (opts, launch) => {
81
117
  return { port, stop };
82
118
  };
83
119
  // One daemon on 127.0.0.1, one child process for each extension (D1).
84
- export const createDaemon = (opts) => startDaemon(opts, forkLaunch());
120
+ // A bad clockRate rejects the promise, like every other refusal of this function.
121
+ export const createDaemon = async (opts) => startDaemon(opts, forkLaunch(undefined, opts.startMs, opts.clockRate));
@@ -0,0 +1,21 @@
1
+ import { type InstallEntry } from './installation.js';
2
+ import { type Entry, type SupervisorDeps } from './supervisor.js';
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 entryOf: (entries: Entries, id: string) => Entry;
21
+ export declare const persist: (deps: SupervisorDeps, id: string, install?: InstallEntry) => Promise<import("./installation.js").Installation>;
@@ -0,0 +1,24 @@
1
+ import { fail } from '../../envelope/envelope.js';
2
+ import { persistInstallation, withEntry } from './installation.js';
3
+ import {} from './supervisor.js';
4
+ // pid of a running child: the e2e teardown reads it.
5
+ export const summary = ({ id, version, state, error, lane }) => ({
6
+ id,
7
+ version,
8
+ state,
9
+ ...(lane && { pid: lane.child.pid }),
10
+ ...(error && { error }),
11
+ });
12
+ export const listed = (entry) => ({
13
+ ...summary(entry),
14
+ source: entry.install.source ?? 'market',
15
+ enabled: entry.install.enabled !== false,
16
+ });
17
+ export const entryOf = (entries, id) => {
18
+ const entry = entries.get(id);
19
+ if (!entry)
20
+ throw fail('NOT_FOUND', `${id} is not installed`);
21
+ return entry;
22
+ };
23
+ // The entry of id in installation.json replaced, added, or (no install) removed.
24
+ export const persist = (deps, id, install) => persistInstallation(deps.configDir, (doc) => withEntry(doc, id, install), deps.lockMs);
@@ -0,0 +1,3 @@
1
+ import { type Entry } from './supervisor.js';
2
+ export declare const hold: (entry: Entry) => (() => void);
3
+ export declare const halt: (entry: Entry, drainMs: number) => Promise<void>;
@@ -0,0 +1,19 @@
1
+ import { retire } from './lane.js';
2
+ import { cancelRestart } from './restart.js';
3
+ import {} from './supervisor.js';
4
+ // New requests of the extension wait here (the proxy gives up after gateMs) until release.
5
+ export const hold = (entry) => {
6
+ let release = () => undefined;
7
+ entry.gate = new Promise((resolve) => (release = resolve));
8
+ return () => {
9
+ entry.gate = undefined;
10
+ release();
11
+ };
12
+ };
13
+ // Detached first, so its exit is not a failure; then drained and stopped.
14
+ export const halt = async (entry, drainMs) => {
15
+ cancelRestart(entry);
16
+ const lane = entry.lane;
17
+ entry.lane = undefined;
18
+ await retire(lane, drainMs);
19
+ };
@@ -1,2 +1,3 @@
1
1
  import { type RequestHandler } from 'express';
2
- export declare const localOnly: (port: () => number) => RequestHandler;
2
+ export declare const localOnly: (port?: () => number, more?: number[]) => RequestHandler;
3
+ export declare const loopbackPorts: (origin: string | undefined) => number[];
@@ -2,14 +2,27 @@ import {} from 'express';
2
2
  import { fail } from '../../envelope/envelope.js';
3
3
  // What a browser says of a request another site started (an <img>, a link, a form).
4
4
  const FOREIGN = ['cross-site', 'same-site'];
5
- // Only this machine, by name: a page elsewhere (DNS rebinding, a cross-site form or GET) gets 403.
6
- export const localOnly = (port) => (req, _res, next) => {
7
- const hosts = [`127.0.0.1:${port()}`, `localhost:${port()}`];
5
+ const hostsAt = (port) => [`127.0.0.1:${port}`, `localhost:${port}`];
6
+ // Only this machine by name (DNS rebinding, a cross-site form); more: other local ports, as the daemon's.
7
+ export const localOnly = (port, more = []) => (req, _res, next) => {
8
+ const at = port?.() ?? req.socket.localPort ?? 0;
9
+ const hosts = [at, ...more].flatMap(hostsAt);
8
10
  const origin = req.get('origin');
9
11
  const hostOk = hosts.includes(req.get('host') ?? '');
10
12
  const originOk = origin === undefined || hosts.some((host) => origin === `http://${host}`);
11
13
  const siteOk = !FOREIGN.includes(req.get('sec-fetch-site') ?? '');
12
14
  if (!hostOk || !originOk || !siteOk)
13
- throw fail('FORBIDDEN', 'Only this machine may call the daemon');
15
+ throw fail('FORBIDDEN', 'Only this machine may call this server');
14
16
  next();
15
17
  };
18
+ // The port of a loopback origin (the daemon's AGENTAGE_ORIGIN); none for any other origin.
19
+ export const loopbackPorts = (origin) => {
20
+ try {
21
+ const url = new URL(origin ?? '');
22
+ const local = url.protocol === 'http:' && ['127.0.0.1', 'localhost'].includes(url.hostname);
23
+ return local && url.port ? [Number(url.port)] : [];
24
+ }
25
+ catch {
26
+ return [];
27
+ }
28
+ };
@@ -0,0 +1,17 @@
1
+ import { type Express } from 'express';
2
+ import { type Entries } from './entries.js';
3
+ import { type Seal } from './seal.js';
4
+ import { type SupervisorDeps } from './supervisor.js';
5
+ export interface DaemonInfo {
6
+ version: string;
7
+ pid: number;
8
+ protocol: number;
9
+ invalid: boolean;
10
+ unreadable?: string;
11
+ notJson?: boolean;
12
+ clockRate?: number;
13
+ seal?: Seal;
14
+ sealError?: string;
15
+ }
16
+ export declare const HOST_DISCOVERY_PATH = "/.well-known/agentage-host.json";
17
+ export declare const healthRoutes: (app: Express, deps: SupervisorDeps, entries: Entries, info: DaemonInfo) => void;
@@ -0,0 +1,61 @@
1
+ import {} from 'express';
2
+ import { hostParts } from '../../manifest/parts.js';
3
+ import { readManifest } from '../../manifest/read-manifest.js';
4
+ import { summary } from './entries.js';
5
+ import { restartsOf } from './restart.js';
6
+ import {} from './seal.js';
7
+ import {} from './supervisor.js';
8
+ // What /health says of the daemon itself: the values of daemon.json, so a client can prove it.
9
+ const DAEMON_SERVICE = 'agentage-daemon';
10
+ // Read at each call: a reload can change the package in its folder.
11
+ const partsOf = async ({ dir }) => dir ? readManifest(dir).then(hostParts, () => []) : [];
12
+ const reported = async (entry, info) => ({
13
+ ...summary(entry),
14
+ parts: await partsOf(entry),
15
+ seal: info.seal ?? 'off',
16
+ restarts: restartsOf(entry),
17
+ });
18
+ const installationOf = ({ invalid, unreadable, notJson }) => {
19
+ if (unreadable)
20
+ return { installation: 'unreadable', installationError: unreadable };
21
+ return invalid || notJson ? { installation: 'invalid' } : {};
22
+ };
23
+ const sealMark = ({ seal, sealError }) => seal === 'off' ? { seal, sealError: sealError ?? 'seal off' } : {};
24
+ const statusOf = (deps, entries, info) => {
25
+ const settled = [...entries.values()].every((e) => ['running', 'disabled'].includes(e.state));
26
+ const clean = !info.invalid && !info.unreadable && !info.notJson && info.seal !== 'off';
27
+ return settled && !deps.unsynced.size && clean ? 'ok' : 'degraded';
28
+ };
29
+ const healthOf = async (deps, entries, info) => {
30
+ const self = { service: DAEMON_SERVICE, pid: info.pid, protocol: info.protocol };
31
+ const extensions = await Promise.all([...entries.values()].map((e) => reported(e, info)));
32
+ const changing = deps.pending.list();
33
+ const marks = {
34
+ ...(changing.length && { pending: changing }),
35
+ ...(info.clockRate && { clockRate: info.clockRate }),
36
+ ...(deps.unsynced.size && { unsynced: [...deps.unsynced] }),
37
+ ...installationOf(info),
38
+ ...sealMark(info),
39
+ };
40
+ const status = statusOf(deps, entries, info);
41
+ return { status, version: info.version, ...self, extensions, ...marks };
42
+ };
43
+ // C10 (D10): where each running extension answers, and its parts; anonymous, bare JSON.
44
+ const discoveryOf = async (entries) => {
45
+ const running = [...entries.values()].filter((e) => e.state === 'running');
46
+ const listed = running.map(async (e) => ({
47
+ id: e.id,
48
+ version: e.version,
49
+ parts: await partsOf(e),
50
+ }));
51
+ return { host: 'local', extensions: await Promise.all(listed) };
52
+ };
53
+ export const HOST_DISCOVERY_PATH = '/.well-known/agentage-host.json';
54
+ export const healthRoutes = (app, deps, entries, info) => {
55
+ app.get('/health', async (_req, res) => {
56
+ res.set('Cache-Control', 'no-store').json(await healthOf(deps, entries, info));
57
+ });
58
+ app.get(HOST_DISCOVERY_PATH, async (_req, res) => {
59
+ res.set('Cache-Control', 'no-store').json(await discoveryOf(entries));
60
+ });
61
+ };
@@ -0,0 +1,6 @@
1
+ import { type IncomingHttpHeaders } from 'node:http';
2
+ import { type RequestHandler } from 'express';
3
+ export declare const newHostToken: () => string;
4
+ export declare const carriesHostToken: (headers: IncomingHttpHeaders, token: string) => boolean;
5
+ export declare const NO_TOKEN = "host token required: this cli is older than the daemon, update @agentage/cli or run \"agentage daemon restart\"";
6
+ export declare const requireHostToken: (token: string) => RequestHandler;
@@ -0,0 +1,28 @@
1
+ import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
2
+ import {} from 'node:http';
3
+ import {} from 'express';
4
+ import { fail } from '../../envelope/envelope.js';
5
+ // D11: a new token at each daemon start, in daemon.json (0600); a sealed child cannot read it.
6
+ export const newHostToken = () => randomBytes(32).toString('base64url');
7
+ const bearerOf = (headers) => {
8
+ const match = /^Bearer\s+(\S+)\s*$/i.exec(headers.authorization ?? '');
9
+ return match?.[1];
10
+ };
11
+ // Digests first: timingSafeEqual needs equal lengths, and the length of the token stays unseen.
12
+ const sameToken = (given, token) => timingSafeEqual(createHash('sha256').update(given).digest(), createHash('sha256').update(token).digest());
13
+ // True when the request carries the host token: the proxy then keeps it from the child.
14
+ export const carriesHostToken = (headers, token) => {
15
+ const given = bearerOf(headers);
16
+ return given !== undefined && sameToken(given, token);
17
+ };
18
+ // A cli that sends no token was made before the host token (C3): the fix is a newer cli or a restart.
19
+ export const NO_TOKEN = 'host token required: this cli is older than the daemon, update @agentage/cli or run "agentage daemon restart"';
20
+ // Every /host/* route: 401 with no bearer, 403 with another one.
21
+ export const requireHostToken = (token) => (req, _res, next) => {
22
+ const given = bearerOf(req.headers);
23
+ if (given === undefined)
24
+ throw fail('UNAUTHORIZED', NO_TOKEN);
25
+ if (!sameToken(given, token))
26
+ throw fail('FORBIDDEN', 'The host token is not valid');
27
+ next();
28
+ };
@@ -11,13 +11,26 @@ export interface Installation {
11
11
  extensions: InstallEntry[];
12
12
  [key: string]: unknown;
13
13
  }
14
- export interface CheckedInstallation {
14
+ interface CheckedInstallation {
15
15
  doc: Installation;
16
16
  invalid: boolean;
17
17
  }
18
- export declare const INSTALLATION_FILE = "installation.json";
19
- export declare const readInstallation: (configDir: string) => Promise<CheckedInstallation>;
18
+ export declare const bootInstallation: (configDir: string) => Promise<{
19
+ doc: Installation;
20
+ invalid: boolean;
21
+ unreadable: string;
22
+ } | (CheckedInstallation & {
23
+ unreadable?: string;
24
+ })>;
25
+ export declare const assertReadable: (configDir: string, why?: string) => Promise<void>;
20
26
  export declare const keepBadCopy: (configDir: string) => Promise<void>;
21
- export declare const updateInstallation: (configDir: string, change: (doc: Installation) => Installation) => Promise<Installation>;
27
+ type Change = (doc: Installation) => Installation;
28
+ /**
29
+ * Read, change and write installation.json under the kit's lock, the path the daemon uses.
30
+ * Only while no daemon runs on configDir (it reads the file at its start and owns it after):
31
+ * a live daemon named by daemon.json is refused, unless this is that daemon's process.
32
+ */
33
+ export declare const updateInstallation: (configDir: string, change: Change, waitMs?: number) => Promise<Installation>;
34
+ export declare const persistInstallation: (configDir: string, change: Change, waitMs?: number) => Promise<Installation>;
22
35
  export declare const withEntry: (doc: Installation, id: string, entry?: InstallEntry) => Installation;
23
36
  export {};
@@ -1,7 +1,9 @@
1
1
  import { copyFile } from 'node:fs/promises';
2
2
  import { isAbsolute, join } from 'node:path';
3
3
  import { z } from 'zod';
4
+ import { fail } from '../../envelope/envelope.js';
4
5
  import { ExtensionIdSchema } from '../../manifest/primitives.schema.js';
6
+ import { assertNoOtherDaemon } from './daemon-owner.js';
5
7
  import { readJsonFile, withFileLock, writeJsonFile } from './json-file.js';
6
8
  // One extension in installation.json (C3): a version, or a source folder; other keys round-trip.
7
9
  const InstallEntrySchema = z.looseObject({
@@ -14,28 +16,70 @@ const InstallationSchema = z.looseObject({
14
16
  host: z.string().default('local'),
15
17
  extensions: z.array(z.unknown()),
16
18
  });
17
- export const INSTALLATION_FILE = 'installation.json';
19
+ const INSTALLATION_FILE = 'installation.json';
18
20
  const EMPTY = { host: 'local', extensions: [] };
19
21
  const checked = (raw) => {
20
22
  const top = InstallationSchema.safeParse(raw);
21
23
  if (!top.success)
22
24
  return { doc: EMPTY, invalid: true };
23
25
  const rows = top.data.extensions.map((row) => InstallEntrySchema.safeParse(row));
24
- const extensions = rows.flatMap((row) => (row.success ? [row.data] : []));
26
+ const valid = rows.flatMap((row) => (row.success ? [row.data] : []));
27
+ const extensions = valid.filter((row, at) => valid.findIndex((e) => e.id === row.id) === at);
25
28
  return { doc: { ...top.data, extensions }, invalid: extensions.length < rows.length };
26
29
  };
27
- export const readInstallation = async (configDir) => checked(await readJsonFile(join(configDir, INSTALLATION_FILE), EMPTY).catch(() => null));
30
+ // At boot the daemon has no rows from it, so a fix needs a restart; later a fix is enough.
31
+ const unreadable = (why, atBoot = false) => fail('CONFLICT', `${INSTALLATION_FILE} cannot be read (${why}): fix it${atBoot ? ', then restart the daemon' : ''}; no change is written`, { code: 'INSTALLATION_UNREADABLE', details: { reason: why } });
32
+ const reasonOf = (err) => err instanceof SyntaxError
33
+ ? 'not JSON'
34
+ : String(err.code ?? err.message);
35
+ // Not readable (EACCES, EISDIR): thrown.
36
+ const rawOf = (configDir, notJson = 'empty') => readJsonFile(join(configDir, INSTALLATION_FILE), EMPTY).catch((err) => {
37
+ if (err instanceof SyntaxError && notJson === 'empty')
38
+ return null;
39
+ throw err;
40
+ });
41
+ const readInstallation = async (configDir, notJson) => checked(await rawOf(configDir, notJson).catch((err) => {
42
+ throw unreadable(reasonOf(err));
43
+ }));
44
+ // At boot an unreadable file gives no rows and its reason; the daemon then refuses every change.
45
+ export const bootInstallation = (configDir) => rawOf(configDir).then((raw) => checked(raw), (err) => ({ doc: EMPTY, invalid: false, unreadable: reasonOf(err) }));
46
+ // A change is refused when the file was unreadable at boot (why) or is unreadable now.
47
+ export const assertReadable = async (configDir, why) => {
48
+ if (why)
49
+ throw unreadable(why, true);
50
+ await readInstallation(configDir, 'refuse');
51
+ };
28
52
  // A bad file is kept as installation.json.bad before the daemon writes the valid rows over it.
29
53
  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) => {
54
+ // Only rows C3 accepts are written, and each id once.
55
+ const checkedDoc = (next) => {
56
+ const ids = next.extensions.map((row) => row.id);
57
+ const bad = next.extensions.find((row) => !InstallEntrySchema.safeParse(row).success);
58
+ if (bad || new Set(ids).size < ids.length || !InstallationSchema.safeParse(next).success)
59
+ throw fail('VALIDATION_ERROR', `${INSTALLATION_FILE}: a row C3 refuses, or an id twice`);
60
+ return next;
61
+ };
62
+ const changeInstallation = (notJson) => async (configDir, change, waitMs) => {
63
+ await assertNoOtherDaemon(configDir);
32
64
  const file = join(configDir, INSTALLATION_FILE);
33
- return withFileLock(file, async () => {
34
- const next = change((await readInstallation(configDir)).doc);
65
+ const write = async () => {
66
+ const read = await readInstallation(configDir, notJson);
67
+ if (read.invalid)
68
+ await keepBadCopy(configDir);
69
+ const next = checkedDoc(change(read.doc));
35
70
  await writeJsonFile(file, next);
36
71
  return next;
37
- });
72
+ };
73
+ return withFileLock(file, write, waitMs);
38
74
  };
75
+ /**
76
+ * Read, change and write installation.json under the kit's lock, the path the daemon uses.
77
+ * Only while no daemon runs on configDir (it reads the file at its start and owns it after):
78
+ * a live daemon named by daemon.json is refused, unless this is that daemon's process.
79
+ */
80
+ export const updateInstallation = changeInstallation('empty');
81
+ // The daemon after its boot: its rows are in the file, so a file that is not JSON is never replaced.
82
+ export const persistInstallation = changeInstallation('refuse');
39
83
  // The entry of id replaced (or added), the order kept; undefined removes it.
40
84
  export const withEntry = (doc, id, entry) => {
41
85
  const at = doc.extensions.findIndex((e) => e.id === id);
@@ -1,7 +1,21 @@
1
- import { type Installer, type SupervisorDeps } from './supervisor.js';
1
+ import { type InstallSpec, type SupervisorDeps } from './supervisor.js';
2
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<{
3
+ declare const BASE: {
4
+ readonly 400: "VALIDATION_ERROR";
5
+ readonly 404: "NOT_FOUND";
6
+ readonly 409: "CONFLICT";
7
+ readonly 501: "UNAVAILABLE";
8
+ readonly 502: "UNAVAILABLE";
9
+ readonly 504: "UNAVAILABLE";
10
+ };
11
+ export declare const answer: (status: keyof typeof BASE, message: string, code?: string, details?: Record<string, unknown>) => import("../../envelope/envelope.js").Failure & {
12
+ code: string;
13
+ status: 400 | 404 | 409 | 501 | 502 | 504;
14
+ retryAfter: undefined;
15
+ };
16
+ export declare const runInstaller: (deps: SupervisorDeps, spec: Omit<InstallSpec, "signal">) => Promise<{
4
17
  id: string;
5
18
  version: string;
6
19
  dir: string;
7
20
  }>;
21
+ export {};
@@ -1,22 +1,48 @@
1
+ import { setTimeout as sleep } from 'node:timers/promises';
1
2
  import { fail } from '../../envelope/envelope.js';
2
3
  import {} from './supervisor.js';
3
4
  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' };
5
+ const BASE = {
6
+ 400: 'VALIDATION_ERROR',
7
+ 404: 'NOT_FOUND',
8
+ 409: 'CONFLICT',
9
+ 501: 'UNAVAILABLE',
10
+ 502: 'UNAVAILABLE',
11
+ 504: 'UNAVAILABLE',
12
+ };
13
+ // The envelope with a status or a code the closed set has not (501, 504, the installer's own code).
14
+ export const answer = (status, message, code = BASE[status], details) => Object.assign(fail(BASE[status], message, { details }), { code, status, retryAfter: undefined });
7
15
  // An installer error with a string code is the client's envelope; any other stays a 500.
8
16
  const answerOf = (err) => {
9
17
  const { code, status, message } = (err ?? {});
10
18
  if (typeof code !== 'string' || !code)
11
19
  return err;
12
20
  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 });
21
+ return answer(at, typeof message === 'string' && message ? message : code, code);
22
+ };
23
+ // A second call while a timed-out one of that id still runs would overlap it.
24
+ const notTwice = (deps, id) => {
25
+ const row = deps.pending.timedOut(id);
26
+ if (row)
27
+ throw answer(409, `the installer of ${id} still runs`, 'CONFLICT', { ...row });
15
28
  };
29
+ // At most installMs, then 504 TIMEOUT; only then the signal asks the installer to stop.
16
30
  export const runInstaller = async (deps, spec) => {
17
31
  if (!deps.install)
18
- throw noInstaller();
19
- return deps.install(spec).catch((err) => {
32
+ throw answer(501, NO_INSTALLER);
33
+ notTwice(deps, spec.id);
34
+ const since = new Date().toISOString();
35
+ const stop = new AbortController();
36
+ const timer = new AbortController();
37
+ const call = deps.install({ ...spec, signal: stop.signal });
38
+ const late = sleep(deps.installMs, undefined, { ref: false, signal: timer.signal }).then(() => {
39
+ stop.abort();
40
+ deps.pending.linger(spec.id, since, call);
41
+ throw answer(504, `the installer did not answer in ${deps.installMs} ms`, 'TIMEOUT');
42
+ });
43
+ late.catch(() => undefined);
44
+ const answered = call.catch((err) => {
20
45
  throw answerOf(err);
21
46
  });
47
+ return Promise.race([answered, late]).finally(() => timer.abort());
22
48
  };