@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
@@ -1,3 +1,4 @@
1
+ import { fail } from '../../envelope/envelope.js';
1
2
  export const serialQueue = () => {
2
3
  let chain = Promise.resolve();
3
4
  return (fn) => {
@@ -6,3 +7,21 @@ export const serialQueue = () => {
6
7
  return run;
7
8
  };
8
9
  };
10
+ // A change that waited ms for the ones before it (the boot too) is 503 and never runs.
11
+ export const waitAtMost = (queue, ms, fn) => {
12
+ let gaveUp = false;
13
+ let timer;
14
+ const late = new Promise((_resolve, reject) => {
15
+ timer = setTimeout(() => {
16
+ gaveUp = true;
17
+ reject(fail('UNAVAILABLE', `other changes ran for ${ms} ms: try again`, { retryAfter: 5 }));
18
+ }, ms);
19
+ });
20
+ const run = queue(async () => {
21
+ clearTimeout(timer);
22
+ if (gaveUp)
23
+ return undefined;
24
+ return fn();
25
+ });
26
+ return Promise.race([run, late]);
27
+ };
@@ -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
+ };
@@ -0,0 +1,14 @@
1
+ import { type Exit } from './child.js';
2
+ import { type Lane } from './lane.js';
3
+ import { type Entry, type SupervisorDeps } from './supervisor.js';
4
+ export interface Retry {
5
+ timer: NodeJS.Timeout;
6
+ }
7
+ type Again = () => Promise<void>;
8
+ export declare const restartsOf: (entry: Entry) => number;
9
+ export declare const cancelRestart: (entry: Entry) => void;
10
+ export declare const resetRestarts: (entry: Entry) => void;
11
+ export declare const healthyFor: (deps: SupervisorDeps, entry: Entry, lane: Lane) => void;
12
+ export declare const reasonOf: (how: Exit) => string;
13
+ export declare const crashed: (deps: SupervisorDeps, entry: Entry, why: string, again: Again) => void;
14
+ export {};
@@ -0,0 +1,59 @@
1
+ import {} from './child.js';
2
+ import {} from './lane.js';
3
+ import {} from './supervisor.js';
4
+ // C6: the restarts since the last enable, update, configure or reload (/health reads it).
5
+ export const restartsOf = (entry) => entry.restarts ?? 0;
6
+ export const cancelRestart = (entry) => {
7
+ if (entry.retry)
8
+ clearTimeout(entry.retry.timer);
9
+ entry.retry = undefined;
10
+ };
11
+ // A new start the owner asked for: the exits and the backoff begin again.
12
+ export const resetRestarts = (entry) => {
13
+ cancelRestart(entry);
14
+ Object.assign(entry, { exits: [], restarts: 0 });
15
+ };
16
+ // Healthy for healthyResetMs on the same child: the past exits no longer count.
17
+ export const healthyFor = (deps, entry, lane) => {
18
+ const reset = () => entry.lane === lane && Object.assign(entry, { exits: [], restarts: 0 });
19
+ setTimeout(reset, deps.healthyResetMs).unref();
20
+ };
21
+ export const reasonOf = (how) => how.words || `the process exited (${how.signal ? `signal ${how.signal}` : `code ${how.code}`})`;
22
+ // The backoff grows with each restart since the reset; the last value repeats.
23
+ const delayOf = (deps, restarts) => deps.backoffMs[Math.min(restarts, deps.backoffMs.length - 1)] ?? 0;
24
+ const giveUp = (deps, entry, why) => {
25
+ const min = Math.round(deps.crashWindowMs / 60_000);
26
+ const error = `exited ${deps.crashLimit} times in ${min} min: ${why}`;
27
+ Object.assign(entry, { state: 'failed', error });
28
+ deps.log.warn('extension failed: too many exits', { id: entry.id, reason: why });
29
+ };
30
+ // In the queue, so it never runs inside a change; a change, remove, reload or stop since cancels it.
31
+ const run = async (deps, entry, retry, again) => {
32
+ if (entry.retry !== retry || entry.lane || deps.stopping.signal.aborted)
33
+ return;
34
+ entry.retry = undefined;
35
+ if (entry.install.enabled === false)
36
+ return;
37
+ entry.restarts = restartsOf(entry) + 1;
38
+ deps.log.info('extension restarts', { id: entry.id, restarts: entry.restarts });
39
+ await again();
40
+ };
41
+ const schedule = (deps, entry, ms, again) => {
42
+ const retry = {};
43
+ const fire = () => void deps.queue(() => run(deps, entry, retry, again)).catch(() => undefined);
44
+ retry.timer = setTimeout(fire, ms);
45
+ retry.timer.unref();
46
+ entry.retry = retry;
47
+ };
48
+ // A child that was the route exited (or a restart did not start): restart after the backoff, or failed.
49
+ export const crashed = (deps, entry, why, again) => {
50
+ const now = Date.now();
51
+ const exits = [...(entry.exits ?? []), now].filter((at) => at > now - deps.crashWindowMs);
52
+ entry.exits = exits;
53
+ if (exits.length >= deps.crashLimit)
54
+ return giveUp(deps, entry, why);
55
+ const ms = delayOf(deps, restartsOf(entry));
56
+ Object.assign(entry, { state: 'starting', error: `${why}: restart in ${ms} ms` });
57
+ deps.log.warn('extension process exited', { id: entry.id, reason: why, restartMs: ms });
58
+ schedule(deps, entry, ms, again);
59
+ };
@@ -1,11 +1,5 @@
1
1
  import { type Express } from 'express';
