@agentage/extension 0.14.0 → 0.15.1

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 (105) hide show
  1. package/README.md +3 -1
  2. package/dist/contracts/index.d.ts +1 -1
  3. package/dist/contracts/index.js +1 -1
  4. package/dist/discovery/discovery.d.ts +10 -25
  5. package/dist/discovery/discovery.js +7 -1
  6. package/dist/discovery/discovery.schema.d.ts +45 -0
  7. package/dist/discovery/discovery.schema.js +33 -4
  8. package/dist/discovery/served-extras.d.ts +8 -0
  9. package/dist/discovery/served-extras.js +10 -0
  10. package/dist/health/health.d.ts +2 -0
  11. package/dist/health/health.js +4 -2
  12. package/dist/health/health.schema.d.ts +9 -0
  13. package/dist/health/health.schema.js +3 -0
  14. package/dist/host/clock-rate.d.ts +1 -0
  15. package/dist/host/clock-rate.js +12 -0
  16. package/dist/host/daemon/add.js +29 -4
  17. package/dist/host/daemon/child-files.d.ts +20 -0
  18. package/dist/host/daemon/child-files.js +45 -0
  19. package/dist/host/daemon/child.d.ts +10 -4
  20. package/dist/host/daemon/child.js +68 -43
  21. package/dist/host/daemon/daemon-files.d.ts +3 -0
  22. package/dist/host/daemon/daemon-files.js +5 -1
  23. package/dist/host/daemon/daemon.d.ts +1 -0
  24. package/dist/host/daemon/daemon.js +21 -6
  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 +16 -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/last-words.d.ts +2 -0
  34. package/dist/host/daemon/last-words.js +28 -0
  35. package/dist/host/daemon/limits.d.ts +4 -0
  36. package/dist/host/daemon/limits.js +7 -0
  37. package/dist/host/daemon/ops.js +4 -1
  38. package/dist/host/daemon/pending.d.ts +1 -1
  39. package/dist/host/daemon/proxy.d.ts +1 -1
  40. package/dist/host/daemon/proxy.js +16 -8
  41. package/dist/host/daemon/redact-stream.d.ts +4 -0
  42. package/dist/host/daemon/redact-stream.js +24 -0
  43. package/dist/host/daemon/reload-marker.d.ts +8 -0
  44. package/dist/host/daemon/reload-marker.js +56 -0
  45. package/dist/host/daemon/reload-route.d.ts +4 -0
  46. package/dist/host/daemon/reload-route.js +21 -0
  47. package/dist/host/daemon/reload.d.ts +10 -0
  48. package/dist/host/daemon/reload.js +73 -0
  49. package/dist/host/daemon/restart.d.ts +14 -0
  50. package/dist/host/daemon/restart.js +59 -0
  51. package/dist/host/daemon/routes.d.ts +2 -10
  52. package/dist/host/daemon/routes.js +13 -31
  53. package/dist/host/daemon/run-lock.d.ts +1 -0
  54. package/dist/host/daemon/run-lock.js +15 -0
  55. package/dist/host/daemon/seal-reach.d.ts +2 -0
  56. package/dist/host/daemon/seal-reach.js +38 -0
  57. package/dist/host/daemon/seal.d.ts +16 -0
  58. package/dist/host/daemon/seal.js +71 -0
  59. package/dist/host/daemon/start-checks.d.ts +7 -0
  60. package/dist/host/daemon/start-checks.js +29 -0
  61. package/dist/host/daemon/supervisor.d.ts +9 -3
  62. package/dist/host/daemon/supervisor.js +33 -40
  63. package/dist/host/data-lock.d.ts +2 -1
  64. package/dist/host/data-lock.js +25 -6
  65. package/dist/host/host-env.d.ts +1 -0
  66. package/dist/host/host-env.js +2 -0
  67. package/dist/host/host-extension.d.ts +6 -0
  68. package/dist/host/host-extension.js +28 -44
  69. package/dist/host/host-parts.d.ts +25 -0
  70. package/dist/host/host-parts.js +82 -0
  71. package/dist/host/host-store.d.ts +3 -0
  72. package/dist/host/host-store.js +21 -2
  73. package/dist/host/main.js +2 -0
  74. package/dist/host/part-checks.d.ts +2 -0
  75. package/dist/host/part-checks.js +19 -0
  76. package/dist/host/serve-host.js +10 -6
  77. package/dist/manifest/parts.d.ts +3 -0
  78. package/dist/manifest/parts.js +3 -0
  79. package/dist/mcp/mcp-app.d.ts +4 -0
  80. package/dist/mcp/mcp-app.js +11 -11
  81. package/dist/runtime/part-mounts.d.ts +31 -0
  82. package/dist/runtime/part-mounts.js +57 -0
  83. package/dist/runtime/part-runners.d.ts +2 -15
  84. package/dist/runtime/part-runners.js +13 -58
  85. package/dist/server/app.d.ts +5 -3
  86. package/dist/server/app.js +16 -17
  87. package/dist/tool/build.d.ts +1 -0
  88. package/dist/tool/build.js +3 -2
  89. package/dist/tool/check.d.ts +3 -1
  90. package/dist/tool/check.js +25 -9
  91. package/dist/tool/container-parts.d.ts +1 -1
  92. package/dist/tool/container-parts.js +6 -6
  93. package/dist/tool/format.d.ts +1 -0
  94. package/dist/tool/format.js +17 -8
  95. package/dist/tool/kit-version.d.ts +2 -0
  96. package/dist/tool/kit-version.js +12 -0
  97. package/dist/tool/record-extras.js +5 -12
  98. package/dist/worker/clock.d.ts +6 -0
  99. package/dist/worker/clock.js +21 -0
  100. package/dist/worker/scheduler.d.ts +1 -0
  101. package/dist/worker/scheduler.js +6 -2
  102. package/package.json +1 -1
  103. package/schemas/extension-discovery.schema.json +61 -34
  104. package/schemas/extension-record.schema.json +1 -1
  105. package/schemas/health.schema.json +17 -0
