@agentage/extension 0.12.2 → 0.13.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 (96) hide show
  1. package/README.md +5 -0
  2. package/dist/api/openapi-doc.js +2 -1
  3. package/dist/api/routes.js +1 -1
  4. package/dist/context/context.d.ts +1 -0
  5. package/dist/context/context.js +3 -3
  6. package/dist/context/package-extension.d.ts +2 -0
  7. package/dist/context/package-extension.js +5 -4
  8. package/dist/context/secrets.d.ts +5 -2
  9. package/dist/context/secrets.js +22 -6
  10. package/dist/context/settings.d.ts +4 -0
  11. package/dist/context/settings.js +6 -5
  12. package/dist/context/test-context.js +3 -2
  13. package/dist/discovery/discovery.d.ts +1 -0
  14. package/dist/discovery/discovery.js +7 -3
  15. package/dist/discovery/discovery.schema.d.ts +6 -0
  16. package/dist/discovery/discovery.schema.js +23 -6
  17. package/dist/discovery/openapi.d.ts +2 -1
  18. package/dist/discovery/openapi.js +3 -1
  19. package/dist/host/daemon/child.d.ts +21 -0
  20. package/dist/host/daemon/child.js +92 -0
  21. package/dist/host/daemon/daemon-files.d.ts +19 -0
  22. package/dist/host/daemon/daemon-files.js +23 -0
  23. package/dist/host/daemon/daemon.d.ts +18 -0
  24. package/dist/host/daemon/daemon.js +84 -0
  25. package/dist/host/daemon/guard.d.ts +2 -0
  26. package/dist/host/daemon/guard.js +15 -0
  27. package/dist/host/daemon/installation.d.ts +23 -0
  28. package/dist/host/daemon/installation.js +48 -0
  29. package/dist/host/daemon/installer-call.d.ts +7 -0
  30. package/dist/host/daemon/installer-call.js +22 -0
  31. package/dist/host/daemon/json-file.d.ts +3 -0
  32. package/dist/host/daemon/json-file.js +51 -0
  33. package/dist/host/daemon/lane.d.ts +11 -0
  34. package/dist/host/daemon/lane.js +29 -0
  35. package/dist/host/daemon/ops.d.ts +36 -0
  36. package/dist/host/daemon/ops.js +149 -0
  37. package/dist/host/daemon/proxy.d.ts +5 -0
  38. package/dist/host/daemon/proxy.js +67 -0
  39. package/dist/host/daemon/queue.d.ts +2 -0
  40. package/dist/host/daemon/queue.js +8 -0
  41. package/dist/host/daemon/routes.d.ts +11 -0
  42. package/dist/host/daemon/routes.js +48 -0
  43. package/dist/host/daemon/secret-names.d.ts +1 -0
  44. package/dist/host/daemon/secret-names.js +14 -0
  45. package/dist/host/daemon/setting-values.d.ts +1 -0
  46. package/dist/host/daemon/setting-values.js +26 -0
  47. package/dist/host/daemon/supervisor.d.ts +52 -0
  48. package/dist/host/daemon/supervisor.js +116 -0
  49. package/dist/host/data-lock.d.ts +2 -0
  50. package/dist/host/data-lock.js +81 -0
  51. package/dist/host/host-env.d.ts +17 -0
  52. package/dist/host/host-env.js +36 -0
  53. package/dist/host/host-extension.d.ts +25 -0
  54. package/dist/host/host-extension.js +86 -0
  55. package/dist/host/host-store.d.ts +4 -0
  56. package/dist/host/host-store.js +35 -0
  57. package/dist/host/index.d.ts +3 -0
  58. package/dist/host/index.js +3 -0
  59. package/dist/host/main.d.ts +2 -0
  60. package/dist/host/main.js +10 -0
  61. package/dist/host/serve-host.d.ts +16 -0
  62. package/dist/host/serve-host.js +61 -0
  63. package/dist/manifest/manifest.schema.d.ts +9 -1
  64. package/dist/manifest/manifest.schema.js +13 -2
  65. package/dist/manifest/parts.d.ts +6 -0
  66. package/dist/manifest/parts.js +8 -0
  67. package/dist/manifest/primitives.schema.d.ts +7 -0
  68. package/dist/manifest/primitives.schema.js +2 -0
  69. package/dist/runtime/part-runners.d.ts +1 -0
  70. package/dist/runtime/part-runners.js +10 -1
  71. package/dist/runtime/run-part.js +3 -2
  72. package/dist/server/app.d.ts +4 -0
  73. package/dist/server/app.js +28 -18
  74. package/dist/server/request-line.d.ts +1 -1
  75. package/dist/server/request-line.js +4 -4
  76. package/dist/server/serve.js +11 -3
  77. package/dist/store/pglite-store.d.ts +25 -0
  78. package/dist/store/pglite-store.js +59 -0
  79. package/dist/store/test-store.d.ts +2 -3
  80. package/dist/store/test-store.js +3 -38
  81. package/dist/testing/test-server.d.ts +2 -0
  82. package/dist/testing/test-server.js +1 -1
  83. package/dist/tool/record-extras.js +2 -2
  84. package/dist/tool/rules/surface.js +6 -6
  85. package/dist/tool/up/compose.js +3 -2
  86. package/dist/tool/up/gateway.d.ts +6 -2
  87. package/dist/tool/up/gateway.js +10 -7
  88. package/dist/tool/up/local-record.d.ts +1 -0
  89. package/dist/tool/up/secrets.js +2 -1
  90. package/dist/tool/up/token.js +1 -1
  91. package/dist/tool/up/up.js +2 -2
  92. package/dist/vendor/logs/events-client.js +1 -1
  93. package/package.json +5 -1
  94. package/schemas/extension-discovery.schema.json +1 -1
  95. package/schemas/extension-package.schema.json +35 -3
  96. package/schemas/extension-record.schema.json +21 -1