2
- import { type Entries } from './ops.js';
2
+ import { type Entries } from './entries.js';
3
+ import { type DaemonInfo } from './health-routes.js';
3
4
  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;
5
+ export declare const daemonApp: (deps: SupervisorDeps, entries: Entries, port: () => number, info: DaemonInfo, hostToken: string) => Express;
@@ -4,44 +4,76 @@ import { ok } from '../../envelope/envelope.js';
4
4
  import { BODY_LIMIT } from '../../server/app.js';
5
5
  import { errorHandler, notFound } from '../../server/errors.js';
6
6
  import { localOnly } from './guard.js';
7
- import { addExtension, changeExtension, listed, removeExtension, summary, } from './ops.js';
7
+ import { addExtension } from './add.js';
8
+ import { listed } from './entries.js';
9
+ import { healthRoutes } from './health-routes.js';
10
+ import { requireHostToken } from './host-token.js';
11
+ import { assertReadable } from './installation.js';
12
+ import { changeExtension, removeExtension } from './ops.js';
13
+ import {} from './pending.js';
14
+ import { waitAtMost } from './queue.js';
8
15
  import { proxyTo } from './proxy.js';
16
+ import { reloadRoute } from './reload-route.js';
17
+ import { stopsNow } from './stopping.js';
9
18
  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
+ const reasonOf = (err) => err.details?.reason;
20
+ // A refusal for a file that turned not JSON shows in /health until a change reads the file again.
21
+ const checkReadable = (deps, info) => assertReadable(deps.configDir, info.unreadable).then(() => void (info.notJson = false), (err) => {
22
+ info.notJson = reasonOf(err) === 'not JSON';
23
+ throw err;
24
+ });
25
+ // What a POST body names, for /health: the id, or the folder.
26
+ const named = (body) => {
27
+ const { id, source } = (body ?? {});
28
+ if (typeof id === 'string')
29
+ return { id };
30
+ return typeof source === 'string' ? { source } : {};
19
31
  };
20
- const changes = (deps, entries) => {
21
- const run = deps.queue;
32
+ // Every change in the queue, and none while installation.json cannot be read.
33
+ const runner = (deps, info, p) => (what, fn) => p.track(what, () => waitAtMost(deps.queue, deps.installMs, async () => {
34
+ if (deps.stopping.signal.aborted)
35
+ throw stopsNow();
36
+ await checkReadable(deps, info);
37
+ return fn();
38
+ }));
39
+ const changes = (deps, entries, info, p) => {
40
+ const run = runner(deps, info, p);
22
41
  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))));
42
+ const add = async (req, res) => {
43
+ const what = { op: 'install', ...named(req.body) };
44
+ res.status(201).json(ok(await run(what, () => addExtension(deps, entries, req.body))));
45
+ };
46
+ const change = async ({ params, body }, res) => {
47
+ const what = { op: 'update', id: id(params) };
48
+ res.json(ok(await run(what, () => changeExtension(deps, entries, id(params), body))));
49
+ };
25
50
  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)))));
51
+ const remove = async ({ params, query }, res) => {
52
+ const what = { op: 'remove', id: id(params) };
53
+ res.json(ok(await run(what, () => removeExtension(deps, entries, what.id, purge(query)))));
54
+ };
27
55
  return { add, change, remove };
28
56
  };
