@agentage/extension 0.13.0 → 0.14.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 (93) hide show
  1. package/dist/discovery/discovery.d.ts +1 -0
  2. package/dist/discovery/discovery.schema.d.ts +2 -0
  3. package/dist/discovery/discovery.schema.js +22 -10
  4. package/dist/host/daemon/add.d.ts +9 -0
  5. package/dist/host/daemon/add.js +63 -0
  6. package/dist/host/daemon/child.d.ts +5 -3
  7. package/dist/host/daemon/child.js +21 -13
  8. package/dist/host/daemon/daemon-files.d.ts +3 -5
  9. package/dist/host/daemon/daemon-files.js +15 -11
  10. package/dist/host/daemon/daemon-owner.d.ts +1 -0
  11. package/dist/host/daemon/daemon-owner.js +32 -0
  12. package/dist/host/daemon/daemon.d.ts +2 -3
  13. package/dist/host/daemon/daemon.js +53 -31
  14. package/dist/host/daemon/entries.d.ts +21 -0
  15. package/dist/host/daemon/entries.js +24 -0
  16. package/dist/host/daemon/guard.d.ts +1 -1
  17. package/dist/host/daemon/guard.js +4 -3
  18. package/dist/host/daemon/installation.d.ts +17 -4
  19. package/dist/host/daemon/installation.js +52 -8
  20. package/dist/host/daemon/installer-call.d.ts +16 -2
  21. package/dist/host/daemon/installer-call.js +33 -7
  22. package/dist/host/daemon/json-file.d.ts +3 -2
  23. package/dist/host/daemon/json-file.js +21 -10
  24. package/dist/host/daemon/lane.d.ts +1 -3
  25. package/dist/host/daemon/lane.js +4 -9
  26. package/dist/host/daemon/limits.d.ts +11 -0
  27. package/dist/host/daemon/limits.js +22 -0
  28. package/dist/host/daemon/ops.d.ts +2 -26
  29. package/dist/host/daemon/ops.js +43 -103
  30. package/dist/host/daemon/patch-values.d.ts +6 -0
  31. package/dist/host/daemon/patch-values.js +39 -0
  32. package/dist/host/daemon/pending.d.ts +15 -0
  33. package/dist/host/daemon/pending.js +18 -0
  34. package/dist/host/daemon/proxy.d.ts +3 -2
  35. package/dist/host/daemon/proxy.js +46 -24
  36. package/dist/host/daemon/queue.d.ts +1 -0
  37. package/dist/host/daemon/queue.js +19 -0
  38. package/dist/host/daemon/routes.d.ts +5 -3
  39. package/dist/host/daemon/routes.js +67 -17
  40. package/dist/host/daemon/stopping.d.ts +10 -0
  41. package/dist/host/daemon/stopping.js +28 -0
  42. package/dist/host/daemon/supervisor.d.ts +13 -11
  43. package/dist/host/daemon/supervisor.js +17 -18
  44. package/dist/host/daemon/write-all.d.ts +8 -0
  45. package/dist/host/daemon/write-all.js +45 -0
  46. package/dist/host/data-lock.d.ts +1 -0
  47. package/dist/host/data-lock.js +63 -23
  48. package/dist/host/host-env.d.ts +2 -1
  49. package/dist/host/host-env.js +8 -2
  50. package/dist/host/host-extension.d.ts +4 -0
  51. package/dist/host/host-extension.js +11 -6
  52. package/dist/host/host-store.d.ts +8 -1
  53. package/dist/host/host-store.js +24 -10
  54. package/dist/host/index.d.ts +4 -0
  55. package/dist/host/index.js +4 -0
  56. package/dist/host/serve-host.d.ts +2 -1
  57. package/dist/host/serve-host.js +12 -9
  58. package/dist/server/app.d.ts +2 -1
  59. package/dist/server/app.js +1 -1
  60. package/dist/server/serve.d.ts +3 -0
  61. package/dist/server/serve.js +9 -4
  62. package/dist/tool/build.d.ts +3 -0
  63. package/dist/tool/build.js +42 -27
  64. package/dist/tool/capabilities.d.ts +1 -0
  65. package/dist/tool/capabilities.js +8 -0
  66. package/dist/tool/container-parts.d.ts +7 -0
  67. package/dist/tool/container-parts.js +10 -0
  68. package/dist/tool/container-recipe.d.ts +4 -0
  69. package/dist/tool/container-recipe.js +55 -0
  70. package/dist/tool/container-stage.d.ts +3 -0
  71. package/dist/tool/container-stage.js +51 -0
  72. package/dist/tool/container.d.ts +73 -0
  73. package/dist/tool/container.js +28 -0
  74. package/dist/tool/docker.d.ts +5 -0
  75. package/dist/tool/docker.js +15 -0
  76. package/dist/tool/format.js +12 -5
  77. package/dist/tool/index.d.ts +2 -0
  78. package/dist/tool/index.js +2 -0
  79. package/dist/tool/kit-version.d.ts +1 -0
  80. package/dist/tool/kit-version.js +16 -2
  81. package/dist/tool/labels.d.ts +1 -1
  82. package/dist/tool/labels.js +4 -2
  83. package/dist/tool/main.js +10 -1
  84. package/dist/tool/stage.d.ts +1 -0
  85. package/dist/tool/stage.js +1 -1
  86. package/dist/tool/up/local-record.d.ts +1 -0
  87. package/package.json +1 -1
  88. package/schemas/extension-discovery.schema.json +8 -1
  89. package/schemas/extension-record.schema.json +8 -1
  90. package/dist/host/daemon/secret-names.d.ts +0 -1
  91. package/dist/host/daemon/secret-names.js +0 -14
  92. package/dist/host/daemon/setting-values.d.ts +0 -1
  93. package/dist/host/daemon/setting-values.js +0 -26