@@ -3,9 +3,13 @@ import { join } from 'node:path';
3
3
  import { readJsonFile, withFileLock, writeJsonFile } from './json-file.js';
4
4
  const DAEMON_FILE = 'daemon.json';
5
5
  export const DAEMON_PROTOCOL = 1;
6
- export const writeDaemonFile = (configDir, file) => writeJsonFile(join(configDir, DAEMON_FILE), file);
6
+ export const writeDaemonFile = (configDir, file) => writeJsonFile(join(configDir, DAEMON_FILE), file, 0o600);
7
7
  export const removeDaemonFile = (configDir) => unlink(join(configDir, DAEMON_FILE)).catch(() => undefined);
8
8
  export const dataDirOf = (configDir, id) => join(configDir, 'data', id);
9
+ // C2: the folder only this child reads and writes (secrets, TMPDIR, the store lock).
10
+ export const runDirOf = (configDir, id) => join(configDir, 'run', id);
11
+ // No user data in it: removed with the extension; each start makes its secrets and tmp anew.
12
+ export const clearRunDir = (configDir, id) => rm(runDirOf(configDir, id), { recursive: true, force: true });
9
13
  export const purgeData = (configDir, id) => rm(dataDirOf(configDir, id), { recursive: true, force: true });
10
14
  const fileOf = (configDir, kind) => join(configDir, `${kind}.json`);
11
15
  export const readValues = async (configDir, kind, id) => (await readJsonFile(fileOf(configDir, kind), {}))[id] ?? {};
@@ -7,6 +7,7 @@ export interface DaemonOptions extends Partial<Limits> {
7
7
  install?: Installer;
8
8
  version: string;
9
9
  startedBy: string;
10
+ clockRate?: number;
10
11
  }