29
- const hostRoutes = (app, deps, entries) => {
57
+ const hostRoutes = (app, deps, entries, info, p) => {
30
58
  app.get('/host/extensions', (_req, res) => void res.json(ok([...entries.values()].map(listed))));
31
59
  const json = express.json({ limit: BODY_LIMIT });
32
- const { add, change, remove } = changes(deps, entries);
60
+ const { add, change, remove } = changes(deps, entries, info, p);
33
61
  app.post('/host/extensions', json, add);
34
62
  app.patch('/host/extensions/:id', json, change);
35
63
  app.delete('/host/extensions/:id', remove);
64
+ reloadRoute(app, deps, entries, () => checkReadable(deps, info));
36
65
  };
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) => {
66
+ // C5 and C1: /health, discovery, /host/* (host token), /api/{id}/* and /mcp/{id} to the child; Host and Origin first.
67
+ export const daemonApp = (deps, entries, port, info, hostToken) => {
39
68
  const app = express();
69
+ const proxy = proxyTo(entries, deps, hostToken);
40
70
  app.disable('x-powered-by');
41
71
  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);
72
+ app.use('/api/:id', proxy);
73
+ app.use('/mcp/:id', proxy);
74
+ healthRoutes(app, deps, entries, info);
75
+ app.use('/host', requireHostToken(hostToken));
76
+ hostRoutes(app, deps, entries, info, deps.pending);
45
77
  app.use(notFound);
46
78
  app.use(errorHandler(deps.log));
47
79
  return app;
@@ -0,0 +1 @@
1
+ export declare const clearRunLock: (lock: string, runDir: string) => Promise<void>;
@@ -0,0 +1,15 @@
1
+ import { readFile, unlink } from 'node:fs/promises';
2
+ const pidIn = (lock) => readFile(lock, 'utf8').then(Number, () => 0);
3
+ // Linux: a child of this run folder has it in its env; a reused pid or a zombie does not.
4
+ const childOf = async (pid, runDir) => {
5
+ if (process.platform !== 'linux')
6
+ return true;
7
+ const env = await readFile(`/proc/${pid}/environ`, 'utf8').catch(() => '');
8
+ return env.split('\0').includes(`AGENTAGE_RUN_DIR=${runDir}`);
9
+ };
10
+ // The daemon starts one child per id at a time: a lock not held by a child of this id is left over.
11
+ export const clearRunLock = async (lock, runDir) => {
12
+ const pid = await pidIn(lock);
13
+ if (pid > 0 && !(await childOf(pid, runDir)))
14
+ await unlink(lock).catch(() => undefined);
15
+ };
@@ -0,0 +1,2 @@
1
+ export declare const real: (path: string) => string;
2
+ export declare const assertReach: (reads: string[], writes: string[], configDir: string, id: string) => void;
@@ -0,0 +1,38 @@
1
+ import { realpathSync } from 'node:fs';
2
+ import { isAbsolute, join, relative, sep } from 'node:path';
3
+ import { fail } from '../../envelope/envelope.js';
4
+ // A path is checked as given and modules load from the real path: a symlinked folder needs both.
5
+ export const real = (path) => {
6
+ try {
7
+ return realpathSync(path);
8
+ }
9
+ catch {
10
+ return path;
11
+ }
12
+ };
13
+ // True when path is folder or inside it.
14
+ const within = (path, folder) => {
15
+ const rel = relative(folder, path);
16
+ return rel === '' || (rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel));
17
+ };
18
+ // The tree folders the cli installs into: the shared 0.51 tree, or one tree per id@version.
19
+ const ownTree = (grant, configDir, id) => {
20
+ const [first, second, third] = relative(join(configDir, 'extensions'), grant).split(sep);
21
+ if (first === 'trees')
22
+ return !!second && !second.startsWith('.');
23
+ const name = first === 'packages' && second === 'trees' ? third : undefined;
24
+ return !!name && name.startsWith(`${id}@`) && name.length > id.length + 1;
25
+ };
26
+ // Inside the config dir only the extension's own tree holds no secret, row or other id's folder.
27
+ const exposes = (grant, configDir, id) => within(configDir, grant) || (within(grant, configDir) && !ownTree(grant, configDir, id));
28
+ const refused = (path, why) => fail('VALIDATION_ERROR', `seal: the folder ${path} ${why}`);
29
+ // Node reads a * in a grant as a wildcard; a read grant on the config dir (or above it) shows daemon.json and secrets.json.
30
+ export const assertReach = (reads, writes, configDir, id) => {
31
+ const star = [...reads, ...writes].find((path) => path.includes('*'));
32
+ if (star)
33
+ throw refused(star, 'has a * that Node reads as a wildcard');
34
+ const configs = [configDir, real(configDir)];
35
+ const open = reads.find((grant) => configs.some((config) => exposes(grant, config, id)));
36
+ if (open)
37
+ throw refused(open, 'would expose the agentage config folder');
38
+ };
@@ -0,0 +1,16 @@
1
+ export type Seal = 'on' | 'off';
2
+ export declare const SEAL_FLOOR = "Node 22.22.2 or 24.14.1";
3
+ export declare const sealOf: (version: string) => Seal;
4
+ export declare const permissionFlag: (version: string) => boolean;
5
+ export declare const sealOffReason: (version: string) => string;
6
+ export declare const treeOf: (dir: string) => string;
7
+ export declare const kitReadDirs: (main: string) => string[];
8
+ export interface SealAt {
9
+ id: string;
10
+ main: string;
11
+ dir: string;
12
+ configDir: string;
13
+ runDir: string;
14
+ dataDir: string;
15
+ }
16
+ export declare const sealFlags: ({ id, main, dir, configDir, runDir, dataDir }: SealAt) => string[];
@@ -0,0 +1,71 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { homedir } from 'node:os';
3
+ import { dirname, join, parse, sep } from 'node:path';
4
+ import { assertReach, real } from './seal-reach.js';
5
+ // C2: the permission model with the bypass fixes of D2; the same rule as e2e sealFloorMet.
6
+ export const SEAL_FLOOR = 'Node 22.22.2 or 24.14.1';
7
+ const versionOf = (version) => version.split('.').map(Number);
8
+ const atLeast = (version, major, minor, patch) => {
9
+ const [a = 0, b = 0, c = 0] = versionOf(version);
10
+ return a === major && (b > minor || (b === minor && c >= patch));
11
+ };
12
+ // An odd major has no known fix release: off; an even major above 24 is on.
13
+ export const sealOf = (version) => {
14
+ const [major = 0] = versionOf(version);
15
+ if (major === 22)
16
+ return atLeast(version, 22, 22, 2) ? 'on' : 'off';
17
+ if (major === 24)
18
+ return atLeast(version, 24, 14, 1) ? 'on' : 'off';
19
+ return major > 24 && major % 2 === 0 ? 'on' : 'off';
20
+ };
21
+ // --permission is a stable flag from 22.13.0 and 23.5.0: below the floor it still limits, seal off.
22
+ export const permissionFlag = (version) => {
23
+ const [major = 0] = versionOf(version);
24
+ return major >= 24 || atLeast(version, 22, 13, 0) || atLeast(version, 23, 5, 0);
25
+ };
26
+ export const sealOffReason = (version) => `seal off: ${SEAL_FLOOR} needed, this is Node ${version}`;
27
+ const NODE_MODULES = `${sep}node_modules${sep}`;
28
+ // The folder that holds the node_modules a path sits in (a tree of the cli); else the path itself.
29
+ export const treeOf = (dir) => {
30
+ const at = dir.lastIndexOf(NODE_MODULES);
31
+ return at < 0 ? dir : dir.slice(0, at);
32
+ };
33
+ const hasWorkspaces = (dir) => {
34
+ try {
35
+ return 'workspaces' in JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8'));
36
+ }
37
+ catch {
38
+ return false;
39
+ }
40
+ };
41
+ // The folders from start up, never above the user's home nor the root.
42
+ const upward = (start) => {
43
+ const found = [start];
44
+ for (let dir = start; dir !== homedir() && dir !== parse(dir).root;)
45
+ found.push((dir = dirname(dir)));
46
+ return found;
47
+ };
48
+ // The nearest folder with a package.json; none: the folder of the file.
49
+ const packageRoot = (file) => upward(dirname(file)).find((dir) => existsSync(join(dir, 'package.json'))) ?? dirname(file);
50
+ // Installed: the node_modules that holds the kit. A checkout: its package and its workspace root.
51
+ export const kitReadDirs = (main) => {
52
+ const at = main.lastIndexOf(NODE_MODULES);
53
+ if (at >= 0)
54
+ return [main.slice(0, at + NODE_MODULES.length - 1)];
55
+ const root = packageRoot(main);
56
+ return [...new Set([root, upward(root).find(hasWorkspaces) ?? root])];
57
+ };
58
+ // C2: read kit, tree, run/{id}, data/{id}; write the last two; no child process, worker, addon, WASI, sqlite.
59
+ export const sealFlags = ({ id, main, dir, configDir, runDir, dataDir }) => {
60
+ const both = (paths) => [...new Set(paths.flatMap((path) => [path, real(path)]))];
61
+ const writes = both([runDir, dataDir]);
62
+ const kit = both([...kitReadDirs(main), treeOf(dir)]);
63
+ assertReach(kit, writes, configDir, id);
64
+ const reads = [...new Set([...kit, ...writes])];
65
+ return [
66
+ '--permission',
67
+ '--no-experimental-sqlite',
68
+ ...reads.map((path) => `--allow-fs-read=${path}`),
69
+ ...writes.map((path) => `--allow-fs-write=${path}`),
70
+ ];
71
+ };
@@ -0,0 +1,6 @@
1
+ import { type ExtensionPackage } from '../../manifest/manifest.schema.js';
2
+ export declare const NEEDS_SECRET = "NEEDS_SECRET";
3
+ export declare const assertSecrets: (pkg: ExtensionPackage, secrets: Record<string, string>) => void;
4
+ export declare const needsSecret: (err: unknown) => boolean;
5
+ export declare const healthy: (port: number, ms: number) => Promise<void>;
6
+ export declare const redact: (text: string, secrets: Record<string, string>) => string;
@@ -0,0 +1,28 @@
1
+ import {} from '../../manifest/manifest.schema.js';
2
+ import { hostParts, mountedIn } from '../../manifest/parts.js';
3
+ export const NEEDS_SECRET = 'NEEDS_SECRET';
4
+ // C6: a declared secret of a server part with no value; the daemon checks it before the fork.
5
+ export const assertSecrets = (pkg, secrets) => {
6
+ const names = new Set(hostParts(pkg).flatMap((part) => mountedIn(pkg, part)));
7
+ const missing = [...names].find((name) => !secrets[name]);
8
+ if (missing)
9
+ throw Object.assign(new Error(`needs secret ${missing}`), { code: NEEDS_SECRET });
10
+ };
11
+ export const needsSecret = (err) => err?.code === NEEDS_SECRET;
12
+ // Healthy before it gets the route: the child's own /health answers 200.
13
+ export const healthy = async (port, ms) => {
14
+ const signal = AbortSignal.timeout(ms);
15
+ const res = await fetch(`http://127.0.0.1:${port}/health`, { signal }).catch((err) => {
16
+ if (err.name === 'TimeoutError')
17
+ throw new Error(`health did not answer in ${ms} ms`);
18
+ const cause = err.cause?.code ?? err.message;
19
+ throw new Error(`health could not be reached (${cause})`);
20
+ });
21
+ if (res.status !== 200)
22
+ throw new Error(`health answered ${res.status}`);
23
+ };
24
+ // A secret value this child was given never reaches error, /health, the list or the log.
25
+ export const redact = (text, secrets) => Object.values(secrets)
26
+ .filter((value) => value.length >= 4)
27
+ .sort((a, b) => b.length - a.length)
28
+ .reduce((out, value) => out.split(value).join('***'), text);
@@ -0,0 +1,10 @@
1
+ import { type Child, type Launch } from './child.js';
2
+ export interface Stopping {
3
+ signal: AbortSignal;
4
+ launching: Set<Promise<unknown>>;
5
+ children: Set<Child>;
6
+ }
7
+ export declare const stoppingOf: (signal: AbortSignal) => Stopping;
8
+ export declare const stopsNow: () => import("../../envelope/envelope.js").Failure;
9
+ export declare const launchUnlessStopping: (stopping: Stopping, launch: Launch) => Launch;
10
+ export declare const stopAll: (stopping: Stopping) => Promise<void>;
@@ -0,0 +1,28 @@
1
+ import { fail } from '../../envelope/envelope.js';
2
+ import {} from './child.js';
3
+ export const stoppingOf = (signal) => ({
4
+ signal,
5
+ launching: new Set(),
6
+ children: new Set(),
7
+ });
8
+ export const stopsNow = () => fail('UNAVAILABLE', 'the daemon stops', { retryAfter: 5 });
9
+ const started = async (stopping, launch) => {
10
+ if (stopping.signal.aborted)
11
+ throw stopsNow();
12
+ const child = await launch();
13
+ stopping.children.add(child);
14
+ void child.exited.then(() => stopping.children.delete(child));
15
+ return child;
16
+ };
17
+ // No child outlives stop(): none starts once it began; stopAll waits for the ones in flight.
18
+ export const launchUnlessStopping = (stopping, launch) => (spec) => {
19
+ const run = started(stopping, () => launch(spec));
20
+ stopping.launching.add(run);
21
+ void run.catch(() => undefined).finally(() => stopping.launching.delete(run));
22
+ return run;
23
+ };
24
+ // After the drain of each route: a child still starting or swapping is stopped too.
25
+ export const stopAll = async (stopping) => {
26
+ await Promise.allSettled([...stopping.launching]);
27
+ await Promise.all([...stopping.children].map((child) => child.stop()));
28
+ };