@@ -1,7 +1,9 @@
1
1
  import { copyFile } from 'node:fs/promises';
2
2
  import { isAbsolute, join } from 'node:path';
3
3
  import { z } from 'zod';
4
+ import { fail } from '../../envelope/envelope.js';
4
5
  import { ExtensionIdSchema } from '../../manifest/primitives.schema.js';
6
+ import { assertNoOtherDaemon } from './daemon-owner.js';
5
7
  import { readJsonFile, withFileLock, writeJsonFile } from './json-file.js';
6
8
  // One extension in installation.json (C3): a version, or a source folder; other keys round-trip.
7
9
  const InstallEntrySchema = z.looseObject({
@@ -14,28 +16,70 @@ const InstallationSchema = z.looseObject({
14
16
  host: z.string().default('local'),
15
17
  extensions: z.array(z.unknown()),
16
18
  });
17
- export const INSTALLATION_FILE = 'installation.json';
19
+ const INSTALLATION_FILE = 'installation.json';
18
20
  const EMPTY = { host: 'local', extensions: [] };
19
21
  const checked = (raw) => {
20
22
  const top = InstallationSchema.safeParse(raw);
21
23
  if (!top.success)
22
24
  return { doc: EMPTY, invalid: true };
23
25
  const rows = top.data.extensions.map((row) => InstallEntrySchema.safeParse(row));
24
- const extensions = rows.flatMap((row) => (row.success ? [row.data] : []));
26
+ const valid = rows.flatMap((row) => (row.success ? [row.data] : []));
27
+ const extensions = valid.filter((row, at) => valid.findIndex((e) => e.id === row.id) === at);
25
28
  return { doc: { ...top.data, extensions }, invalid: extensions.length < rows.length };
26
29
  };
27
- export const readInstallation = async (configDir) => checked(await readJsonFile(join(configDir, INSTALLATION_FILE), EMPTY).catch(() => null));
30
+ // At boot the daemon has no rows from it, so a fix needs a restart; later a fix is enough.
31
+ const unreadable = (why, atBoot = false) => fail('CONFLICT', `${INSTALLATION_FILE} cannot be read (${why}): fix it${atBoot ? ', then restart the daemon' : ''}; no change is written`, { code: 'INSTALLATION_UNREADABLE', details: { reason: why } });
32
+ const reasonOf = (err) => err instanceof SyntaxError
33
+ ? 'not JSON'
34
+ : String(err.code ?? err.message);
35
+ // Not readable (EACCES, EISDIR): thrown.
36
+ const rawOf = (configDir, notJson = 'empty') => readJsonFile(join(configDir, INSTALLATION_FILE), EMPTY).catch((err) => {
37
+ if (err instanceof SyntaxError && notJson === 'empty')
38
+ return null;
39
+ throw err;
40
+ });
41
+ const readInstallation = async (configDir, notJson) => checked(await rawOf(configDir, notJson).catch((err) => {
42
+ throw unreadable(reasonOf(err));
43
+ }));
44
+ // At boot an unreadable file gives no rows and its reason; the daemon then refuses every change.
45
+ export const bootInstallation = (configDir) => rawOf(configDir).then((raw) => checked(raw), (err) => ({ doc: EMPTY, invalid: false, unreadable: reasonOf(err) }));
46
+ // A change is refused when the file was unreadable at boot (why) or is unreadable now.
47
+ export const assertReadable = async (configDir, why) => {
48
+ if (why)
49
+ throw unreadable(why, true);
50
+ await readInstallation(configDir, 'refuse');
51
+ };
28
52
  // A bad file is kept as installation.json.bad before the daemon writes the valid rows over it.
29
53
  export const keepBadCopy = (configDir) => copyFile(join(configDir, INSTALLATION_FILE), join(configDir, `${INSTALLATION_FILE}.bad`));
30
- // Read, change and write under the lock: the daemon is the only writer.
31
- export const updateInstallation = (configDir, change) => {
54
+ // Only rows C3 accepts are written, and each id once.
55
+ const checkedDoc = (next) => {
56
+ const ids = next.extensions.map((row) => row.id);
57
+ const bad = next.extensions.find((row) => !InstallEntrySchema.safeParse(row).success);
58
+ if (bad || new Set(ids).size < ids.length || !InstallationSchema.safeParse(next).success)
59
+ throw fail('VALIDATION_ERROR', `${INSTALLATION_FILE}: a row C3 refuses, or an id twice`);
60
+ return next;
61
+ };
62
+ const changeInstallation = (notJson) => async (configDir, change, waitMs) => {
63
+ await assertNoOtherDaemon(configDir);
32
64
  const file = join(configDir, INSTALLATION_FILE);
33
- return withFileLock(file, async () => {
34
- const next = change((await readInstallation(configDir)).doc);
65
+ const write = async () => {
66
+ const read = await readInstallation(configDir, notJson);
67
+ if (read.invalid)
68
+ await keepBadCopy(configDir);
69
+ const next = checkedDoc(change(read.doc));
35
70
  await writeJsonFile(file, next);
36
71
  return next;
37
- });
72
+ };
73
+ return withFileLock(file, write, waitMs);
38
74
  };
75
+ /**
76
+ * Read, change and write installation.json under the kit's lock, the path the daemon uses.
77
+ * Only while no daemon runs on configDir (it reads the file at its start and owns it after):
78
+ * a live daemon named by daemon.json is refused, unless this is that daemon's process.
79
+ */
80
+ export const updateInstallation = changeInstallation('empty');
81
+ // The daemon after its boot: its rows are in the file, so a file that is not JSON is never replaced.
82
+ export const persistInstallation = changeInstallation('refuse');
39
83
  // The entry of id replaced (or added), the order kept; undefined removes it.
40
84
  export const withEntry = (doc, id, entry) => {
41
85
  const at = doc.extensions.findIndex((e) => e.id === id);
@@ -1,7 +1,21 @@
1
- import { type Installer, type SupervisorDeps } from './supervisor.js';
1
+ import { type InstallSpec, type SupervisorDeps } from './supervisor.js';
2
2
  export declare const NO_INSTALLER = "this daemon has no installer: install a folder with { source }";
3
- export declare const runInstaller: (deps: SupervisorDeps, spec: Parameters<Installer>[0]) => Promise<{
3
+ declare const BASE: {
4
+ readonly 400: "VALIDATION_ERROR";
5
+ readonly 404: "NOT_FOUND";
6
+ readonly 409: "CONFLICT";
7
+ readonly 501: "UNAVAILABLE";
8
+ readonly 502: "UNAVAILABLE";
9
+ readonly 504: "UNAVAILABLE";
10
+ };
11
+ export declare const answer: (status: keyof typeof BASE, message: string, code?: string, details?: Record<string, unknown>) => import("../../envelope/envelope.js").Failure & {
12
+ code: string;
13
+ status: 400 | 404 | 409 | 501 | 502 | 504;
14
+ retryAfter: undefined;
15
+ };
16
+ export declare const runInstaller: (deps: SupervisorDeps, spec: Omit<InstallSpec, "signal">) => Promise<{
4
17
  id: string;
5
18
  version: string;
6
19
  dir: string;
7
20
  }>;
21
+ export {};
@@ -1,22 +1,48 @@
1
+ import { setTimeout as sleep } from 'node:timers/promises';
1
2
  import { fail } from '../../envelope/envelope.js';
2
3
  import {} from './supervisor.js';
3
4
  export const NO_INSTALLER = 'this daemon has no installer: install a folder with { source }';
4
- // 501 as C5 says, in the envelope; the closed code set has no NOT_IMPLEMENTED.
5
- const noInstaller = () => Object.assign(fail('UNAVAILABLE', NO_INSTALLER), { status: 501, retryAfter: undefined });
6
- const BASE = { 400: 'VALIDATION_ERROR', 404: 'NOT_FOUND', 502: 'UNAVAILABLE' };
5
+ const BASE = {
6
+ 400: 'VALIDATION_ERROR',
7
+ 404: 'NOT_FOUND',
8
+ 409: 'CONFLICT',
9
+ 501: 'UNAVAILABLE',
10
+ 502: 'UNAVAILABLE',
11
+ 504: 'UNAVAILABLE',
12
+ };
13
+ // The envelope with a status or a code the closed set has not (501, 504, the installer's own code).
14
+ export const answer = (status, message, code = BASE[status], details) => Object.assign(fail(BASE[status], message, { details }), { code, status, retryAfter: undefined });
7
15
  // An installer error with a string code is the client's envelope; any other stays a 500.
8
16
  const answerOf = (err) => {
9
17
  const { code, status, message } = (err ?? {});
10
18
  if (typeof code !== 'string' || !code)
11
19
  return err;
12
20
  const at = status === 404 || status === 502 ? status : 400;
13
- const failure = fail(BASE[at], typeof message === 'string' && message ? message : code);
14
- return Object.assign(failure, { code, status: at, retryAfter: undefined });
21
+ return answer(at, typeof message === 'string' && message ? message : code, code);
22
+ };
23
+ // A second call while a timed-out one of that id still runs would overlap it.
24
+ const notTwice = (deps, id) => {
25
+ const row = deps.pending.timedOut(id);
26
+ if (row)
27
+ throw answer(409, `the installer of ${id} still runs`, 'CONFLICT', { ...row });
15
28
  };
29
+ // At most installMs, then 504 TIMEOUT; only then the signal asks the installer to stop.
16
30
  export const runInstaller = async (deps, spec) => {
17
31
  if (!deps.install)
18
- throw noInstaller();
19
- return deps.install(spec).catch((err) => {
32
+ throw answer(501, NO_INSTALLER);
33
+ notTwice(deps, spec.id);
34
+ const since = new Date().toISOString();
35
+ const stop = new AbortController();
36
+ const timer = new AbortController();
37
+ const call = deps.install({ ...spec, signal: stop.signal });
38
+ const late = sleep(deps.installMs, undefined, { ref: false, signal: timer.signal }).then(() => {
39
+ stop.abort();
40
+ deps.pending.linger(spec.id, since, call);
41
+ throw answer(504, `the installer did not answer in ${deps.installMs} ms`, 'TIMEOUT');
42
+ });
43
+ late.catch(() => undefined);
44
+ const answered = call.catch((err) => {
20
45
  throw answerOf(err);
21
46
  });
47
+ return Promise.race([answered, late]).finally(() => timer.abort());
22
48
  };
@@ -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,11 @@
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
+ };
10
+ export type Limits = typeof LIMITS;
11
+ export declare const limitsOf: (given: Partial<Limits>) => Limits;
@@ -0,0 +1,22 @@
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
+ };
19
+ export const limitsOf = (given) => {
20
+ const keys = Object.keys(LIMITS);
21
+ return Object.fromEntries(keys.map((key) => [key, given[key] ?? LIMITS[key]]));
22
+ };
@@ -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,21 @@
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 { purgeData } from './daemon-files.js';
7
+ import { entryOf, summary } from './entries.js';
8
+ import { unsynced, writeAll } from './write-all.js';
8
9
  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
- ]);
10
+ import { checkedSettings } from './patch-values.js';
11
+ import {} from './installation.js';
12
+ import { halt, hold, swap, valuesOf, } from './supervisor.js';
18
13
  const PatchSchema = z.strictObject({
19
14
  version: z.string().min(1).optional(),
20
15
  enabled: z.boolean().optional(),
21
16
  settings: z.record(z.string(), z.unknown()).optional(),
22
17
  secrets: z.record(SecretNameSchema, z.string()).optional(),
23
18
  });
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
19
  // The install entry a patch asks for; a new version is installed first and its folder kept aside.
81
20
  const nextInstall = async (deps, entry, patch) => {
82
21
  // enabled absent means true (C3), so only false is written.
@@ -84,65 +23,66 @@ const nextInstall = async (deps, entry, patch) => {
84
23
  delete install.enabled;
85
24
  if ((patch.enabled ?? entry.install.enabled) === false)
86
25
  install.enabled = false;
87
- if (!patch.version)
26
+ if (!patch.version || patch.version === entry.install.version)
88
27
  return { install };
89
28
  if (install.source)
90
29
  throw fail('VALIDATION_ERROR', `${entry.id} runs a folder: it has no version`);
91
30
  const got = await runInstaller(deps, { id: entry.id, version: patch.version });
92
31
  return { install: { ...install, version: got.version }, dir: got.dir };
93
32
  };
33
+ // The change, and the values on disk now: what a failed write puts back.
94
34
  const nextOf = async (deps, entry, patch) => {
95
35
  const next = await nextInstall(deps, entry, patch);
96
36
  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);
37
+ const given = await checkedSettings(dir, patch, entry.id);
99
38
  const was = await valuesOf(deps.configDir, entry.id);
100
39
  const settings = { ...was.settings, ...given };
101
- return { ...next, values: { settings, secrets: { ...was.secrets, ...patch.secrets } } };
40
+ const values = { settings, secrets: { ...was.secrets, ...patch.secrets } };
41
+ return { to: { ...next, values }, was };
102
42
  };
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) {
43
+ // Disabled: written, then stopped. Else written, then swapped; a refused start puts the files back.
44
+ const apply = async (deps, entry, to, was) => {
45
+ const back = { install: entry.install, values: was };
46
+ await writeAll(deps, entry.id, to, back);
47
+ const undo = () => writeAll(deps, entry.id, back, to).catch(() => unsynced(deps, entry.id));
48
+ if (to.install.enabled !== false)
49
+ await swap(deps, entry, to, undo);
50
+ else
123
51
  await halt(entry, deps.drainMs);
52
+ Object.assign(entry, { install: to.install }, to.dir && { dir: to.dir });
53
+ if (to.install.enabled === false)
124
54
  entry.state = 'disabled';
125
- return save(deps, entry, to);
55
+ };
56
+ // A request sent once the change is decided waits (gateMs) and goes to the result.
57
+ const held = async (deps, entry, to, was) => {
58
+ const release = hold(entry);
59
+ try {
60
+ await apply(deps, entry, to, was);
61
+ }
62
+ finally {
63
+ release();
126
64
  }
127
- const dir = entry.dir;
128
- await swap(deps, entry, to);
129
- await saveOrRestore(deps, entry, to, dir);
130
65
  };
131
- // PATCH: a refused change keeps the old one and is 400 START_FAILED.
66
+ // Nothing to do: the same files, and the entry already runs (or is stopped) as they say.
67
+ const unchanged = (entry, to, was) => entry.state === (to.install.enabled === false ? 'disabled' : 'running') &&
68
+ (!to.dir || to.dir === entry.dir) &&
69
+ isDeepStrictEqual(to.install, entry.install) &&
70
+ isDeepStrictEqual(to.values, was);
71
+ // PATCH: a refused change keeps the old one and is 400 START_FAILED; a failed entry is started again.
132
72
  export const changeExtension = async (deps, entries, id, body) => {
133
73
  const patch = parse(PatchSchema, body, 'Invalid body');
134
74
  const entry = entryOf(entries, id);
135
- await apply(deps, entry, await nextOf(deps, entry, patch));
75
+ const { to, was } = await nextOf(deps, entry, patch);
76
+ if (!unchanged(entry, to, was))
77
+ await held(deps, entry, to, was);
136
78
  return summary(entry);
137
79
  };
138
- // DELETE: stops the child, forgets its settings and secrets; purge also deletes its data folder.
80
+ // DELETE: the files first (all or none), then the child stops; purge also deletes its data folder.
139
81
  export const removeExtension = async (deps, entries, id, purge) => {
140
82
  const entry = entryOf(entries, id);
83
+ await writeAll(deps, id, {}, { install: entry.install, values: await valuesOf(deps.configDir, id) });
141
84
  entries.delete(id);
142
85
  await halt(entry, deps.drainMs);
143
- await persist(deps, id);
144
- await writeValues(deps.configDir, 'settings', id);
145
- await writeValues(deps.configDir, 'secrets', id);
146
86
  if (purge)
147
87
  await purgeData(deps.configDir, id);
148
88
  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';
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">) => RequestHandler;