@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
1
  export declare const readJsonFile: <T>(file: string, fallback: T) => Promise<T>;
2
- export declare const writeJsonFile: (file: string, value: unknown, mode?: number) => Promise<void>;
3
- export declare const withFileLock: <T>(file: string, fn: () => Promise<T>) => Promise<T>;
2
+ export declare const writeJsonFile: (file: string, value: unknown, given?: number) => Promise<void>;
3
+ export declare const LOCK_WAIT_MS = 5000;
4
+ export declare const withFileLock: <T>(file: string, fn: () => T | Promise<T>, waitMs?: number) => Promise<T>;
@@ -1,5 +1,8 @@
1
1
  import { randomBytes } from 'node:crypto';
2
- import { chmod, open, readFile, rename } from 'node:fs/promises';
2
+ import { chmod, open, readFile, rename, stat } from 'node:fs/promises';
3
+ import { setTimeout as sleep } from 'node:timers/promises';
4
+ import { basename } from 'node:path';
5
+ import { fail } from '../../envelope/envelope.js';
3
6
  import { DATA_DIR_LOCKED, lockDataDir } from '../data-lock.js';
4
7
  export const readJsonFile = async (file, fallback) => {
5
8
  try {
@@ -11,8 +14,11 @@ export const readJsonFile = async (file, fallback) => {
11
14
  throw err;
12
15
  }
13
16
  };
17
+ // The mode of a file already there, narrowed by the default: a 0600 file is never widened.
18
+ const modeOf = (file, mode) => stat(file).then((st) => st.mode & mode & 0o777, () => mode);
14
19
  // A reader sees the old file or the new one, never half of one, also after a power loss.
15
- export const writeJsonFile = async (file, value, mode = 0o644) => {
20
+ export const writeJsonFile = async (file, value, given = 0o644) => {
21
+ const mode = await modeOf(file, given);
16
22
  const tmp = `${file}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
17
23
  const handle = await open(tmp, 'w', mode);
18
24
  try {
@@ -25,23 +31,28 @@ export const writeJsonFile = async (file, value, mode = 0o644) => {
25
31
  await chmod(tmp, mode);
26
32
  await rename(tmp, file);
27
33
  };
28
- const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
29
- // The pid lock of data-lock.ts: a dead holder's lock is taken over, a live one is waited for.
30
- const acquire = async (file) => {
31
- for (let tries = 0;; tries += 1) {
34
+ export const LOCK_WAIT_MS = 5_000;
35
+ // A live holder (or a reused pid of a dead one) named, so a person can check that process.
36
+ const lockedBy = (file, err, waitMs) => fail('UNAVAILABLE', `${basename(file)} is locked by process ${err.pid ?? 0}: waited ${waitMs} ms`, { retryAfter: 1 });
37
+ // The pid lock of data-lock.ts: a dead holder's lock is taken over, a live one waited for waitMs.
38
+ const acquire = async (file, waitMs) => {
39
+ const until = Date.now() + waitMs;
40
+ for (;;) {
32
41
  try {
33
42
  return await lockDataDir(file);
34
43
  }
35
44
  catch (err) {
36
- if (err.code !== DATA_DIR_LOCKED || tries >= 200)
45
+ if (err.code !== DATA_DIR_LOCKED)
37
46
  throw err;
38
- await pause(25);
47
+ if (Date.now() >= until)
48
+ throw lockedBy(file, err, waitMs);
49
+ await sleep(25);
39
50
  }
40
51
  }
41
52
  };
42
53
  // One writer at a time across processes: an exclusive lock file (<file>.lock) beside the file.
43
- export const withFileLock = async (file, fn) => {
44
- const release = await acquire(file);
54
+ export const withFileLock = async (file, fn, waitMs = LOCK_WAIT_MS) => {
55
+ const release = await acquire(file, waitMs);
45
56
  try {
46
57
  return await fn();
47
58
  }
@@ -1,11 +1,9 @@
1
1
  import { type Child } from './child.js';
2
2
  export interface Lane {
3
3
  child: Child;
4
- version: string;
5
4
  open: number;
6
5
  idle: (() => void)[];
7
6
  }
8
- export declare const laneOf: (child: Child, version: string) => Lane;
7
+ export declare const laneOf: (child: Child) => Lane;
9
8
  export declare const enter: (lane: Lane) => (() => void);
10
- export declare const drained: (lane: Lane) => Promise<void>;
11
9
  export declare const retire: (lane: Lane | undefined, drainMs: number) => Promise<void>;
@@ -1,10 +1,6 @@
1
+ import { setTimeout as sleep } from 'node:timers/promises';
1
2
  import {} from './child.js';
2
- export const laneOf = (child, version) => ({
3
- child,
4
- version,
5
- open: 0,
6
- idle: [],
7
- });
3
+ export const laneOf = (child) => ({ child, open: 0, idle: [] });
8
4
  // Counts one request until leave() is called (once).
9
5
  export const enter = (lane) => {
10
6
  lane.open += 1;
@@ -18,12 +14,11 @@ export const enter = (lane) => {
18
14
  lane.idle.splice(0).forEach((resolve) => resolve());
19
15
  };
20
16
  };
21
- export const drained = (lane) => lane.open === 0 ? Promise.resolve() : new Promise((resolve) => lane.idle.push(resolve));
22
- const waited = (ms) => new Promise((resolve) => setTimeout(resolve, ms).unref());
17
+ const drained = (lane) => lane.open === 0 ? Promise.resolve() : new Promise((resolve) => lane.idle.push(resolve));
23
18
  // Waits for the open requests (at most drainMs, so a hung one blocks nothing), then stops the child.
24
19
  export const retire = async (lane, drainMs) => {
25
20
  if (!lane)
26
21
  return;
27
- await Promise.race([drained(lane), waited(drainMs)]);
22
+ await Promise.race([drained(lane), sleep(drainMs, undefined, { ref: false })]);
28
23
  await lane.child.stop();
29
24
  };
@@ -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
+ };
@@ -0,0 +1,15 @@
1
+ export declare const LIMITS: {
2
+ drainMs: number;
3
+ startMs: number;
4
+ healthMs: number;
5
+ lockMs: number;
6
+ gateMs: number;
7
+ answerMs: number;
8
+ installMs: number;
9
+ backoffMs: number[];
10
+ crashLimit: number;
11
+ crashWindowMs: number;
12
+ healthyResetMs: number;
13
+ };
14
+ export type Limits = typeof LIMITS;
15
+ export declare const limitsOf: (given: Partial<Limits>) => Limits;
@@ -0,0 +1,29 @@
1
+ // Every wait of the daemon has a bound; each is a createDaemon option (docs/part-image.md).
2
+ export const LIMITS = {
3
+ // An old child's open requests before it is stopped.
4
+ drainMs: 10_000,
5
+ // A forked child's port report; then SIGKILL.
6
+ startMs: 60_000,
7
+ // A new child's own /health, once it reported its port.
8
+ healthMs: 60_000,
9
+ // A write waits for another process that holds the lock of a daemon file.
10
+ lockMs: 5_000,
11
+ // A request held while its extension swaps children.
12
+ gateMs: 30_000,
13
+ // A child's answer headers; then 504.
14
+ answerMs: 60_000,
15
+ // One Installer call (POST, PATCH, each entry at boot), and a change queued behind others:
16
+ // above the cli's npm bound (10 min), below its client wait (12 min).
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,
25
+ };
26
+ export const limitsOf = (given) => {
27
+ const keys = Object.keys(LIMITS);
28
+ return Object.fromEntries(keys.map((key) => [key, given[key] ?? LIMITS[key]]));
29
+ };
@@ -1,29 +1,5 @@
1
- import { type Entry, type SupervisorDeps } from './supervisor.js';
2
- export declare const RESERVED_ID = "host";
3
- export type Entries = Map<string, Entry>;
4
- export declare const summary: ({ id, version, state, error, lane }: Entry) => {
5
- error?: string | undefined;
6
- pid?: number | undefined;
7
- id: string;
8
- version: string;
9
- state: import("./supervisor.js").State;
10
- };
11
- export declare const listed: (entry: Entry) => {
12
- source: string;
13
- enabled: boolean;
14
- error?: string | undefined;
15
- pid?: number | undefined;
16
- id: string;
17
- version: string;
18
- state: import("./supervisor.js").State;
19
- };
20
- export declare const addExtension: (deps: SupervisorDeps, entries: Entries, body: unknown) => Promise<{
21
- error?: string | undefined;
22
- pid?: number | undefined;
23
- id: string;
24
- version: string;
25
- state: import("./supervisor.js").State;
26
- }>;
1
+ import { type Entries } from './entries.js';
2
+ import { type SupervisorDeps } from './supervisor.js';
27
3
  export declare const changeExtension: (deps: SupervisorDeps, entries: Entries, id: string, body: unknown) => Promise<{
28
4
  error?: string | undefined;
29
5
  pid?: number | undefined;
@@ -1,82 +1,22 @@
1
- import { isAbsolute } from 'node:path';
1
+ import { isDeepStrictEqual } from 'node:util';
2
2
  import { z } from 'zod';
3
3
  import { fail } from '../../envelope/envelope.js';
4
4
  import { parse } from '../../envelope/parse.js';
5
- import { ExtensionIdSchema, SecretNameSchema } from '../../manifest/primitives.schema.js';
6
- import { readManifest } from '../../manifest/read-manifest.js';
7
- import { purgeData, writeValues } from './daemon-files.js';
5
+ import { SecretNameSchema } from '../../manifest/primitives.schema.js';
6
+ import { clearRunDir, purgeData } from './daemon-files.js';
7
+ import { unmarkReload } from './reload-marker.js';
8
+ import { entryOf, summary } from './entries.js';
9
+ import { unsynced, writeAll } from './write-all.js';
8
10
  import { runInstaller } from './installer-call.js';
9
- import { checkSecrets } from './secret-names.js';
10
- import { coerceSettings } from './setting-values.js';
11
- import { updateInstallation, withEntry } from './installation.js';
12
- import { halt, startEntry, swap, valuesOf, } from './supervisor.js';
13
- export const RESERVED_ID = 'host';
14
- const AddSchema = z.union([
15
- z.strictObject({ id: ExtensionIdSchema, version: z.string().min(1).optional() }),
16
- z.strictObject({ source: z.string().refine(isAbsolute, 'an absolute path') }),
17
- ]);
11
+ import { checkedSettings } from './patch-values.js';
12
+ import {} from './installation.js';
13
+ import { halt, hold, swap, valuesOf, } from './supervisor.js';
18
14
  const PatchSchema = z.strictObject({
19
15
  version: z.string().min(1).optional(),
20
16
  enabled: z.boolean().optional(),
21
17
  settings: z.record(z.string(), z.unknown()).optional(),
22
18
  secrets: z.record(SecretNameSchema, z.string()).optional(),
23
19
  });
24
- // pid of a running child: the e2e teardown reads it.
25
- export const summary = ({ id, version, state, error, lane }) => ({
26
- id,
27
- version,
28
- state,
29
- ...(lane && { pid: lane.child.pid }),
30
- ...(error && { error }),
31
- });
32
- export const listed = (entry) => ({
33
- ...summary(entry),
34
- source: entry.install.source ?? 'market',
35
- enabled: entry.install.enabled !== false,
36
- });
37
- const reserve = (entries, id) => {
38
- if (id === RESERVED_ID)
39
- throw fail('VALIDATION_ERROR', 'the id host is reserved');
40
- if (entries.has(id))
41
- throw fail('CONFLICT', `${id} is installed`);
42
- };
43
- const sourceEntry = async (source) => {
44
- const pkg = await readManifest(source).catch((err) => {
45
- throw fail('VALIDATION_ERROR', `${source}: ${err.message}`);
46
- });
47
- return { install: { id: pkg.agentage.id, source }, dir: source };
48
- };
49
- const marketEntry = async (deps, entries, id, version) => {
50
- reserve(entries, id);
51
- const got = await runInstaller(deps, { id, version });
52
- return { install: { id: got.id, version: got.version }, dir: got.dir };
53
- };
54
- const persist = (deps, id, install) => updateInstallation(deps.configDir, (doc) => withEntry(doc, id, install));
55
- // POST: installs (or links a folder), records it, starts it; a failed start stays listed as failed.
56
- export const addExtension = async (deps, entries, body) => {
57
- const spec = parse(AddSchema, body, 'Invalid body');
58
- const { install, dir } = 'source' in spec
59
- ? await sourceEntry(spec.source)
60
- : await marketEntry(deps, entries, spec.id, spec.version);
61
- reserve(entries, install.id);
62
- const entry = {
63
- id: install.id,
64
- install,
65
- state: 'starting',
66
- version: '',
67
- dir,
68
- };
69
- entries.set(entry.id, entry);
70
- await persist(deps, entry.id, install);
71
- await startEntry(deps, entry);
72
- return summary(entry);
73
- };
74
- const entryOf = (entries, id) => {
75
- const entry = entries.get(id);
76
- if (!entry)
77
- throw fail('NOT_FOUND', `${id} is not installed`);
78
- return entry;
79
- };
80
20
  // The install entry a patch asks for; a new version is installed first and its folder kept aside.
81
21
  const nextInstall = async (deps, entry, patch) => {
82
22
  // enabled absent means true (C3), so only false is written.
@@ -84,65 +24,68 @@ const nextInstall = async (deps, entry, patch) => {
84
24
  delete install.enabled;
85
25
  if ((patch.enabled ?? entry.install.enabled) === false)
86
26
  install.enabled = false;
87
- if (!patch.version)
27
+ if (!patch.version || patch.version === entry.install.version)
88
28
  return { install };
89
29
  if (install.source)
90
30
  throw fail('VALIDATION_ERROR', `${entry.id} runs a folder: it has no version`);
91
31
  const got = await runInstaller(deps, { id: entry.id, version: patch.version });
92
32
  return { install: { ...install, version: got.version }, dir: got.dir };
93
33
  };
34
+ // The change, and the values on disk now: what a failed write puts back.
94
35
  const nextOf = async (deps, entry, patch) => {
95
36
  const next = await nextInstall(deps, entry, patch);
96
37
  const dir = next.dir ?? entry.dir ?? entry.install.source;
97
- await checkSecrets(dir, Object.keys(patch.secrets ?? {}), entry.id);
98
- const given = await coerceSettings(dir, patch.settings ?? {}, entry.id);
38
+ const given = await checkedSettings(dir, patch, entry.id);
99
39
  const was = await valuesOf(deps.configDir, entry.id);
100
40
  const settings = { ...was.settings, ...given };
101
- return { ...next, values: { settings, secrets: { ...was.secrets, ...patch.secrets } } };
41
+ const values = { settings, secrets: { ...was.secrets, ...patch.secrets } };
42
+ return { to: { ...next, values }, was };
102
43
  };
103
- const save = async (deps, entry, to) => {
104
- Object.assign(entry, { install: to.install }, to.dir && { dir: to.dir });
105
- await persist(deps, entry.id, to.install);
106
- await writeValues(deps.configDir, 'settings', entry.id, to.values.settings);
107
- await writeValues(deps.configDir, 'secrets', entry.id, to.values.secrets);
108
- };
109
- // A change that could not be written stops the new child and starts the old one from the files.
110
- const saveOrRestore = async (deps, entry, to, dir) => {
111
- const was = entry.install;
112
- await save(deps, entry, to).catch(async (err) => {
113
- Object.assign(entry, { install: was, dir });
114
- await halt(entry, deps.drainMs);
115
- await startEntry(deps, entry);
116
- throw err;
117
- });
118
- };
119
- // Disabled: stopped. Else one rule, running or not: the swap, then the files; values persist
120
- // only once the new child runs.
121
- const apply = async (deps, entry, to) => {
122
- if (to.install.enabled === false) {
44
+ // Disabled: written, then stopped. Else written, then swapped; a refused start puts the files back.
45
+ const apply = async (deps, entry, to, was) => {
46
+ const back = { install: entry.install, values: was };
47
+ await writeAll(deps, entry.id, to, back);
48
+ const undo = () => writeAll(deps, entry.id, back, to).catch(() => unsynced(deps, entry.id));
49
+ if (to.install.enabled !== false)
50
+ await swap(deps, entry, to, undo);
51
+ else
123
52
  await halt(entry, deps.drainMs);
53
+ Object.assign(entry, { install: to.install }, to.dir && { dir: to.dir });
54
+ if (to.install.enabled === false)
124
55
  entry.state = 'disabled';
125
- return save(deps, entry, to);
56
+ };
57
+ // A request sent once the change is decided waits (gateMs) and goes to the result.
58
+ const held = async (deps, entry, to, was) => {
59
+ const release = hold(entry);
60
+ try {
61
+ await apply(deps, entry, to, was);
62
+ }
63
+ finally {
64
+ release();
126
65
  }
127
- const dir = entry.dir;
128
- await swap(deps, entry, to);
129
- await saveOrRestore(deps, entry, to, dir);
130
66
  };
131
- // PATCH: a refused change keeps the old one and is 400 START_FAILED.
67
+ // Nothing to do: the same files, and the entry already runs (or is stopped) as they say.
68
+ const unchanged = (entry, to, was) => entry.state === (to.install.enabled === false ? 'disabled' : 'running') &&
69
+ (!to.dir || to.dir === entry.dir) &&
70
+ isDeepStrictEqual(to.install, entry.install) &&
71
+ isDeepStrictEqual(to.values, was);
72
+ // PATCH: a refused change keeps the old one and is 400 START_FAILED; a failed entry is started again.
132
73
  export const changeExtension = async (deps, entries, id, body) => {
133
74
  const patch = parse(PatchSchema, body, 'Invalid body');
134
75
  const entry = entryOf(entries, id);
135
- await apply(deps, entry, await nextOf(deps, entry, patch));
76
+ const { to, was } = await nextOf(deps, entry, patch);
77
+ if (!unchanged(entry, to, was))
78
+ await held(deps, entry, to, was);
136
79
  return summary(entry);
137
80
  };
138
- // DELETE: stops the child, forgets its settings and secrets; purge also deletes its data folder.
81
+ // DELETE: the files first (all or none), then the child stops; purge also deletes its data folder.
139
82
  export const removeExtension = async (deps, entries, id, purge) => {
140
83
  const entry = entryOf(entries, id);
84
+ await writeAll(deps, id, {}, { install: entry.install, values: await valuesOf(deps.configDir, id) });
141
85
  entries.delete(id);
142
86
  await halt(entry, deps.drainMs);
143
- await persist(deps, id);
144
- await writeValues(deps.configDir, 'settings', id);
145
- await writeValues(deps.configDir, 'secrets', id);
87
+ await unmarkReload(deps.configDir, id);
88
+ await clearRunDir(deps.configDir, id);
146
89
  if (purge)
147
90
  await purgeData(deps.configDir, id);
148
91
  return { id };
@@ -0,0 +1,6 @@
1
+ interface GivenValues {
2
+ settings?: Record<string, unknown>;
3
+ secrets?: Record<string, string>;
4
+ }
5
+ export declare const checkedSettings: (dir: string | undefined, given: GivenValues, id: string) => Promise<Record<string, unknown>>;
6
+ export {};
@@ -0,0 +1,39 @@
1
+ import { fits } from '../../context/settings.js';
2
+ import { fail } from '../../envelope/envelope.js';
3
+ import {} from '../../manifest/manifest.schema.js';
4
+ import { readManifest } from '../../manifest/read-manifest.js';
5
+ const PARSE = {
6
+ number: (t) => (/^-?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?$/i.test(t) ? Number(t) : t),
7
+ integer: (t) => (/^-?\d+$/.test(t) ? Number(t) : t),
8
+ boolean: (t) => (t === 'true' ? true : t === 'false' ? false : t),
9
+ };
10
+ const refused = (key, message) => fail('VALIDATION_ERROR', `setting ${key}: ${message}`, { code: 'INVALID_SETTING' });
11
+ const valueOf = (key, setting, given) => {
12
+ if (!setting)
13
+ throw refused(key, 'not declared in the manifest');
14
+ const value = typeof given === 'string' ? (PARSE[setting.type]?.(given) ?? given) : given;
15
+ if (!fits(setting, value))
16
+ throw refused(key, `${JSON.stringify(given)} is not a valid ${setting.type}`);
17
+ return value;
18
+ };
19
+ // Only a secret the package declares: the name becomes a file name in the child's folder.
20
+ const checkSecrets = (pkg, names, id) => {
21
+ const known = (pkg.agentage.secrets ?? []).map((s) => (typeof s === 'string' ? s : s.name));
22
+ const unknown = names.filter((name) => !known.includes(name));
23
+ if (unknown.length)
24
+ throw fail('VALIDATION_ERROR', `${id} declares no secret ${unknown.join(', ')}`);
25
+ };
26
+ // The secret names checked, and each setting a client sent as text (`limit=5`) in its declared type.
27
+ export const checkedSettings = async (dir, given, id) => {
28
+ const settings = given.settings ?? {};
29
+ const names = Object.keys(given.secrets ?? {});
30
+ if (!names.length && !Object.keys(settings).length)
31
+ return settings;
32
+ if (!dir)
33
+ throw fail('VALIDATION_ERROR', `${id} has no package yet: install it first`);
34
+ const pkg = await readManifest(dir);
35
+ checkSecrets(pkg, names, id);
36
+ const declared = pkg.agentage.settings ?? {};
37
+ const typed = Object.entries(settings).map(([key, v]) => [key, valueOf(key, declared[key], v)]);
38
+ return Object.fromEntries(typed);
39
+ };
@@ -0,0 +1,15 @@
1
+ export type PendingOp = 'install' | 'update' | 'remove' | 'reload';
2
+ export interface Pending {
3
+ op: PendingOp;
4
+ id?: string;
5
+ source?: string;
6
+ since: string;
7
+ timedOut?: true;
8
+ }
9
+ export declare const pendingChanges: () => {
10
+ track: <T>(change: Omit<Pending, "since">, fn: () => Promise<T>) => Promise<T>;
11
+ linger: (id: string, since: string, work: Promise<unknown>) => void;
12
+ timedOut: (id: string) => Pending | undefined;
13
+ list: () => Pending[];
14
+ };
15
+ export type PendingChanges = ReturnType<typeof pendingChanges>;
@@ -0,0 +1,18 @@
1
+ // The changes taken and not yet answered, queued ones too: /health shows one the client gave up on.
2
+ export const pendingChanges = () => {
3
+ const open = new Set();
4
+ const until = async (row, work) => {
5
+ open.add(row);
6
+ try {
7
+ return await work;
8
+ }
9
+ finally {
10
+ open.delete(row);
11
+ }
12
+ };
13
+ const track = (change, fn) => until({ ...change, since: new Date().toISOString() }, Promise.resolve().then(fn));
14
+ // A timed-out installer call stays listed until it settles.
15
+ const linger = (id, since, work) => void until({ op: 'install', id, since, timedOut: true }, work).catch(() => undefined);
16
+ const timedOut = (id) => [...open].find((row) => row.timedOut && row.id === id);
17
+ return { track, linger, timedOut, list: () => [...open] };
18
+ };
@@ -1,5 +1,6 @@
1
1
  import { type IncomingHttpHeaders } from 'node:http';
2
2
  import { type RequestHandler } from 'express';
3
- import { type Entries } from './ops.js';
3
+ import { type Entries } from './entries.js';
4
+ import { type Limits } from './limits.js';
4
5
  export declare const endToEnd: (headers: IncomingHttpHeaders) => IncomingHttpHeaders;
5
- export declare const proxyTo: (entries: Entries, gateMs?: number) => RequestHandler;
6
+ export declare const proxyTo: (entries: Entries, limits: Pick<Limits, "gateMs" | "answerMs">, hostToken?: string) => RequestHandler;
@@ -1,10 +1,11 @@
1
- import { request } from 'node:http';
1
+ import { request, } from 'node:http';
2
+ import { setTimeout as sleep } from 'node:timers/promises';
2
3
  import {} from 'express';
3
4
  import { fail } from '../../envelope/envelope.js';
5
+ import { carriesHostToken } from './host-token.js';
4
6
  import { enter } from './lane.js';
5
- import {} from './ops.js';
6
- import { GATE_MS } from './supervisor.js';
7
- const waited = (ms) => new Promise((resolve) => setTimeout(resolve, ms).unref());
7
+ import {} from './entries.js';
8
+ import {} from './limits.js';
8
9
  // 404 not installed or disabled (chosen, not to retry); 503 starting, failed, or held past gateMs.
9
10
  const laneFor = async (entries, id, gateMs) => {
10
11
  const entry = entries.get(id);
@@ -13,10 +14,12 @@ const laneFor = async (entries, id, gateMs) => {
13
14
  if (entry.state === 'disabled')
14
15
  throw fail('NOT_FOUND', `${id} is disabled`);
15
16
  if (entry.gate)
16
- await Promise.race([entry.gate, waited(gateMs)]);
17
- if (!entry.lane)
17
+ await Promise.race([entry.gate, sleep(gateMs, undefined, { ref: false })]);
18
+ const lane = entry.lane;
19
+ if (!lane)
18
20
  throw fail('UNAVAILABLE', `${id} is ${entry.state}`, { retryAfter: 5 });
19
- return entry.lane;
21
+ // Counted in the same tick it is read: a swap cannot stop this child before the request is open.
22
+ return { lane, leave: enter(lane) };
20
23
  };
21
24
  const HOP = [
22
25
  'connection',
@@ -36,32 +39,59 @@ export const endToEnd = (headers) => {
36
39
  const drop = new Set([...HOP, ...named.map((h) => h.trim())]);
37
40
  return Object.fromEntries(Object.entries(headers).filter(([key]) => !drop.has(key)));
38
41
  };
39
- const answer = (res) => (up) => {
40
- res.writeHead(up.statusCode ?? 502, endToEnd(up.headers));
41
- up.pipe(res);
42
+ // No answer headers in answerMs: 504 TIMEOUT; the child may still apply the call.
43
+ const noAnswer = (ms) => Object.assign(fail('UNAVAILABLE', `The extension did not answer in ${ms} ms`), {
44
+ code: 'TIMEOUT',
45
+ status: 504,
46
+ retryAfter: undefined,
47
+ });
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) => {
50
+ const headers = endToEnd(req.headers);
51
+ if (hostToken && carriesHostToken(req.headers, hostToken))
52
+ delete headers['authorization'];
53
+ return headers;
42
54
  };
43
- // Streams the request to the child as it came (path and query kept), no pooled connection.
44
- const forward = (req, res, next, lane) => {
45
- const leave = enter(lane);
55
+ const requestTo = (req, lane, hostToken) => {
46
56
  const { method, originalUrl: path } = req;
47
- const headers = endToEnd(req.headers);
57
+ const headers = forChild(req, hostToken);
48
58
  const options = { host: '127.0.0.1', port: lane.child.port, method, path, headers, agent: false };
49
- const upstream = request(options, answer(res));
59
+ return request(options);
60
+ };
61
+ // The child's answer as it streams; an error before its headers is the envelope (504 when late).
62
+ const relay = (upstream, res, next, ms) => {
63
+ let late = false;
64
+ const timer = setTimeout(() => ((late = true), upstream.destroy()), ms);
65
+ upstream.on('response', (up) => {
66
+ clearTimeout(timer);
67
+ res.writeHead(up.statusCode ?? 502, endToEnd(up.headers));
68
+ // A child gone in the middle of its body: the answer is cut, not left open.
69
+ up.once('close', () => void (up.complete || res.destroy()));
70
+ up.pipe(res);
71
+ });
72
+ upstream.on('error', () => {
73
+ if (res.headersSent)
74
+ return void res.destroy();
75
+ next(late ? noAnswer(ms) : fail('UNAVAILABLE', 'The extension did not answer', { retryAfter: 5 }));
76
+ });
77
+ return () => clearTimeout(timer);
78
+ };
79
+ const forward = (req, res, next, { to, ms, hostToken }) => {
80
+ const { lane, leave } = to;
81
+ const upstream = requestTo(req, lane, hostToken);
82
+ const stop = relay(upstream, res, next, ms);
83
+ upstream.on('error', leave);
50
84
  // A client that went away aborts the request to the child too.
51
85
  res.on('close', () => {
86
+ stop();
52
87
  if (!res.writableFinished)
53
88
  upstream.destroy();
54
89
  leave();
55
90
  });
56
- upstream.on('error', () => {
57
- leave();
58
- if (res.headersSent)
59
- return void res.destroy();
60
- next(fail('UNAVAILABLE', 'The extension did not answer', { retryAfter: 5 }));
61
- });
62
91
  req.pipe(upstream);
63
92
  };
64
- export const proxyTo = (entries, gateMs = GATE_MS) => async (req, res, next) => {
65
- const lane = await laneFor(entries, String(req.params['id']), gateMs);
66
- forward(req, res, next, lane);
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 });
67
97
  };
@@ -1,2 +1,3 @@
1
1
  export type Queue = <T>(fn: () => Promise<T>) => Promise<T>;
2
2
  export declare const serialQueue: () => Queue;
3
+ export declare const waitAtMost: <T>(queue: Queue, ms: number, fn: () => Promise<T>) => Promise<T>;