@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
@@ -47,6 +47,7 @@ export declare const discoveryDocument: (record: ExtensionRecord, host: string)
47
47
  };
48
48
  secrets?: string[] | undefined;
49
49
  secretParts?: Record<string, ("pages" | "api" | "mcp" | "worker")[]> | undefined;
50
+ image?: string | undefined;
50
51
  openapi?: string | undefined;
51
52
  tools?: {
52
53
  name: string;
@@ -43,6 +43,7 @@ export declare const ExtensionRecordSchema: z.ZodObject<{
43
43
  migrations: z.ZodOptional<z.ZodInt>;
44
44
  }, z.core.$strict>>;
45
45
  }, z.core.$strict>;
46
+ image: z.ZodOptional<z.ZodString>;
46
47
  openapi: z.ZodOptional<z.ZodString>;
47
48
  tools: z.ZodOptional<z.ZodArray<z.ZodObject<{
48
49
  name: z.ZodString;
@@ -87,6 +88,7 @@ export declare const DiscoveryDocumentSchema: z.ZodObject<{
87
88
  migrations: z.ZodOptional<z.ZodInt>;
88
89
  }, z.core.$strict>>;
89
90
  }, z.core.$strict>;
91
+ image: z.ZodOptional<z.ZodString>;
90
92
  openapi: z.ZodOptional<z.ZodString>;