package/README.md CHANGED
@@ -27,5 +27,10 @@ false); `file` and `line` are there only when a problem has them:
27
27
  }
28
28
  ```
29
29
 
30
+ Secrets: `agentage.secrets` lists names, never values. A plain name is mounted in every part
31
+ but ui; `{ "name": "github-app-key", "parts": ["worker"] }` only in the parts it names. Any
32
+ other part starts without it, and a read of `ctx.secrets.githubAppKey` there throws. A test
33
+ takes a part's view with `createTestContext({ extension: { part: 'worker' } })`.
34
+
30
35
  See the [platform README](https://github.com/agentage/platform#readme) for every part kind, the
31
36
  manifest, the tool and how a part image runs.
@@ -1,4 +1,5 @@
1
1
  import { scopeOf } from '../auth/token-check.js';
2
+ import { apiPrefix } from '../discovery/openapi.js';
2
3
  import {} from '../envelope/codes.js';
3
4
  import { ErrorEnvelopeSchema } from '../envelope/envelope.schema.js';
4
5
  import {} from '../manifest/manifest.schema.js';
@@ -94,7 +95,7 @@ export const generatedOpenapi = (pkg, routes) => {
94
95
  const { id } = pkg.agentage;
95
96
  const paths = {};
96
97
  for (const entry of routes) {
97
- const at = `/api/v1${entry.path}`;
98
+ const at = `${apiPrefix(id)}${entry.path}`;
98
99
  paths[at] = { ...paths[at], [entry.method]: operation(id, entry) };
99
100
  }
100
101
  return {
@@ -9,7 +9,7 @@ const problemOf = (routes, { method, path, spec }) => {
9
9
  if (!ROUTE_METHODS.includes(method))
10
10
  return `method ${String(method)}: one of get, post, put, patch, delete`;
11
11
  if (!PATH.test(path))
12
- return 'path: /segments and {param} segments under /api/v1';
12
+ return 'path: /segments and {param} segments under /api/{id}';
13
13
  if (routes.some((r) => r.method === method && r.path === path))
14
14
  return 'is registered twice';
15
15
  if (!spec.summary)
@@ -50,5 +50,6 @@ export interface ContextInput {
50
50
  secrets?: Secrets;
51
51
  platform?: PlatformInfo;
52
52
  checks?: Record<string, HealthCheck>;
53
+ onExit?: () => void;
53
54
  }
54
55
  export declare const createContext: (input: ContextInput) => PartContext;
@@ -15,12 +15,12 @@ export const healthRegistrar = (checks) => (name, check) => {
15
15
  checks[name] = check;
16
16
  };
17
17
  // Inside a request: after its answer (server/request-line.ts); outside one: now.
18
- const exitAfterAnswer = () => {
18
+ const exitAfterAnswer = (onExit = sigtermOnce) => () => {
19
19
  const scope = requestScope.getStore();
20
20
  if (scope)
21
21
  scope.exit = true;
22
22
  else
23
- sigtermOnce();
23
+ onExit();
24
24
  };
25
25
  // ctx.store is always there; without a store part in the manifest it says so on first use.
26
26
  export const NO_STORE = {
@@ -55,7 +55,7 @@ export const createContext = (input) => {
55
55
  store: store ?? NO_STORE,
56
56
  secrets,
57
57
  platform,
58
- exit: exitAfterAnswer,
58
+ exit: exitAfterAnswer(input.onExit),
59
59
  health: healthRegistrar(input.checks ?? {}),
60
60
  });
61
61
  };
@@ -1,2 +1,4 @@
1
+ import { type ExtensionPackage } from '../manifest/manifest.schema.js';
1
2
  import { type ExtensionInfo } from './context.js';
3
+ export declare const packageManifest: (dir?: string) => ExtensionPackage | undefined;
2
4
  export declare const packageExtension: (dir?: string) => Partial<ExtensionInfo>;
@@ -12,11 +12,12 @@ const readJson = (file) => {
12
12
  }
13
13
  };
14
14
  // The id, version and store kind of the package a test runs in; nothing outside an extension.
15
+ export const packageManifest = (dir = process.cwd()) => PackageSchema.safeParse(readJson(join(dir, 'package.json'))).data;
15
16
  export const packageExtension = (dir = process.cwd()) => {
16
- const parsed = PackageSchema.safeParse(readJson(join(dir, 'package.json')));
17
- if (!parsed.success)
17
+ const pkg = packageManifest(dir);
18
+ if (!pkg)
18
19
  return {};
19
- const { version, agentage } = parsed.data;
20
- const store = storeOf(parsed.data);
20
+ const { version, agentage } = pkg;
21
+ const store = storeOf(pkg);
21
22
  return { id: agentage.id, version, ...(store && { store }) };
22
23
  };
@@ -1,5 +1,8 @@
1
+ import { type ExtensionPackage } from '../manifest/manifest.schema.js';
2
+ import { type ImagePartKind as Part } from '../manifest/primitives.schema.js';
1
3
  export interface Secrets {
2
4
  }
3
5
  export declare const SECRETS_DIR = "/run/secrets";
4
- export declare const camelName: (name: string) => string;
5
- export declare const readSecrets: (names: readonly string[], dir: string, part: string) => Promise<Readonly<Record<string, string>>>;
6
+ export declare const secretsFrom: (pkg: ExtensionPackage, part: Part, value: (name: string) => Promise<string>) => Promise<Readonly<Record<string, string>>>;
7
+ export declare const readSecrets: (pkg: ExtensionPackage, part: Part, dir: string) => Promise<Readonly<Record<string, string>>>;
8
+ export declare const withAbsent: (values: Record<string, string>, part: Part, pkg?: ExtensionPackage) => Record<string, string>;
@@ -1,21 +1,37 @@
1
1
  import { readFile } from 'node:fs/promises';
2
2
  import { join } from 'node:path';
3
+ import {} from '../manifest/manifest.schema.js';
4
+ import { mountedIn, unmountedIn } from '../manifest/parts.js';
5
+ import { camelName } from '../manifest/primitives.schema.js';
3
6
  export const SECRETS_DIR = '/run/secrets';
4
- export const camelName = (name) => name.replace(/-([a-z0-9])/g, (_, c) => c.toUpperCase());
5
7
  // Only a missing file reads as no value; any other error stops the part with its code.
6
8
  const valueOf = (file, refused) => readFile(file, 'utf8').then((text) => text.replace(/\r?\n$/, ''), (err) => {
7
9
  if (err.code === 'ENOENT')
8
10
  return '';
9
11
  throw new Error(`${refused} cannot be read: ${err.code ?? 'unknown'}`);
10
12
  });
11
- // Each declared name from its mounted file; a missing or empty file stops the part, named, never valued.
12
- export const readSecrets = async (names, dir, part) => {
13
- const refused = (name) => `${part} refused to start: secret ${name}`;
14
- const read = names.map(async (name) => [name, await valueOf(join(dir, name), refused(name))]);
13
+ const refusal = (part) => (name) => `${part} refused to start: secret ${name}`;
14
+ // Each name the part mounts, from value(name); an empty value stops the part, named, never valued.
15
+ export const secretsFrom = async (pkg, part, value) => {
16
+ const refused = refusal(part);
17
+ const read = mountedIn(pkg, part).map(async (name) => [name, await value(name)]);
15
18
  const pairs = await Promise.all(read);
16
19
  const missing = pairs.find(([, value]) => value === '');
17
20
  if (missing)
18
21
  throw new Error(`${refused(missing[0])} has no value`);
19
22
  const secrets = Object.fromEntries(pairs.map(([name, value]) => [camelName(name), value]));
20
- return Object.freeze(secrets);
23
+ return Object.freeze(withAbsent(secrets, part, pkg));
24
+ };
25
+ // Each declared name from its mounted file; a missing or empty file stops the part, named, never valued.
26
+ export const readSecrets = (pkg, part, dir) => secretsFrom(pkg, part, (name) => valueOf(join(dir, name), refusal(part)(name)));
27
+ // A secret of other parts throws on read, never reads empty; spread and keys skip it.
28
+ export const withAbsent = (values, part, pkg) => {
29
+ for (const name of unmountedIn(pkg, part))
30
+ Object.defineProperty(values, camelName(name), {
31
+ enumerable: false,
32
+ get: () => {
33
+ throw new Error(`secret ${name} is not mounted in ${part}`);
34
+ },
35
+ });
36
+ return values;
21
37
  };
@@ -2,4 +2,8 @@ import { type Log } from '../log/log.js';
2
2
  import { type ExtensionPackage } from '../manifest/manifest.schema.js';
3
3
  import { type Env } from '../runtime/build-info.js';
4
4
  import { type SettingValue } from './context.js';
5
+ export type Setting = NonNullable<ExtensionPackage['agentage']['settings']>[string];
6
+ export declare const fits: (setting: Setting, value: unknown) => value is SettingValue;
7
+ export declare const parseObject: (text: string) => Record<string, unknown>;
8
+ export declare const settingsOf: (pkg: ExtensionPackage, given: Record<string, unknown>, log: Log) => Record<string, SettingValue>;
5
9
  export declare const settingsFromEnv: (pkg: ExtensionPackage, env: Env, log: Log) => Record<string, SettingValue>;
@@ -2,22 +2,21 @@ import {} from '../log/log.js';
2
2
  import {} from '../manifest/manifest.schema.js';
3
3
  import {} from '../runtime/build-info.js';
4
4
  import { settingDefaults } from './context.js';
5
- const fits = (setting, value) => {
5
+ export const fits = (setting, value) => {
6
6
  if (setting.type === 'integer' ? !Number.isInteger(value) : typeof value !== setting.type)
7
7
  return false;
8
8
  return !setting.enum || setting.enum.includes(String(value));
9
9
  };
10
- const parseObject = (text) => {
10
+ export const parseObject = (text) => {
11
11
  const value = JSON.parse(text);
12
12
  if (typeof value !== 'object' || value === null || Array.isArray(value)) {
13
13
  throw new Error('AGENTAGE_SETTINGS is not a JSON object');
14
14
  }
15
15
  return value;
16
16
  };
17
- // The host's values (AGENTAGE_SETTINGS, JSON) over the defaults; a wrong type stops the start.
18
- export const settingsFromEnv = (pkg, env, log) => {
17
+ // The host's values over the defaults; a wrong type stops the start.
18
+ export const settingsOf = (pkg, given, log) => {
19
19
  const declared = pkg.agentage.settings ?? {};
20
- const given = env['AGENTAGE_SETTINGS'] ? parseObject(env['AGENTAGE_SETTINGS']) : {};
21
20
  const values = settingDefaults(pkg);
22
21
  for (const [key, value] of Object.entries(given)) {
23
22
  const setting = declared[key];
@@ -30,3 +29,5 @@ export const settingsFromEnv = (pkg, env, log) => {
30
29
  }
31
30
  return values;
32
31
  };
32
+ // The values as AGENTAGE_SETTINGS (JSON) of the image gives them.
33
+ export const settingsFromEnv = (pkg, env, log) => settingsOf(pkg, env['AGENTAGE_SETTINGS'] ? parseObject(env['AGENTAGE_SETTINGS']) : {}, log);
@@ -11,7 +11,8 @@ import { memoryRuns } from '../worker/runs.js';
11
11
  import { createScheduler } from '../worker/scheduler.js';
12
12
  import {} from '../manifest/primitives.schema.js';
13
13
  import { NO_PLATFORM, healthRegistrar, NO_STORE, } from './context.js';
14
- import { packageExtension } from './package-extension.js';
14
+ import { packageExtension, packageManifest } from './package-extension.js';
15
+ import { withAbsent } from './secrets.js';
15
16
  import { recordingLog } from './recording-log.js';
16
17
  import { commandContext, } from './test-command-context.js';
17
18
  export {} from './recording-log.js';
@@ -73,7 +74,7 @@ const serverContext = (options) => {
73
74
  spans,
74
75
  settings: { ...options.settings },
75
76
  store: store ?? NO_STORE,
76
- secrets: Object.freeze({ ...options.secrets }),
77
+ secrets: Object.freeze(withAbsent({ ...options.secrets }, extension.part, packageManifest())),
77
78
  platform: Object.freeze({ ...(options.platform ?? NO_PLATFORM) }),
78
79
  exits,
79
80
  exit: () => void exits.push(Date.now()),
@@ -46,6 +46,7 @@ export declare const discoveryDocument: (record: ExtensionRecord, host: string)
46
46
  } | undefined;
47
47
  };
48
48
  secrets?: string[] | undefined;
49
+ secretParts?: Record<string, ("pages" | "api" | "mcp" | "worker")[]> | undefined;
49
50
  openapi?: string | undefined;
50
51
  tools?: {
51
52
  name: string;
@@ -1,6 +1,6 @@
1
1
  import { formatIssues, readJsonIfExists } from '../manifest/read-manifest.js';
2
2
  import {} from '../manifest/manifest.schema.js';
3
- import { normalizeParts } from '../manifest/parts.js';
3
+ import { normalizeParts, scopedSecrets } from '../manifest/parts.js';
4
4
  import {} from '../manifest/primitives.schema.js';
5
5
  import { ExtensionRecordSchema } from './discovery.schema.js';
6
6
  export const DEFAULT_RECORD_FILE = '/run/agentage/agentage-extension.json';
@@ -15,7 +15,8 @@ const partsOf = (pkg, images, migrations) => {
15
15
  };
16
16
  // From the manifest, the build, the images by digest and what the code serves.
17
17
  export const recordOf = (pkg, build, images, extras = {}) => {
18
- const { id, commands, secrets } = pkg.agentage;
18
+ const { id, commands } = pkg.agentage;
19
+ const secrets = (pkg.agentage.secrets ?? []).filter((s) => typeof s === 'string');
19
20
  const { commit, buildTime } = build;
20
21
  const parts = partsOf(pkg, images, extras.migrations);
21
22
  const record = { id, version: pkg.version, commit, buildTime, parts };
@@ -27,8 +28,10 @@ export const recordOf = (pkg, build, images, extras = {}) => {
27
28
  record.commands = commands.map((command) => command.name);
28
29
  if (extras.widgets)
29
30
  record.widgets = extras.widgets;
30
- if (secrets?.length)
31
+ if (secrets.length)
31
32
  record.secrets = secrets;
33
+ if (Object.keys(scopedSecrets(pkg)).length)
34
+ record.secretParts = scopedSecrets(pkg);
32
35
  return record;
33
36
  };
34
37
  export const validateRecord = (value) => {
@@ -45,5 +48,6 @@ export const loadRecord = async (file) => {
45
48
  export const discoveryDocument = (record, host) => {
46
49
  const { id, version, commit, buildTime, ...rest } = record;
47
50
  delete rest.secrets;
51
+ delete rest.secretParts;
48
52
  return { id, version, commit, buildTime, host, ...rest };
49
53
  };
@@ -7,6 +7,12 @@ export declare const WidgetSchema: z.ZodObject<{
7
7
  }, z.core.$strict>;
8
8
  export declare const ExtensionRecordSchema: z.ZodObject<{
9
9
  secrets: z.ZodOptional<z.ZodArray<z.ZodString>>;
10
+ secretParts: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodArray<z.ZodEnum<{
11
+ pages: "pages";
12
+ api: "api";
13
+ mcp: "mcp";
14
+ worker: "worker";
15
+ }>>>>;
10
16
  id: z.ZodString;
11
17
  version: z.ZodString;
12
18
  commit: z.ZodString;
@@ -1,5 +1,5 @@
1
1
  import { z } from 'zod';
2
- import { CommandNameSchema, CommitSchema, ExtensionIdSchema, IMAGE_PART_KINDS, PrefixedToolNameSchema, SecretNameSchema, StoreKindSchema, VersionSchema, } from '../manifest/primitives.schema.js';
2
+ import { CommandNameSchema, CommitSchema, ExtensionIdSchema, IMAGE_PART_KINDS, PrefixedToolNameSchema, SecretNameSchema, SecretPartSchema, StoreKindSchema, VersionSchema, } from '../manifest/primitives.schema.js';
3
3
  // registry host[:port]/owner/{id}-{part}@sha256: deployed by digest, a version's images never change.
4
4
  const ImageDigestRefSchema = z
5
5
  .string()
@@ -39,9 +39,10 @@ const recordShape = {
39
39
  commit: CommitSchema,
40
40
  buildTime: z.iso.datetime(),
41
41
  parts: PartsRecordSchema,
42
+ // /api/v{N}: an extension still on a kit before 0.13, read by a newer one; it goes in phase 4.
42
43
  openapi: z
43
44
  .string()
44
- .regex(/^\/api\/v[1-9][0-9]*\/openapi\.json$/)
45
+ .regex(/^\/api\/(?:v[0-9]+|[a-z][a-z0-9-]*)\/openapi\.json$/)
45
46
  .optional(),
46
47
  tools: z.array(ToolRecordSchema).min(1).optional(),
47
48
  widgets: z.array(WidgetSchema).min(1).optional(),
@@ -52,12 +53,28 @@ const imagesNameTheirExtension = (doc) => IMAGE_PART_KINDS.every((kind) => {
52
53
  return image === undefined || image.includes(`/${doc.id}-${kind}@sha256:`);
53
54
  });
54
55
  const IMAGE_RULE = { message: 'every image is {id}-{part}', path: ['parts'] };
56
+ // The api prefix is /api/{id}, or the old /api/v{N}: never another extension's id.
57
+ const openapiNamesItsExtension = ({ id, openapi }) => !openapi || /^\/api\/v[0-9]+\//.test(openapi) || openapi === `/api/${id}/openapi.json`;
58
+ const OPENAPI_RULE = { message: 'openapi is /api/{id}/openapi.json', path: ['openapi'] };
59
+ // A scoped name lives only in secretParts, so an estate that does not read it mounts nothing.
60
+ const scoped = (name) => `secret ${name}: one or more parts, none repeated, and never also in secrets`;
55
61
  // The build record: written by `build --push` into the package and the release asset; no host.
56
- // Secret names are for the estate's mounts only; discovery leaves them out.
62
+ // Secret names and scoped parts are for the estate's mounts only; discovery leaves them out.
57
63
  export const ExtensionRecordSchema = z
58
- .strictObject({ ...recordShape, secrets: z.array(SecretNameSchema).min(1).optional() })
59
- .refine(imagesNameTheirExtension, IMAGE_RULE);
64
+ .strictObject({
65
+ ...recordShape,
66
+ secrets: z.array(SecretNameSchema).min(1).optional(),
67
+ secretParts: z.record(SecretNameSchema, z.array(SecretPartSchema)).optional(),
68
+ })
69
+ .refine(imagesNameTheirExtension, IMAGE_RULE)
70
+ .refine(openapiNamesItsExtension, OPENAPI_RULE)
71
+ .superRefine((doc, ctx) => {
72
+ for (const [name, parts] of Object.entries(doc.secretParts ?? {}))
73
+ if (!parts.length || new Set(parts).size !== parts.length || doc.secrets?.includes(name))
74
+ ctx.addIssue({ code: 'custom', path: ['secretParts', name], message: scoped(name) });
75
+ });
60
76
  // What a deployment serves at /.well-known/agentage-extension.json: the record plus its host.
61
77
  export const DiscoveryDocumentSchema = z
62
78
  .strictObject({ ...recordShape, host: OriginSchema })
63
- .refine(imagesNameTheirExtension, IMAGE_RULE);
79
+ .refine(imagesNameTheirExtension, IMAGE_RULE)
80
+ .refine(openapiNamesItsExtension, OPENAPI_RULE);
@@ -1,3 +1,4 @@
1
1
  export declare const OPENAPI_FILE = "openapi.json";
2
- export declare const OPENAPI_PATH = "/api/v1/openapi.json";
2
+ export declare const apiPrefix: (id: string) => string;
3
+ export declare const openapiPath: (id: string) => string;
3
4
  export declare const readOpenapi: (dir: string) => Promise<Record<string, unknown> | null>;
@@ -2,7 +2,9 @@ import { join } from 'node:path';
2
2
  import { z } from 'zod';
3
3
  import { readJsonIfExists } from '../manifest/read-manifest.js';
4
4
  export const OPENAPI_FILE = 'openapi.json';
5
- export const OPENAPI_PATH = '/api/v1/openapi.json';
5
+ // The api part's URL prefix: the extension id, no version (D3 of S1.1.1).
6
+ export const apiPrefix = (id) => `/api/${id}`;
7
+ export const openapiPath = (id) => `${apiPrefix(id)}/openapi.json`;
6
8
  const OpenapiSchema = z.looseObject({
7
9
  openapi: z.string().regex(/^3\.1\.[0-9]+$/, { message: 'OpenAPI 3.1' }),
8
10
  paths: z.record(z.string(), z.unknown()),
@@ -0,0 +1,21 @@
1
+ export interface LaunchSpec {
2
+ id: string;
3
+ dir: string;
4
+ dataDir: string;
5
+ settings: Record<string, unknown>;
6
+ secrets: Record<string, string>;
7
+ origin: string;
8
+ }
9
+ export interface Exit {
10
+ code: number | null;
11
+ signal: string | null;
12
+ }
13
+ export interface Child {
14
+ port: number;
15
+ pid: number;
16
+ exited: Promise<Exit>;
17
+ stop(): Promise<void>;
18
+ }
19
+ export type Launch = (spec: LaunchSpec) => Promise<Child>;
20
+ export declare const HOST_MAIN: string;
21
+ export declare const forkLaunch: (main?: string) => Launch;
@@ -0,0 +1,92 @@
1
+ import { fork } from 'node:child_process';
2
+ import { mkdtemp, rm, writeFile } from 'node:fs/promises';
3
+ import { tmpdir } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
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;
9
+ const STOP_MS = 5_000;
10
+ const PASSED = ['PATH', 'HOME', 'TMPDIR', 'LANG', 'NODE_EXTRA_CA_CERTS'];
11
+ // Handed over as 0600 files in a 0700 folder, removed once the child has read them.
12
+ const secretFiles = async (spec) => {
13
+ const dir = await mkdtemp(join(tmpdir(), `agentage-${spec.id}-`));
14
+ for (const [name, value] of Object.entries(spec.secrets))
15
+ await writeFile(join(dir, SecretNameSchema.parse(name)), value, { mode: 0o600 });
16
+ return dir;
17
+ };
18
+ const envOf = (spec, secretsDir) => ({
19
+ ...Object.fromEntries(PASSED.flatMap((k) => (process.env[k] ? [[k, process.env[k]]] : []))),
20
+ PORT: '0',
21
+ AGENTAGE_EXTENSION_DIR: spec.dir,
22
+ AGENTAGE_DATA_DIR: spec.dataDir,
23
+ AGENTAGE_SETTINGS: JSON.stringify(spec.settings),
24
+ AGENTAGE_SECRETS_DIR: secretsDir,
25
+ AGENTAGE_ORIGIN: spec.origin,
26
+ });
27
+ // The child's last stderr line, its msg when it is a log row: why it did not start.
28
+ const lastWords = (tail, code) => {
29
+ const lines = tail
30
+ .trim()
31
+ .split('\n')
32
+ .filter((l) => !/^Node\.js v\d/.test(l));
33
+ const line = lines.at(-1) ?? '';
34
+ try {
35
+ const msg = String(JSON.parse(line).msg ?? line);
36
+ return msg.replace(/^[A-Za-z]*Error: /, '');
37
+ }
38
+ catch {
39
+ return line || `exited with code ${code}`;
40
+ }
41
+ };
42
+ const captured = (child) => {
43
+ let tail = '';
44
+ child.stdout?.pipe(process.stdout);
45
+ child.stderr?.on('data', (chunk) => {
46
+ process.stderr.write(chunk);
47
+ tail = (tail + chunk.toString()).slice(-4000);
48
+ });
49
+ return () => tail;
50
+ };
51
+ const portOf = (msg) => {
52
+ const { type, port } = (msg ?? {});
53
+ return type === 'ready' && typeof port === 'number' ? port : undefined;
54
+ };
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);
58
+ const settle = (fn) => {
59
+ clearTimeout(timer);
60
+ fn();
61
+ };
62
+ child.on('message', (msg) => {
63
+ const port = portOf(msg);
64
+ if (port)
65
+ settle(() => resolve(port));
66
+ });
67
+ child.once('exit', (code) => settle(() => reject(new Error(lastWords(tail(), code)))));
68
+ });
69
+ // SIGTERM drains; a child still there after STOP_MS (a request that never ends) gets SIGKILL.
70
+ const stopOf = (child, exited) => async () => {
71
+ if (child.exitCode === null && child.signalCode === null)
72
+ child.kill('SIGTERM');
73
+ const kill = setTimeout(() => child.kill('SIGKILL'), STOP_MS);
74
+ await exited;
75
+ clearTimeout(kill);
76
+ };
77
+ // 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) => {
79
+ const secretsDir = await secretFiles(spec);
80
+ const stdio = ['ignore', 'pipe', 'pipe', 'ipc'];
81
+ // execArgv []: the daemon's own node flags (a loader, --input-type) are not the child's.
82
+ const env = envOf(spec, secretsDir);
83
+ const child = fork(main, [], { env, execArgv: [], stdio: [...stdio] });
84
+ const exited = new Promise((resolve) => child.once('exit', (code, signal) => resolve({ code, signal })));
85
+ try {
86
+ const port = await readyOf(child, captured(child));
87
+ return { port, pid: child.pid ?? 0, exited, stop: stopOf(child, exited) };
88
+ }
89
+ finally {
90
+ await rm(secretsDir, { recursive: true, force: true });
91
+ }
92
+ };
@@ -0,0 +1,19 @@
1
+ export declare const DAEMON_FILE = "daemon.json";
2
+ export declare const DAEMON_PROTOCOL = 1;
3
+ export interface DaemonFile {
4
+ pid: number;
5
+ port: number;
6
+ version: string;
7
+ protocol: number;
8
+ startedBy: string;
9
+ }
10
+ export declare const writeDaemonFile: (configDir: string, file: DaemonFile) => Promise<void>;
11
+ export declare const removeDaemonFile: (configDir: string) => Promise<void>;
12
+ export declare const dataDirOf: (configDir: string, id: string) => string;
13
+ export declare const purgeData: (configDir: string, id: string) => Promise<void>;
14
+ export type ValueKind = 'settings' | 'secrets';
15
+ type Values = Record<string, unknown>;
16
+ 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>;
19
+ export {};
@@ -0,0 +1,23 @@
1
+ import { mkdir, rm, unlink } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { readJsonFile, withFileLock, writeJsonFile } from './json-file.js';
4
+ export const DAEMON_FILE = 'daemon.json';
5
+ export const DAEMON_PROTOCOL = 1;
6
+ export const writeDaemonFile = (configDir, file) => writeJsonFile(join(configDir, DAEMON_FILE), file);
7
+ export const removeDaemonFile = (configDir) => unlink(join(configDir, DAEMON_FILE)).catch(() => undefined);
8
+ export const dataDirOf = (configDir, id) => join(configDir, 'data', id);
9
+ export const purgeData = (configDir, id) => rm(dataDirOf(configDir, id), { recursive: true, force: true });
10
+ const fileOf = (configDir, kind) => join(configDir, `${kind}.json`);
11
+ export const readValues = async (configDir, kind, id) => (await readJsonFile(fileOf(configDir, kind), {}))[id] ?? {};
12
+ export const writeValues = (configDir, kind, id, values) => {
13
+ const file = fileOf(configDir, kind);
14
+ return withFileLock(file, async () => {
15
+ 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
+ });
22
+ };
23
+ export const ensureConfigDir = (configDir) => mkdir(configDir, { recursive: true });
@@ -0,0 +1,18 @@
1
+ import { type Launch } from './child.js';
2
+ import { type Installer } from './supervisor.js';
3
+ export interface DaemonOptions {
4
+ configDir: string;
5
+ port?: number;
6
+ install?: Installer;
7
+ version: string;
8
+ startedBy: string;
9
+ drainMs?: number;
10
+ healthMs?: number;
11
+ }
12
+ export interface Daemon {
13
+ port: number;
14
+ stop(): Promise<void>;
15
+ }
16
+ export declare const DAEMON_PORT = 4243;
17
+ export declare const startDaemon: (opts: DaemonOptions, launch: Launch) => Promise<Daemon>;
18
+ export declare const createDaemon: (opts: DaemonOptions) => Promise<Daemon>;
@@ -0,0 +1,84 @@
1
+ import {} from 'node:http';
2
+ import {} from 'node:net';
3
+ import { createLog } from '../../log/log.js';
4
+ import { listen } from '../../server/serve.js';
5
+ 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';
9
+ import { serialQueue } from './queue.js';
10
+ import { daemonApp } from './routes.js';
11
+ import { DRAIN_MS, HEALTH_MS, halt, startEntry, } from './supervisor.js';
12
+ 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);
16
+ if (invalid)
17
+ await keepBadCopy(configDir).catch(() => undefined);
18
+ const entries = new Map();
19
+ for (const install of doc.extensions) {
20
+ const state = install.enabled === false ? 'disabled' : 'starting';
21
+ entries.set(install.id, { id: install.id, install, state, version: install.version ?? '' });
22
+ }
23
+ return { entries, invalid };
24
+ };
25
+ // One at a time, so the installer is never called twice at once; a failed one stops no other.
26
+ const boot = async (deps, entries) => {
27
+ for (const entry of entries.values())
28
+ if (entry.state === 'starting')
29
+ await startEntry(deps, entry);
30
+ };
31
+ const close = (server) => new Promise((resolve) => {
32
+ server.close(() => resolve());
33
+ server.closeAllConnections();
34
+ });
35
+ const stopper = (server, entries, deps) => {
36
+ let stopped;
37
+ const stop = async () => {
38
+ await Promise.all([...entries.values()].map((entry) => halt(entry, deps.drainMs)));
39
+ await close(server);
40
+ await removeDaemonFile(deps.configDir);
41
+ };
42
+ return () => (stopped ??= stop());
43
+ };
44
+ // C4: how a client finds this daemon.
45
+ const announce = ({ configDir, version, startedBy }, port) => writeDaemonFile(configDir, {
46
+ pid: process.pid,
47
+ port,
48
+ version,
49
+ protocol: DAEMON_PROTOCOL,
50
+ startedBy,
51
+ });
52
+ const depsOf = (opts, launch, origin) => ({
53
+ configDir: opts.configDir,
54
+ launch,
55
+ install: opts.install,
56
+ log: createLog({ extension: 'host', part: 'api', version: opts.version }),
57
+ origin,
58
+ drainMs: opts.drainMs ?? DRAIN_MS,
59
+ healthMs: opts.healthMs ?? HEALTH_MS,
60
+ queue: serialQueue(),
61
+ });
62
+ // Read and check the file, listen, write daemon.json, start the children; a failed boot undoes it.
63
+ export const startDaemon = async (opts, launch) => {
64
+ await ensureConfigDir(opts.configDir);
65
+ 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 };
69
+ const app = daemonApp(deps, entries, () => port, info);
70
+ const server = await listen(app, port, '127.0.0.1');
71
+ port = server.address().port;
72
+ const stop = stopper(server, entries, deps);
73
+ try {
74
+ await announce(opts, port);
75
+ await deps.queue(() => boot(deps, entries));
76
+ }
77
+ catch (err) {
78
+ await stop();
79
+ throw err;
80
+ }
81
+ return { port, stop };
82
+ };
83
+ // One daemon on 127.0.0.1, one child process for each extension (D1).
84
+ export const createDaemon = (opts) => startDaemon(opts, forkLaunch());
@@ -0,0 +1,2 @@
1
+ import { type RequestHandler } from 'express';
2
+ export declare const localOnly: (port: () => number) => RequestHandler;
@@ -0,0 +1,15 @@
1
+ import {} from 'express';
2
+ import { fail } from '../../envelope/envelope.js';
3
+ // What a browser says of a request another site started (an <img>, a link, a form).
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.
6
+ export const localOnly = (port) => (req, _res, next) => {
7
+ const hosts = [`127.0.0.1:${port()}`, `localhost:${port()}`];
8
+ const origin = req.get('origin');
9
+ const hostOk = hosts.includes(req.get('host') ?? '');
10
+ const originOk = origin === undefined || hosts.some((host) => origin === `http://${host}`);
11
+ const siteOk = !FOREIGN.includes(req.get('sec-fetch-site') ?? '');
12
+ if (!hostOk || !originOk || !siteOk)
13
+ throw fail('FORBIDDEN', 'Only this machine may call the daemon');
14
+ next();
15
+ };