11
12
  export interface Daemon {
12
13
  port: number;
@@ -8,12 +8,15 @@ import { removeDaemonFile, writeDaemonFile, DAEMON_PROTOCOL } from './daemon-fil
8
8
  import { assertNoOtherDaemon } from './daemon-owner.js';
9
9
  import { bootInstallation, updateInstallation } from './installation.js';
10
10
  import {} from './entries.js';
11
+ import { newHostToken } from './host-token.js';
12
+ import { sealOffReason } from './seal.js';
11
13
  import { limitsOf } from './limits.js';
12
14
  import { pendingChanges } from './pending.js';
13
15
  import { serialQueue } from './queue.js';
14
16
  import { launchUnlessStopping, stopAll, stoppingOf } from './stopping.js';
15
17
  import { daemonApp } from './routes.js';
16
18
  import { runInstaller } from './installer-call.js';
19
+ import { repairReload } from './reload-marker.js';
17
20
  import { halt, startEntry } from './supervisor.js';
18
21
  export const DAEMON_PORT = 4243;
19
22
  const warnOf = (deps) => (err) => deps.log.warn('a daemon file was not cleaned at boot', { reason: err.message });
@@ -42,6 +45,8 @@ const boot = async (deps, entries) => {
42
45
  const off = all.filter((e) => e.state === 'disabled');
43
46
  const on = all.filter((e) => e.state !== 'disabled');
44
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));
45
50
  for (const entry of ordered)
46
51
  await startEntry(deps, entry);
47
52
  for (const entry of off)
@@ -58,13 +63,20 @@ const stopper = (server, entries, deps, life) => {
58
63
  };
59
64
  return () => (stopped ??= stop());
60
65
  };
61
- // C4: how a client finds this daemon.
62
- 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, {
63
68
  pid: process.pid,
64
69
  port,
65
70
  version,
66
71
  protocol: DAEMON_PROTOCOL,
67
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) }),
68
80
  });