91
93
  tools: z.ZodOptional<z.ZodArray<z.ZodObject<{
92
94
  name: z.ZodString;
@@ -6,8 +6,12 @@ const ImageDigestRefSchema = z
6
6
  .max(256)
7
7
  .regex(/^[a-z0-9][a-z0-9.-]*(:[0-9]{1,5})?\/[a-z0-9][a-z0-9-]*\/[a-z][a-z0-9-]*-(pages|ui|api|mcp|worker)@sha256:[0-9a-f]{64}$/);
8
8
  const PartImageSchema = z.strictObject({ image: ImageDigestRefSchema });
9
- const PartsRecordSchema = z
10
- .strictObject({
9
+ // The one image: registry host[:port]/owner[/team...]/{id}@sha256.
10
+ const OneImageRefSchema = z
11
+ .string()
12
+ .max(256)
13
+ .regex(/^[a-z0-9][a-z0-9.-]*(:[0-9]{1,5})?(\/[a-z0-9][a-z0-9_.-]*)+\/[a-z][a-z0-9-]*@sha256:[0-9a-f]{64}$/);
14
+ const PartsRecordSchema = z.strictObject({
11
15
  pages: PartImageSchema.optional(),
12
16
  ui: PartImageSchema.optional(),
13
17
  api: PartImageSchema.optional(),
@@ -16,9 +20,6 @@ const PartsRecordSchema = z
16
20
  store: z
17
21
  .strictObject({ kind: StoreKindSchema, migrations: z.int().min(0).optional() })
18
22
  .optional(),
19
- })
20
- .refine((parts) => IMAGE_PART_KINDS.some((kind) => parts[kind] !== undefined), {
21
- message: 'at least one part with an image',
22
23
  });
23
24
  export const OriginSchema = z
24
25
  .string()
@@ -39,20 +40,29 @@ const recordShape = {
39
40
  commit: CommitSchema,
40
41
  buildTime: z.iso.datetime(),
41
42
  parts: PartsRecordSchema,
43
+ image: OneImageRefSchema.optional().describe('The one image (build --container). A record has part images or this image: never both, never none.'),
42
44
  // /api/v{N}: an extension still on a kit before 0.13, read by a newer one; it goes in phase 4.
43
45
  openapi: z
44
46
  .string()
45
47
  .regex(/^\/api\/(?:v[0-9]+|[a-z][a-z0-9-]*)\/openapi\.json$/)
48
+ .describe('/api/{id}/openapi.json, or the old /api/v{N}; only the kit checks that {id} is the id')
46
49
  .optional(),
47
50
  tools: z.array(ToolRecordSchema).min(1).optional(),
48
51
  widgets: z.array(WidgetSchema).min(1).optional(),
49
52
  commands: z.array(CommandNameSchema).min(1).optional(),
50
53
  };
51
- const imagesNameTheirExtension = (doc) => IMAGE_PART_KINDS.every((kind) => {
52
- const image = doc.parts[kind]?.image;
53
- return image === undefined || image.includes(`/${doc.id}-${kind}@sha256:`);
54
- });
55
- const IMAGE_RULE = { message: 'every image is {id}-{part}', path: ['parts'] };
54
+ const imagesNameTheirExtension = (doc) => (!doc.image || doc.image.includes(`/${doc.id}@sha256:`)) &&
55
+ IMAGE_PART_KINDS.every((kind) => {
56
+ const image = doc.parts[kind]?.image;
57
+ return image === undefined || image.includes(`/${doc.id}-${kind}@sha256:`);
58
+ });
59
+ const IMAGE_RULE = { message: 'every image is {id}-{part}, the one image {id}', path: ['parts'] };
60
+ // One image per part, or the one image of every part (build --container): never both, never none.
61
+ const oneImageForm = (doc) => IMAGE_PART_KINDS.some((kind) => doc.parts[kind] !== undefined) !== Boolean(doc.image);
62
+ const FORM_RULE = {
63
+ message: 'at least one part with an image, or the one image and no part image',
64
+ path: ['parts'],
65
+ };
56
66
  // The api prefix is /api/{id}, or the old /api/v{N}: never another extension's id.
57
67
  const openapiNamesItsExtension = ({ id, openapi }) => !openapi || /^\/api\/v[0-9]+\//.test(openapi) || openapi === `/api/${id}/openapi.json`;
58
68
  const OPENAPI_RULE = { message: 'openapi is /api/{id}/openapi.json', path: ['openapi'] };
@@ -66,6 +76,7 @@ export const ExtensionRecordSchema = z
66
76
  secrets: z.array(SecretNameSchema).min(1).optional(),
67
77
  secretParts: z.record(SecretNameSchema, z.array(SecretPartSchema)).optional(),
68
78
  })
79
+ .refine(oneImageForm, FORM_RULE)
69
80
  .refine(imagesNameTheirExtension, IMAGE_RULE)
70
81
  .refine(openapiNamesItsExtension, OPENAPI_RULE)
71
82
  .superRefine((doc, ctx) => {
@@ -76,5 +87,6 @@ export const ExtensionRecordSchema = z
76
87
  // What a deployment serves at /.well-known/agentage-extension.json: the record plus its host.
77
88
  export const DiscoveryDocumentSchema = z
78
89
  .strictObject({ ...recordShape, host: OriginSchema })
90
+ .refine(oneImageForm, FORM_RULE)
79
91
  .refine(imagesNameTheirExtension, IMAGE_RULE)
80
92
  .refine(openapiNamesItsExtension, OPENAPI_RULE);
@@ -0,0 +1,9 @@
1
+ import { type Entries } from './entries.js';
2
+ import { type SupervisorDeps } from './supervisor.js';
3
+ export declare const addExtension: (deps: SupervisorDeps, entries: Entries, body: unknown) => Promise<{
4
+ error?: string | undefined;
5
+ pid?: number | undefined;
6
+ id: string;
7
+ version: string;
8
+ state: import("./supervisor.js").State;
9
+ }>;
@@ -0,0 +1,63 @@
1
+ import { isAbsolute } from 'node:path';
2
+ import { z } from 'zod';
3
+ import { fail } from '../../envelope/envelope.js';
4
+ import { parse } from '../../envelope/parse.js';
5
+ import { ExtensionIdSchema } from '../../manifest/primitives.schema.js';
6
+ import { readManifest } from '../../manifest/read-manifest.js';
7
+ import { persist, summary } from './entries.js';
8
+ import { runInstaller } from './installer-call.js';
9
+ import {} from './installation.js';
10
+ import { startEntry } from './supervisor.js';
11
+ const RESERVED_ID = 'host';
12
+ // enabled: false records the extension and never starts it (a profile "off" entry).
13
+ const AddSchema = z.union([
14
+ z.strictObject({
15
+ id: ExtensionIdSchema,
16
+ version: z.string().min(1).optional(),
17
+ enabled: z.boolean().optional(),
18
+ }),
19
+ z.strictObject({
20
+ source: z.string().refine(isAbsolute, 'an absolute path'),
21
+ enabled: z.boolean().optional(),
22
+ }),
23
+ ]);
24
+ // The entry a 409 names, so a client can tell a repeat from another package of that id.
25
+ const existing = ({ id, version, install }) => ({
26
+ id,
27
+ ...(version ? { version } : {}),
28
+ ...(install.source ? { source: install.source } : {}),
29
+ });
30
+ const reserve = (entries, id) => {
31
+ if (id === RESERVED_ID)
32
+ throw fail('VALIDATION_ERROR', 'the id host is reserved');
33
+ const has = entries.get(id);
34
+ if (has)
35
+ throw fail('CONFLICT', `${id} is installed`, { details: existing(has) });
36
+ };
37
+ const sourceEntry = async (source) => {
38
+ const pkg = await readManifest(source).catch((err) => {
39
+ throw fail('VALIDATION_ERROR', `${source}: ${err.message}`);
40
+ });
41
+ return { install: { id: pkg.agentage.id, source }, dir: source, version: pkg.version };
42
+ };
43
+ const marketEntry = async (deps, entries, id, version) => {
44
+ reserve(entries, id);
45
+ const got = await runInstaller(deps, { id, version });
46
+ return { install: { id: got.id, version: got.version }, dir: got.dir, version: got.version };
47
+ };
48
+ // POST: installs (or links a folder), records it, then starts it; a failed start stays listed as failed.
49
+ export const addExtension = async (deps, entries, body) => {
50
+ const spec = parse(AddSchema, body, 'Invalid body');
51
+ const got = 'source' in spec
52
+ ? await sourceEntry(spec.source)
53
+ : await marketEntry(deps, entries, spec.id, spec.version);
54
+ reserve(entries, got.install.id);
55
+ const off = spec.enabled === false;
56
+ const install = off ? { ...got.install, enabled: false } : got.install;
57
+ await persist(deps, install.id, install);
58
+ const entry = { ...got, id: install.id, install, state: 'disabled' };
59
+ entries.set(entry.id, entry);
60
+ if (!off)
61
+ await startEntry(deps, entry);
62
+ return summary(entry);
63
+ };
@@ -1,10 +1,11 @@
1
- export interface LaunchSpec {
1
+ interface LaunchSpec {
2
2
  id: string;
3
3
  dir: string;
4
4
  dataDir: string;
5
5
  settings: Record<string, unknown>;
6
6
  secrets: Record<string, string>;
7
7
  origin: string;
8
+ storeOpenMs?: number;
8
9
  }
9
10
  export interface Exit {
10
11
  code: number | null;
@@ -17,5 +18,6 @@ export interface Child {
17
18
  stop(): Promise<void>;
18
19
  }
19
20
  export type Launch = (spec: LaunchSpec) => Promise<Child>;
20
- export declare const HOST_MAIN: string;
21
- export declare const forkLaunch: (main?: string) => Launch;
21
+ export declare const childEnv: (spec: LaunchSpec, secretsDir: string) => Record<string, string>;
22
+ export declare const forkLaunch: (main?: string, startMs?: number) => Launch;
23
+ export {};
@@ -4,8 +4,8 @@ import { tmpdir } from 'node:os';
4
4
  import { join } from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
6
  import { SecretNameSchema } from '../../manifest/primitives.schema.js';
7
- export const HOST_MAIN = fileURLToPath(new URL('../main.js', import.meta.url));
8
- const START_MS = 60_000;
7
+ import { LIMITS } from './limits.js';
8
+ const HOST_MAIN = fileURLToPath(new URL('../main.js', import.meta.url));
9
9
  const STOP_MS = 5_000;
10
10
  const PASSED = ['PATH', 'HOME', 'TMPDIR', 'LANG', 'NODE_EXTRA_CA_CERTS'];
11
11
  // Handed over as 0600 files in a 0700 folder, removed once the child has read them.
@@ -15,17 +15,19 @@ const secretFiles = async (spec) => {
15
15
  await writeFile(join(dir, SecretNameSchema.parse(name)), value, { mode: 0o600 });
16
16
  return dir;
17
17
  };
18
- const envOf = (spec, secretsDir) => ({
19
- ...Object.fromEntries(PASSED.flatMap((k) => (process.env[k] ? [[k, process.env[k]]] : []))),
18
+ // What dist/host/main.js reads (docs/part-image.md), on a port the OS picks.
19
+ export const childEnv = (spec, secretsDir) => ({
20
20
  PORT: '0',
21
21
  AGENTAGE_EXTENSION_DIR: spec.dir,
22
22
  AGENTAGE_DATA_DIR: spec.dataDir,
23
23
  AGENTAGE_SETTINGS: JSON.stringify(spec.settings),
24
24
  AGENTAGE_SECRETS_DIR: secretsDir,
25
25
  AGENTAGE_ORIGIN: spec.origin,
26
+ ...(spec.storeOpenMs && { AGENTAGE_STORE_OPEN_MS: String(spec.storeOpenMs) }),
26
27
  });
28
+ const passedEnv = () => Object.fromEntries(PASSED.flatMap((k) => (process.env[k] ? [[k, process.env[k]]] : [])));
27
29
  // The child's last stderr line, its msg when it is a log row: why it did not start.
28
- const lastWords = (tail, code) => {
30
+ const lastWords = (tail, how) => {
29
31
  const lines = tail
30
32
  .trim()
31
33
  .split('\n')
@@ -36,7 +38,7 @@ const lastWords = (tail, code) => {
36
38
  return msg.replace(/^[A-Za-z]*Error: /, '');
37
39
  }
38
40
  catch {
39
- return line || `exited with code ${code}`;
41
+ return line || `exited with ${how.signal ? `signal ${how.signal}` : `code ${how.code}`}`;
40
42
  }
41
43
  };
42
44
  const captured = (child) => {
@@ -52,9 +54,10 @@ const portOf = (msg) => {
52
54
  const { type, port } = (msg ?? {});
53
55
  return type === 'ready' && typeof port === 'number' ? port : undefined;
54
56
  };
55
- // The port the child bound, or why it exited first; a child silent for START_MS is killed.
56
- const readyOf = (child, tail) => new Promise((resolve, reject) => {
57
- const timer = setTimeout(() => child.kill('SIGKILL'), START_MS);
57
+ // The port the child bound, or why it exited first; a child silent for startMs is killed.
58
+ const readyOf = (child, tail, startMs) => new Promise((resolve, reject) => {
59
+ let killed = false;
60
+ const timer = setTimeout(() => ((killed = true), child.kill('SIGKILL')), startMs);
58
61
  const settle = (fn) => {
59
62
  clearTimeout(timer);
60
63
  fn();
@@ -64,7 +67,12 @@ const readyOf = (child, tail) => new Promise((resolve, reject) => {
64
67
  if (port)
65
68
  settle(() => resolve(port));
66
69
  });
67
- child.once('exit', (code) => settle(() => reject(new Error(lastWords(tail(), code)))));
70
+ child.once('exit', (code, signal) => {
71
+ const why = killed
72
+ ? `reported no port in ${startMs} ms: killed`
73
+ : lastWords(tail(), { code, signal });
74
+ settle(() => reject(new Error(why)));
75
+ });
68
76
  });
69
77
  // SIGTERM drains; a child still there after STOP_MS (a request that never ends) gets SIGKILL.
70
78
  const stopOf = (child, exited) => async () => {
@@ -75,15 +83,15 @@ const stopOf = (child, exited) => async () => {
75
83
  clearTimeout(kill);
76
84
  };
77
85
  // One child process per extension: node dist/host/main.js on a port the OS picks.
78
- export const forkLaunch = (main = HOST_MAIN) => async (spec) => {
86
+ export const forkLaunch = (main = HOST_MAIN, startMs = LIMITS.startMs) => async (spec) => {
79
87
  const secretsDir = await secretFiles(spec);
80
88
  const stdio = ['ignore', 'pipe', 'pipe', 'ipc'];
81
89
  // execArgv []: the daemon's own node flags (a loader, --input-type) are not the child's.
82
- const env = envOf(spec, secretsDir);
90
+ const env = { ...passedEnv(), ...childEnv(spec, secretsDir) };
83
91
  const child = fork(main, [], { env, execArgv: [], stdio: [...stdio] });
84
92
  const exited = new Promise((resolve) => child.once('exit', (code, signal) => resolve({ code, signal })));
85
93
  try {
86
- const port = await readyOf(child, captured(child));
94
+ const port = await readyOf(child, captured(child), startMs);
87
95
  return { port, pid: child.pid ?? 0, exited, stop: stopOf(child, exited) };
88
96
  }
89
97
  finally {
@@ -1,6 +1,5 @@
1
- export declare const DAEMON_FILE = "daemon.json";
2
1
  export declare const DAEMON_PROTOCOL = 1;
3
- export interface DaemonFile {
2
+ interface DaemonFile {
4
3
  pid: number;
5
4
  port: number;
6
5
  version: string;
@@ -11,9 +10,8 @@ export declare const writeDaemonFile: (configDir: string, file: DaemonFile) => P
11
10
  export declare const removeDaemonFile: (configDir: string) => Promise<void>;
12
11
  export declare const dataDirOf: (configDir: string, id: string) => string;
13
12
  export declare const purgeData: (configDir: string, id: string) => Promise<void>;
14
- export type ValueKind = 'settings' | 'secrets';
13
+ type ValueKind = 'settings' | 'secrets';
15
14
  type Values = Record<string, unknown>;
16
15
  export declare const readValues: (configDir: string, kind: ValueKind, id: string) => Promise<Values>;
17
- export declare const writeValues: (configDir: string, kind: ValueKind, id: string, values?: Values) => Promise<void>;
18
- export declare const ensureConfigDir: (configDir: string) => Promise<string | undefined>;
16
+ export declare const writeValues: (configDir: string, kind: ValueKind, id: string, values?: Values, waitMs?: number) => Promise<void>;
19
17
  export {};
@@ -1,7 +1,7 @@
1
- import { mkdir, rm, unlink } from 'node:fs/promises';
1
+ import { rm, unlink } from 'node:fs/promises';
2
2
  import { join } from 'node:path';
3
3
  import { readJsonFile, withFileLock, writeJsonFile } from './json-file.js';
4
- export const DAEMON_FILE = 'daemon.json';
4
+ const DAEMON_FILE = 'daemon.json';
5
5
  export const DAEMON_PROTOCOL = 1;
6
6
  export const writeDaemonFile = (configDir, file) => writeJsonFile(join(configDir, DAEMON_FILE), file);
7
7
  export const removeDaemonFile = (configDir) => unlink(join(configDir, DAEMON_FILE)).catch(() => undefined);
@@ -9,15 +9,19 @@ export const dataDirOf = (configDir, id) => join(configDir, 'data', id);
9
9
  export const purgeData = (configDir, id) => rm(dataDirOf(configDir, id), { recursive: true, force: true });
10
10
  const fileOf = (configDir, kind) => join(configDir, `${kind}.json`);
11
11
  export const readValues = async (configDir, kind, id) => (await readJsonFile(fileOf(configDir, kind), {}))[id] ?? {};
12
- export const writeValues = (configDir, kind, id, values) => {
12
+ // The rows of one file changed under its lock; the same object back writes nothing.
13
+ const changeValues = (configDir, kind, change, waitMs) => {
13
14
  const file = fileOf(configDir, kind);
14
- return withFileLock(file, async () => {
15
+ const write = async () => {
15
16
  const all = await readJsonFile(file, {});
16
- if (values)
17
- all[id] = values;
18
- else
19
- delete all[id];
20
- await writeJsonFile(file, all, kind === 'secrets' ? 0o600 : 0o644);
21
- });
17
+ const next = change(all);
18
+ if (next !== all)
19
+ await writeJsonFile(file, next, kind === 'secrets' ? 0o600 : 0o644);
20
+ };
21
+ return withFileLock(file, write, waitMs);
22
22
  };
23
- export const ensureConfigDir = (configDir) => mkdir(configDir, { recursive: true });
23
+ export const writeValues = (configDir, kind, id, values, waitMs) => changeValues(configDir, kind, (all) => {
24
+ const rest = { ...all };
25
+ delete rest[id];
26
+ return values ? { ...rest, [id]: values } : rest;
27
+ }, waitMs);
@@ -0,0 +1 @@
1
+ export declare const assertNoOtherDaemon: (configDir: string) => Promise<void>;
@@ -0,0 +1,32 @@
1
+ import { join } from 'node:path';
2
+ import { fail } from '../../envelope/envelope.js';
3
+ import { readJsonFile } from './json-file.js';
4
+ const alive = (pid) => {
5
+ try {
6
+ return process.kill(pid, 0);
7
+ }
8
+ catch (err) {
9
+ return err.code === 'EPERM';
10
+ }
11
+ };
12
+ // A daemon.json of a dead or other process is stale: only one that answers as that daemon counts.
13
+ const answersAsDaemon = async (port, pid) => {
14
+ const res = await fetch(`http://127.0.0.1:${port}/health`, {
15
+ signal: AbortSignal.timeout(1_000),
16
+ });
17
+ const body = (await res.json());
18
+ return body.service === 'agentage-daemon' && body.pid === pid;
19
+ };
20
+ // installation.json belongs to the daemon that runs on configDir; its own process may write it.
21
+ export const assertNoOtherDaemon = async (configDir) => {
22
+ const file = await readJsonFile(join(configDir, 'daemon.json'), null).catch(() => null);
23
+ const { pid, port } = file ?? {};
24
+ if (!pid || !port || pid === process.pid || !alive(pid))
25
+ return;
26
+ if (!(await answersAsDaemon(port, pid).catch(() => false)))
27
+ return;
28
+ throw fail('CONFLICT', `a daemon (process ${pid}) runs on ${configDir}: change it through it`, {
29
+ code: 'DAEMON_RUNNING',
30
+ details: { pid, port },
31
+ });
32
+ };
@@ -1,13 +1,12 @@
1
1
  import { type Launch } from './child.js';
2
+ import { type Limits } from './limits.js';
2
3
  import { type Installer } from './supervisor.js';
3
- export interface DaemonOptions {
4
+ export interface DaemonOptions extends Partial<Limits> {
4
5
  configDir: string;
5
6
  port?: number;
6
7
  install?: Installer;
7
8
  version: string;
8
9
  startedBy: string;
9
- drainMs?: number;
10
- healthMs?: number;
11
10
  }
12
11
  export interface Daemon {
13
12
  port: number;
@@ -1,42 +1,59 @@
1
+ import { mkdir } from 'node:fs/promises';
1
2
  import {} from 'node:http';
2
3
  import {} from 'node:net';
3
4
  import { createLog } from '../../log/log.js';
4
- import { listen } from '../../server/serve.js';
5
+ import { closeNow, listen } from '../../server/serve.js';
5
6
  import { forkLaunch } from './child.js';
6
- import { ensureConfigDir, removeDaemonFile, writeDaemonFile, DAEMON_PROTOCOL, } from './daemon-files.js';
7
- import { keepBadCopy, readInstallation } from './installation.js';
8
- import {} from './ops.js';
7
+ import { removeDaemonFile, writeDaemonFile, DAEMON_PROTOCOL } from './daemon-files.js';
8
+ import { assertNoOtherDaemon } from './daemon-owner.js';
9
+ import { bootInstallation, updateInstallation } from './installation.js';
10
+ import {} from './entries.js';
11
+ import { limitsOf } from './limits.js';
12
+ import { pendingChanges } from './pending.js';
9
13
  import { serialQueue } from './queue.js';
14
+ import { launchUnlessStopping, stopAll, stoppingOf } from './stopping.js';
10
15
  import { daemonApp } from './routes.js';
11
- import { DRAIN_MS, HEALTH_MS, halt, startEntry, } from './supervisor.js';
16
+ import { runInstaller } from './installer-call.js';
17
+ import { halt, startEntry } from './supervisor.js';
12
18
  export const DAEMON_PORT = 4243;
13
- // The valid rows of installation.json; a bad file is kept aside and reported in /health.
14
- const loadEntries = async (configDir) => {
15
- const { doc, invalid } = await readInstallation(configDir);
19
+ const warnOf = (deps) => (err) => deps.log.warn('a daemon file was not cleaned at boot', { reason: err.message });
20
+ // The valid rows of installation.json; a bad file is kept aside, replaced by them, and in /health.
21
+ const loadEntries = async (deps) => {
22
+ const { doc, invalid, unreadable } = await bootInstallation(deps.configDir);
16
23
  if (invalid)
17
- await keepBadCopy(configDir).catch(() => undefined);
24
+ await updateInstallation(deps.configDir, () => doc, deps.lockMs).catch(warnOf(deps));
18
25
  const entries = new Map();
19
26
  for (const install of doc.extensions) {
20
27
  const state = install.enabled === false ? 'disabled' : 'starting';
21
28
  entries.set(install.id, { id: install.id, install, state, version: install.version ?? '' });
22
29
  }
23
- return { entries, invalid };
30
+ return { entries, invalid, unreadable };
24
31
  };
25
- // One at a time, so the installer is never called twice at once; a failed one stops no other.
32
+ // A disabled entry gets its folder (configure and enable work); a failure is kept as its error.
33
+ const resolveDir = async (deps, entry) => {
34
+ const { id, install } = entry;
35
+ if (install.source)
36
+ return void (entry.dir = install.source);
37
+ await runInstaller(deps, { id, version: install.version }).then((got) => void Object.assign(entry, { dir: got.dir, version: got.version, error: undefined }), (err) => void (entry.error = err.message));
38
+ };
39
+ // Enabled folders first (no installer), then enabled versions one at a time, disabled ones last.
26
40
  const boot = async (deps, entries) => {
27
- for (const entry of entries.values())
28
- if (entry.state === 'starting')
29
- await startEntry(deps, entry);
41
+ const all = [...entries.values()];
42
+ const off = all.filter((e) => e.state === 'disabled');
43
+ const on = all.filter((e) => e.state !== 'disabled');
44
+ const ordered = [...on.filter((e) => e.install.source), ...on.filter((e) => !e.install.source)];
45
+ for (const entry of ordered)
46
+ await startEntry(deps, entry);
47
+ for (const entry of off)
48
+ await resolveDir(deps, entry);
30
49
  };
31
- const close = (server) => new Promise((resolve) => {
32
- server.close(() => resolve());
33
- server.closeAllConnections();
34
- });
35
- const stopper = (server, entries, deps) => {
50
+ const stopper = (server, entries, deps, life) => {
36
51
  let stopped;
37
52
  const stop = async () => {
53
+ life.abort();
38
54
  await Promise.all([...entries.values()].map((entry) => halt(entry, deps.drainMs)));
39
- await close(server);
55
+ await stopAll(deps.stopping);
56
+ await closeNow(server);
40
57
  await removeDaemonFile(deps.configDir);
41
58
  };
42
59
  return () => (stopped ??= stop());
@@ -49,27 +66,32 @@ const announce = ({ configDir, version, startedBy }, port) => writeDaemonFile(co
49
66
  protocol: DAEMON_PROTOCOL,
50
67
  startedBy,
51
68
  });
52
- const depsOf = (opts, launch, origin) => ({
69
+ const depsOf = (opts, launch, origin, stopping) => ({
53
70
  configDir: opts.configDir,
54
- launch,
71
+ launch: launchUnlessStopping(stopping, launch),
72
+ stopping,
55
73
  install: opts.install,
56
74
  log: createLog({ extension: 'host', part: 'api', version: opts.version }),
57
75
  origin,
58
- drainMs: opts.drainMs ?? DRAIN_MS,
59
- healthMs: opts.healthMs ?? HEALTH_MS,
76
+ ...limitsOf(opts),
60
77
  queue: serialQueue(),
78
+ pending: pendingChanges(),
79
+ unsynced: new Set(),
61
80
  });
62
- // Read and check the file, listen, write daemon.json, start the children; a failed boot undoes it.
81
+ // No other daemon, read and check the file, listen, write daemon.json, start the children; a failed boot undoes it.
63
82
  export const startDaemon = async (opts, launch) => {
64
- await ensureConfigDir(opts.configDir);
83
+ await mkdir(opts.configDir, { recursive: true });
84
+ // A live daemon owns the folder: a second one fails before it writes any file there.
85
+ await assertNoOtherDaemon(opts.configDir);
65
86
  let port = opts.port ?? DAEMON_PORT;
66
- const deps = depsOf(opts, launch, () => `http://127.0.0.1:${port}`);
67
- const { entries, invalid } = await loadEntries(opts.configDir);
68
- const info = { version: opts.version, pid: process.pid, protocol: DAEMON_PROTOCOL, invalid };
87
+ const life = new AbortController();
88
+ const deps = depsOf(opts, launch, () => `http://127.0.0.1:${port}`, stoppingOf(life.signal));
89
+ const { entries, ...file } = await loadEntries(deps);
90
+ const info = { version: opts.version, pid: process.pid, protocol: DAEMON_PROTOCOL, ...file };
69
91
  const app = daemonApp(deps, entries, () => port, info);
70
92
  const server = await listen(app, port, '127.0.0.1');
71
93
  port = server.address().port;
72
- const stop = stopper(server, entries, deps);
94
+ const stop = stopper(server, entries, deps, life);
73
95
  try {
74
96
  await announce(opts, port);
75
97
  await deps.queue(() => boot(deps, entries));
@@ -81,4 +103,4 @@ export const startDaemon = async (opts, launch) => {
81
103
  return { port, stop };
82
104
  };
83
105
  // One daemon on 127.0.0.1, one child process for each extension (D1).
84
- export const createDaemon = (opts) => startDaemon(opts, forkLaunch());
106
+ export const createDaemon = (opts) => startDaemon(opts, forkLaunch(undefined, opts.startMs));
@@ -0,0 +1,21 @@
1
+ import { type InstallEntry } from './installation.js';
2
+ import { type Entry, type SupervisorDeps } from './supervisor.js';
3
+ export type Entries = Map<string, Entry>;
4
+ export declare const summary: ({ id, version, state, error, lane }: Entry) => {
5
+ error?: string | undefined;
6
+ pid?: number | undefined;
7
+ id: string;
8
+ version: string;
9
+ state: import("./supervisor.js").State;
10
+ };
11
+ export declare const listed: (entry: Entry) => {
12
+ source: string;
13
+ enabled: boolean;
14
+ error?: string | undefined;
15
+ pid?: number | undefined;
16
+ id: string;
17
+ version: string;
18
+ state: import("./supervisor.js").State;
19
+ };
20
+ export declare const entryOf: (entries: Entries, id: string) => Entry;
21
+ export declare const persist: (deps: SupervisorDeps, id: string, install?: InstallEntry) => Promise<import("./installation.js").Installation>;
@@ -0,0 +1,24 @@
1
+ import { fail } from '../../envelope/envelope.js';
2
+ import { persistInstallation, withEntry } from './installation.js';
3
+ import {} from './supervisor.js';
4
+ // pid of a running child: the e2e teardown reads it.
5
+ export const summary = ({ id, version, state, error, lane }) => ({
6
+ id,
7
+ version,
8
+ state,
9
+ ...(lane && { pid: lane.child.pid }),
10
+ ...(error && { error }),
11
+ });
12
+ export const listed = (entry) => ({
13
+ ...summary(entry),
14
+ source: entry.install.source ?? 'market',
15
+ enabled: entry.install.enabled !== false,
16
+ });
17
+ export const entryOf = (entries, id) => {
18
+ const entry = entries.get(id);
19
+ if (!entry)
20
+ throw fail('NOT_FOUND', `${id} is not installed`);
21
+ return entry;
22
+ };
23
+ // The entry of id in installation.json replaced, added, or (no install) removed.
24
+ export const persist = (deps, id, install) => persistInstallation(deps.configDir, (doc) => withEntry(doc, id, install), deps.lockMs);
@@ -1,2 +1,2 @@
1
1
  import { type RequestHandler } from 'express';
2
- export declare const localOnly: (port: () => number) => RequestHandler;
2
+ export declare const localOnly: (port?: () => number) => RequestHandler;
@@ -2,14 +2,15 @@ import {} from 'express';
2
2
  import { fail } from '../../envelope/envelope.js';
3
3
  // What a browser says of a request another site started (an <img>, a link, a form).
4
4
  const FOREIGN = ['cross-site', 'same-site'];
5
- // Only this machine, by name: a page elsewhere (DNS rebinding, a cross-site form or GET) gets 403.
5
+ // Only this machine by name (DNS rebinding, a cross-site form): no port given, the socket's own.
6
6
  export const localOnly = (port) => (req, _res, next) => {
7
- const hosts = [`127.0.0.1:${port()}`, `localhost:${port()}`];
7
+ const at = port?.() ?? req.socket.localPort;
8
+ const hosts = [`127.0.0.1:${at}`, `localhost:${at}`];
8
9
  const origin = req.get('origin');
9
10
  const hostOk = hosts.includes(req.get('host') ?? '');
10
11
  const originOk = origin === undefined || hosts.some((host) => origin === `http://${host}`);
11
12
  const siteOk = !FOREIGN.includes(req.get('sec-fetch-site') ?? '');
12
13
  if (!hostOk || !originOk || !siteOk)
13
- throw fail('FORBIDDEN', 'Only this machine may call the daemon');
14
+ throw fail('FORBIDDEN', 'Only this machine may call this server');
14
15
  next();
15
16
  };
@@ -11,13 +11,26 @@ export interface Installation {
11
11
  extensions: InstallEntry[];
12
12
  [key: string]: unknown;
13
13
  }
14
- export interface CheckedInstallation {
14
+ interface CheckedInstallation {
15
15
  doc: Installation;
16
16
  invalid: boolean;
17
17
  }
18
- export declare const INSTALLATION_FILE = "installation.json";
19
- export declare const readInstallation: (configDir: string) => Promise<CheckedInstallation>;
18
+ export declare const bootInstallation: (configDir: string) => Promise<{
19
+ doc: Installation;
20
+ invalid: boolean;
21
+ unreadable: string;
22
+ } | (CheckedInstallation & {
23
+ unreadable?: string;
24
+ })>;
25
+ export declare const assertReadable: (configDir: string, why?: string) => Promise<void>;
20
26
  export declare const keepBadCopy: (configDir: string) => Promise<void>;
21
- export declare const updateInstallation: (configDir: string, change: (doc: Installation) => Installation) => Promise<Installation>;
27
+ type Change = (doc: Installation) => Installation;
28
+ /**
29
+ * Read, change and write installation.json under the kit's lock, the path the daemon uses.
30
+ * Only while no daemon runs on configDir (it reads the file at its start and owns it after):
31
+ * a live daemon named by daemon.json is refused, unless this is that daemon's process.
32
+ */
33
+ export declare const updateInstallation: (configDir: string, change: Change, waitMs?: number) => Promise<Installation>;
34
+ export declare const persistInstallation: (configDir: string, change: Change, waitMs?: number) => Promise<Installation>;
22
35
  export declare const withEntry: (doc: Installation, id: string, entry?: InstallEntry) => Installation;
23
36
  export {};