69
81
  const depsOf = (opts, launch, origin, stopping) => ({
70
82
  configDir: opts.configDir,
@@ -87,13 +99,15 @@ export const startDaemon = async (opts, launch) => {
87
99
  const life = new AbortController();
88
100
  const deps = depsOf(opts, launch, () => `http://127.0.0.1:${port}`, stoppingOf(life.signal));
89
101
  const { entries, ...file } = await loadEntries(deps);
90
- const info = { version: opts.version, pid: process.pid, protocol: DAEMON_PROTOCOL, ...file };
91
- const app = daemonApp(deps, entries, () => port, info);
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);
92
106
  const server = await listen(app, port, '127.0.0.1');
93
107
  port = server.address().port;
94
108
  const stop = stopper(server, entries, deps, life);
95
109
  try {
96
- await announce(opts, port);
110
+ await announce(opts, port, hostToken);
97
111
  await deps.queue(() => boot(deps, entries));
98
112
  }
99
113
  catch (err) {
@@ -103,4 +117,5 @@ export const startDaemon = async (opts, launch) => {
103
117
  return { port, stop };
104
118
  };
105
119
  // One daemon on 127.0.0.1, one child process for each extension (D1).
106
- export const createDaemon = (opts) => startDaemon(opts, forkLaunch(undefined, opts.startMs));
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,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,10 +2,11 @@ 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 (DNS rebinding, a cross-site form): no port given, the socket's own.
6
- export const localOnly = (port) => (req, _res, next) => {
7
- const at = port?.() ?? req.socket.localPort;
8
- const hosts = [`127.0.0.1:${at}`, `localhost:${at}`];
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);
9
10
  const origin = req.get('origin');
10
11
  const hostOk = hosts.includes(req.get('host') ?? '');
11
12
  const originOk = origin === undefined || hosts.some((host) => origin === `http://${host}`);
@@ -14,3 +15,14 @@ export const localOnly = (port) => (req, _res, next) => {
14
15
  throw fail('FORBIDDEN', 'Only this machine may call this server');
15
16
  next();
16
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
+ };
@@ -0,0 +1,2 @@
1
+ import { type Exit } from './child.js';
2
+ export declare const lastWords: (tail: string, how: Exit) => string;
@@ -0,0 +1,28 @@
1
+ import {} from './child.js';
2
+ // Lines that never say why: blanks, stack frames, error properties, the Node version, the hint.
3
+ const NOISE = [
4
+ /^\s*$/,
5
+ /^\s+at /,
6
+ /^\s*[{}]\s*$/,
7
+ /^\s+[\w$'"]+: /,
8
+ /^Node\.js v\d/,
9
+ /^\(Use `node/,
10
+ ];
11
+ // A log row below error (listening, a request, a warning) is not why a child exited.
12
+ const QUIET = /^\{.*"level":"(warn|info|debug|trace)"/;
13
+ const msgOf = (line) => {
14
+ try {
15
+ return String(JSON.parse(line).msg ?? line);
16
+ }
17
+ catch {
18
+ return line;
19
+ }
20
+ };
21
+ // The last line that says why (an error line, a log row's msg, or the thrown text): from stderr.
22
+ export const lastWords = (tail, how) => {
23
+ const lines = tail.split('\n').map((l) => l.trimEnd());
24
+ const line = lines.reverse().find((l) => !QUIET.test(l) && !NOISE.some((re) => re.test(l)));
25
+ if (line)
26
+ return msgOf(line).replace(/^[A-Za-z]*Error(?: \[[A-Z_]+\])?: /, '');
27
+ return `exited with ${how.signal ? `signal ${how.signal}` : `code ${how.code}`}`;
28
+ };
@@ -6,6 +6,10 @@ export declare const LIMITS: {
6
6
  gateMs: number;
7
7
  answerMs: number;
8
8
  installMs: number;
9
+ backoffMs: number[];
10
+ crashLimit: number;
11
+ crashWindowMs: number;
12
+ healthyResetMs: number;
9
13
  };
10
14
  export type Limits = typeof LIMITS;
11
15
  export declare const limitsOf: (given: Partial<Limits>) => Limits;
@@ -15,6 +15,13 @@ export const LIMITS = {
15
15
  // One Installer call (POST, PATCH, each entry at boot), and a change queued behind others:
16
16
  // above the cli's npm bound (10 min), below its client wait (12 min).
17
17
  installMs: 660_000,
18
+ // C6: the waits before each restart of a child that exited; the last one repeats.
19
+ backoffMs: [1_000, 2_000, 4_000, 8_000, 16_000],
20
+ // C6: this many exits inside crashWindowMs is failed, with no more restarts.
21
+ crashLimit: 5,
22
+ crashWindowMs: 600_000,
23
+ // A child healthy this long has its restart count and exits reset.
24
+ healthyResetMs: 600_000,
18
25
  };
19
26
  export const limitsOf = (given) => {
20
27
  const keys = Object.keys(LIMITS);
@@ -3,7 +3,8 @@ import { z } from 'zod';
3
3
  import { fail } from '../../envelope/envelope.js';
4
4
  import { parse } from '../../envelope/parse.js';
5
5
  import { SecretNameSchema } from '../../manifest/primitives.schema.js';
6
- import { purgeData } from './daemon-files.js';
6
+ import { clearRunDir, purgeData } from './daemon-files.js';
7
+ import { unmarkReload } from './reload-marker.js';
7
8
  import { entryOf, summary } from './entries.js';
8
9
  import { unsynced, writeAll } from './write-all.js';
9
10
  import { runInstaller } from './installer-call.js';
@@ -83,6 +84,8 @@ export const removeExtension = async (deps, entries, id, purge) => {
83
84
  await writeAll(deps, id, {}, { install: entry.install, values: await valuesOf(deps.configDir, id) });
84
85
  entries.delete(id);
85
86
  await halt(entry, deps.drainMs);
87
+ await unmarkReload(deps.configDir, id);
88
+ await clearRunDir(deps.configDir, id);
86
89
  if (purge)
87
90
  await purgeData(deps.configDir, id);
88
91
  return { id };
@@ -1,4 +1,4 @@
1
- export type PendingOp = 'install' | 'update' | 'remove';
1
+ export type PendingOp = 'install' | 'update' | 'remove' | 'reload';
2
2
  export interface Pending {
3
3
  op: PendingOp;
4
4
  id?: string;
@@ -3,4 +3,4 @@ import { type RequestHandler } from 'express';
3
3
  import { type Entries } from './entries.js';
4
4
  import { type Limits } from './limits.js';
5
5
  export declare const endToEnd: (headers: IncomingHttpHeaders) => IncomingHttpHeaders;
6
- export declare const proxyTo: (entries: Entries, limits: Pick<Limits, "gateMs" | "answerMs">) => RequestHandler;
6
+ export declare const proxyTo: (entries: Entries, limits: Pick<Limits, "gateMs" | "answerMs">, hostToken?: string) => RequestHandler;
@@ -2,6 +2,7 @@ import { request, } from 'node:http';
2
2
  import { setTimeout as sleep } from 'node:timers/promises';
3
3
  import {} from 'express';
4
4
  import { fail } from '../../envelope/envelope.js';
5
+ import { carriesHostToken } from './host-token.js';
5
6
  import { enter } from './lane.js';
6
7
  import {} from './entries.js';
7
8
  import {} from './limits.js';
@@ -44,9 +45,16 @@ const noAnswer = (ms) => Object.assign(fail('UNAVAILABLE', `The extension did no
44
45
  status: 504,
45
46
  retryAfter: undefined,
46
47
  });
47
- const requestTo = (req, lane) => {
48
- const { method, originalUrl: path } = req;
48
+ // D11: the host token is for the daemon; a child never sees it, also when a client sends it here.
49
+ const forChild = (req, hostToken) => {
49
50
  const headers = endToEnd(req.headers);
51
+ if (hostToken && carriesHostToken(req.headers, hostToken))
52
+ delete headers['authorization'];
53
+ return headers;
54
+ };
55
+ const requestTo = (req, lane, hostToken) => {
56
+ const { method, originalUrl: path } = req;
57
+ const headers = forChild(req, hostToken);
50
58
  const options = { host: '127.0.0.1', port: lane.child.port, method, path, headers, agent: false };
51
59
  return request(options);
52
60
  };
@@ -68,10 +76,9 @@ const relay = (upstream, res, next, ms) => {
68
76
  });
69
77
  return () => clearTimeout(timer);
70
78
  };
71
- // Streams the request to the child as it came (path and query kept), no pooled connection.
72
- const forward = (req, res, next, to, ms) => {
79
+ const forward = (req, res, next, { to, ms, hostToken }) => {
73
80
  const { lane, leave } = to;
74
- const upstream = requestTo(req, lane);
81
+ const upstream = requestTo(req, lane, hostToken);
75
82
  const stop = relay(upstream, res, next, ms);
76
83
  upstream.on('error', leave);
77
84
  // A client that went away aborts the request to the child too.
@@ -83,7 +90,8 @@ const forward = (req, res, next, to, ms) => {
83
90
  });
84
91
  req.pipe(upstream);
85
92
  };
86
- export const proxyTo = (entries, limits) => async (req, res, next) => {
87
- const taken = await laneFor(entries, String(req.params['id']), limits.gateMs);
88
- forward(req, res, next, taken, limits.answerMs);
93
+ // ANY /api/{id}/* and /mcp/{id} (C1): the same lane, the same refusals (404 unknown, 503 not running).
94
+ export const proxyTo = (entries, limits, hostToken) => async (req, res, next) => {
95
+ const to = await laneFor(entries, String(req.params['id']), limits.gateMs);
96
+ forward(req, res, next, { to, ms: limits.answerMs, hostToken });
89
97
  };
@@ -0,0 +1,4 @@
1
+ import { type Readable, type Writable } from 'node:stream';
2
+ export declare const PENDING_MAX: number;
3
+ export declare const redactedLines: (write: (text: string) => void, secrets: Record<string, string>) => (chunk?: string) => void;
4
+ export declare const pipeRedacted: (from: Readable | null, to: Writable, secrets: Record<string, string>) => void;
@@ -0,0 +1,24 @@
1
+ import {} from 'node:stream';
2
+ import { maskedForms, redact } from './start-checks.js';
3
+ // Past this, a line with no newline is written up to a tail that could hold a split secret.
4
+ export const PENDING_MAX = 64 * 1024;
5
+ // By line, so a value split over two chunks is masked too; a call with no chunk flushes the rest.
6
+ export const redactedLines = (write, secrets) => {
7
+ const keep = Math.max(0, (maskedForms(secrets)[0]?.length ?? 1) - 1);
8
+ let rest = '';
9
+ return (chunk) => {
10
+ const lines = (rest + (chunk ?? '\n')).split('\n');
11
+ rest = lines.pop() ?? '';
12
+ const cut = rest.length > PENDING_MAX ? rest.length - keep : 0;
13
+ const out = `${lines.join('\n')}${lines.length && chunk !== undefined ? '\n' : ''}`;
14
+ if (out || cut)
15
+ write(redact(out + rest.slice(0, cut), secrets));
16
+ rest = rest.slice(cut);
17
+ };
18
+ };
19
+ // A child stream to the daemon's own, masked; its rest is written at the end.
20
+ export const pipeRedacted = (from, to, secrets) => {
21
+ const out = redactedLines((text) => to.write(text), secrets);
22
+ from?.on('data', (chunk) => out(chunk.toString()));
23
+ from?.once('end', () => out());
24
+ };
@@ -0,0 +1,8 @@
1
+ import { type Log } from '../../log/log.js';
2
+ import { type Entry } from './supervisor.js';
3
+ export declare const markReload: (configDir: string, id: string, dir: string) => Promise<void>;
4
+ export declare const unmarkReload: (configDir: string, id: string) => Promise<void>;
5
+ export declare const swapIn: (dir: string) => Promise<boolean>;
6
+ export declare const swapBack: (dir: string) => Promise<void>;
7
+ export declare const confirmReload: (configDir: string, id: string, dir: string) => Promise<void>;
8
+ export declare const repairReload: (configDir: string, entry: Entry, log: Log) => Promise<void>;
@@ -0,0 +1,56 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { cp, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+ import {} from '../../log/log.js';
5
+ import {} from './supervisor.js';
6
+ // D14 (revised): the child runs dist/; dist.next/ is the watcher's tree and stays; dist.prev/ is the last good.
7
+ const DIST = 'dist';
8
+ const NEXT = 'dist.next';
9
+ const PREV = 'dist.prev';
10
+ const markerOf = (configDir, id) => join(configDir, 'run', id, 'reload.json');
11
+ const gone = (path) => rm(path, { recursive: true, force: true });
12
+ // Written once a stale dist.prev is gone: marker and dist.prev together mean a swap not confirmed.
13
+ export const markReload = async (configDir, id, dir) => {
14
+ await gone(join(dir, PREV));
15
+ const marker = markerOf(configDir, id);
16
+ await mkdir(join(marker, '..'), { recursive: true });
17
+ await writeFile(marker, JSON.stringify({ id, dir, complete: false, at: new Date().toISOString() }));
18
+ };
19
+ export const unmarkReload = (configDir, id) => gone(markerOf(configDir, id));
20
+ // dist to dist.prev, a copy of dist.next to dist; false when there is no new build (a plain restart).
21
+ export const swapIn = async (dir) => {
22
+ if (!existsSync(join(dir, NEXT)))
23
+ return false;
24
+ if (existsSync(join(dir, DIST)))
25
+ await rename(join(dir, DIST), join(dir, PREV));
26
+ await cp(join(dir, NEXT), join(dir, DIST), { recursive: true });
27
+ return true;
28
+ };
29
+ // The copied build goes, the last good one comes back; with no dist.prev, dist is never touched.
30
+ export const swapBack = async (dir) => {
31
+ if (!existsSync(join(dir, PREV)))
32
+ return;
33
+ await gone(join(dir, DIST));
34
+ await rename(join(dir, PREV), join(dir, DIST));
35
+ };
36
+ // The new build is healthy: the marker first, then the old build.
37
+ export const confirmReload = async (configDir, id, dir) => {
38
+ await unmarkReload(configDir, id);
39
+ await gone(join(dir, PREV));
40
+ };
41
+ const markedDir = async (configDir, id) => {
42
+ const text = await readFile(markerOf(configDir, id), 'utf8');
43
+ return JSON.parse(text).dir;
44
+ };
45
+ // At boot: a marker of this row's folder with a dist.prev is a cut reload, put back to the last good build.
46
+ export const repairReload = async (configDir, entry, log) => {
47
+ const dir = entry.install.source;
48
+ if (!dir || !existsSync(markerOf(configDir, entry.id)))
49
+ return;
50
+ const ours = (await markedDir(configDir, entry.id).catch(() => undefined)) === dir;
51
+ if (ours && existsSync(join(dir, PREV))) {
52
+ await swapBack(dir);
53
+ log.warn('a cut reload was put back to the last good build', { id: entry.id });
54
+ }
55
+ await unmarkReload(configDir, entry.id);
56
+ };
@@ -0,0 +1,4 @@
1
+ import { type Express } from 'express';
2
+ import { type Entries } from './entries.js';
3
+ import { type SupervisorDeps } from './supervisor.js';
4
+ export declare const reloadRoute: (app: Express, deps: SupervisorDeps, entries: Entries, readable: () => Promise<void>) => void;
@@ -0,0 +1,21 @@
1
+ import express, {} from 'express';
2
+ import { ok } from '../../envelope/envelope.js';
3
+ import { BODY_LIMIT } from '../../server/app.js';
4
+ import {} from './entries.js';
5
+ import { waitAtMost } from './queue.js';
6
+ import { reloadExtension } from './reload.js';
7
+ import { stopsNow } from './stopping.js';
8
+ import {} from './supervisor.js';
9
+ // In the change queue (a second reload waits); refused like every change while installation.json is unreadable.
10
+ export const reloadRoute = (app, deps, entries, readable) => {
11
+ app.post('/host/extensions/:id/reload', express.json({ limit: BODY_LIMIT }), async (req, res) => {
12
+ const id = String(req.params['id']);
13
+ const run = () => waitAtMost(deps.queue, deps.installMs, async () => {
14
+ if (deps.stopping.signal.aborted)
15
+ throw stopsNow();
16
+ await readable();
17
+ return reloadExtension(deps, entries, id, req.body);
18
+ });
19
+ res.json(ok(await deps.pending.track({ op: 'reload', id }, run)));
20
+ });
21
+ };
@@ -0,0 +1,10 @@
1
+ import { type Entries } from './entries.js';
2
+ import { type SupervisorDeps } from './supervisor.js';
3
+ export declare const reloadExtension: (deps: SupervisorDeps, entries: Entries, id: string, body: unknown) => Promise<{
4
+ refused?: string | undefined;
5
+ reloaded: boolean;
6
+ pid?: number | undefined;
7
+ id: string;
8
+ version: string;
9
+ state: import("./supervisor.js").State;
10
+ }>;
@@ -0,0 +1,73 @@
1
+ import { z } from 'zod';
2
+ import { fail } from '../../envelope/envelope.js';
3
+ import { parse } from '../../envelope/parse.js';
4
+ import { entryOf } from './entries.js';
5
+ import { confirmReload, markReload, swapBack, swapIn, unmarkReload } from './reload-marker.js';
6
+ import { resetRestarts } from './restart.js';
7
+ import { halt, hold, startEntry } from './supervisor.js';
8
+ const ReloadSchema = z.strictObject({});
9
+ // Only a linked working copy has a build to reload; a disabled one stays stopped.
10
+ const folderOf = (entry) => {
11
+ const dir = entry.install.source;
12
+ if (!dir)
13
+ throw fail('VALIDATION_ERROR', `${entry.id} is not a folder: only a linked folder reloads`);
14
+ if (entry.install.enabled === false)
15
+ throw fail('CONFLICT', `${entry.id} is disabled: enable it first`);
16
+ return dir;
17
+ };
18
+ const answer = (entry, refused) => ({
19
+ id: entry.id,
20
+ version: entry.version,
21
+ state: entry.state,
22
+ ...(entry.lane && { pid: entry.lane.child.pid }),
23
+ reloaded: refused === undefined,
24
+ ...(refused !== undefined && { refused }),
25
+ });
26
+ // Not healthy: the copied build goes, the last good build starts again.
27
+ const restoreLast = async (deps, entry, dir, swapped) => {
28
+ if (swapped)
29
+ await swapBack(dir);
30
+ await unmarkReload(deps.configDir, entry.id);
31
+ if (swapped)
32
+ await startEntry(deps, entry);
33
+ };
34
+ // The new child runs: what is left to clean is best-effort, never a second start.
35
+ const settle = async (deps, entry, dir) => {
36
+ await confirmReload(deps.configDir, entry.id, dir).catch((err) => deps.log.warn('a reload left dist.prev or its marker', { id: entry.id, reason: err.message }));
37
+ resetRestarts(entry);
38
+ return answer(entry);
39
+ };
40
+ const tryNew = async (deps, entry, dir) => {
41
+ await markReload(deps.configDir, entry.id, dir);
42
+ const swapped = await swapIn(dir);
43
+ const err = await startEntry(deps, entry);
44
+ if (!err)
45
+ return settle(deps, entry, dir);
46
+ await restoreLast(deps, entry, dir, swapped);
47
+ return answer(entry, err.message.split('\n')[0]);
48
+ };
49
+ // A file step failed (EPERM, EBUSY): the last good build runs again, the answer says why.
50
+ const fileFailed = async (deps, entry, dir, err) => {
51
+ await swapBack(dir).catch((again) => deps.log.warn('a reload could not put the last good build back', { reason: again.message }));
52
+ await unmarkReload(deps.configDir, entry.id).catch(() => undefined);
53
+ await startEntry(deps, entry);
54
+ return answer(entry, err.message.split('\n')[0]);
55
+ };
56
+ // D14: stop and wait for the exit (one writer on the store), swap the builds, start, wait healthy.
57
+ const reloadIn = async (deps, entry, dir) => {
58
+ await halt(entry, deps.drainMs);
59
+ return tryNew(deps, entry, dir).catch((err) => fileFailed(deps, entry, dir, err));
60
+ };
61
+ // POST /host/extensions/{id}/reload, body {}: requests wait at the gate and go to the new child.
62
+ export const reloadExtension = async (deps, entries, id, body) => {
63
+ parse(ReloadSchema, body ?? {}, 'Invalid body');
64
+ const entry = entryOf(entries, id);
65
+ const dir = folderOf(entry);
66
+ const release = hold(entry);
67
+ try {
68
+ return await reloadIn(deps, entry, dir);
69
+ }
70
+ finally {
71
+ release();
72
+ }
73
+ };