@agentage/extension 0.14.0 → 0.15.1

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 (105) hide show
  1. package/README.md +3 -1
  2. package/dist/contracts/index.d.ts +1 -1
  3. package/dist/contracts/index.js +1 -1
  4. package/dist/discovery/discovery.d.ts +10 -25
  5. package/dist/discovery/discovery.js +7 -1
  6. package/dist/discovery/discovery.schema.d.ts +45 -0
  7. package/dist/discovery/discovery.schema.js +33 -4
  8. package/dist/discovery/served-extras.d.ts +8 -0
  9. package/dist/discovery/served-extras.js +10 -0
  10. package/dist/health/health.d.ts +2 -0
  11. package/dist/health/health.js +4 -2
  12. package/dist/health/health.schema.d.ts +9 -0
  13. package/dist/health/health.schema.js +3 -0
  14. package/dist/host/clock-rate.d.ts +1 -0
  15. package/dist/host/clock-rate.js +12 -0
  16. package/dist/host/daemon/add.js +29 -4
  17. package/dist/host/daemon/child-files.d.ts +20 -0
  18. package/dist/host/daemon/child-files.js +45 -0
  19. package/dist/host/daemon/child.d.ts +10 -4
  20. package/dist/host/daemon/child.js +68 -43
  21. package/dist/host/daemon/daemon-files.d.ts +3 -0
  22. package/dist/host/daemon/daemon-files.js +5 -1
  23. package/dist/host/daemon/daemon.d.ts +1 -0
  24. package/dist/host/daemon/daemon.js +21 -6
  25. package/dist/host/daemon/gate.d.ts +3 -0
  26. package/dist/host/daemon/gate.js +19 -0
  27. package/dist/host/daemon/guard.d.ts +2 -1
  28. package/dist/host/daemon/guard.js +16 -4
  29. package/dist/host/daemon/health-routes.d.ts +17 -0
  30. package/dist/host/daemon/health-routes.js +61 -0
  31. package/dist/host/daemon/host-token.d.ts +6 -0
  32. package/dist/host/daemon/host-token.js +28 -0
  33. package/dist/host/daemon/last-words.d.ts +2 -0
  34. package/dist/host/daemon/last-words.js +28 -0
  35. package/dist/host/daemon/limits.d.ts +4 -0
  36. package/dist/host/daemon/limits.js +7 -0
  37. package/dist/host/daemon/ops.js +4 -1
  38. package/dist/host/daemon/pending.d.ts +1 -1
  39. package/dist/host/daemon/proxy.d.ts +1 -1
  40. package/dist/host/daemon/proxy.js +16 -8
  41. package/dist/host/daemon/redact-stream.d.ts +4 -0
  42. package/dist/host/daemon/redact-stream.js +24 -0
  43. package/dist/host/daemon/reload-marker.d.ts +8 -0
  44. package/dist/host/daemon/reload-marker.js +56 -0
  45. package/dist/host/daemon/reload-route.d.ts +4 -0
  46. package/dist/host/daemon/reload-route.js +21 -0
  47. package/dist/host/daemon/reload.d.ts +10 -0
  48. package/dist/host/daemon/reload.js +73 -0
  49. package/dist/host/daemon/restart.d.ts +14 -0
  50. package/dist/host/daemon/restart.js +59 -0
  51. package/dist/host/daemon/routes.d.ts +2 -10
  52. package/dist/host/daemon/routes.js +13 -31
  53. package/dist/host/daemon/run-lock.d.ts +1 -0
  54. package/dist/host/daemon/run-lock.js +15 -0
  55. package/dist/host/daemon/seal-reach.d.ts +2 -0
  56. package/dist/host/daemon/seal-reach.js +38 -0
  57. package/dist/host/daemon/seal.d.ts +16 -0
  58. package/dist/host/daemon/seal.js +71 -0
  59. package/dist/host/daemon/start-checks.d.ts +7 -0
  60. package/dist/host/daemon/start-checks.js +29 -0
  61. package/dist/host/daemon/supervisor.d.ts +9 -3
  62. package/dist/host/daemon/supervisor.js +33 -40
  63. package/dist/host/data-lock.d.ts +2 -1
  64. package/dist/host/data-lock.js +25 -6
  65. package/dist/host/host-env.d.ts +1 -0
  66. package/dist/host/host-env.js +2 -0
  67. package/dist/host/host-extension.d.ts +6 -0
  68. package/dist/host/host-extension.js +28 -44
  69. package/dist/host/host-parts.d.ts +25 -0
  70. package/dist/host/host-parts.js +82 -0
  71. package/dist/host/host-store.d.ts +3 -0
  72. package/dist/host/host-store.js +21 -2
  73. package/dist/host/main.js +2 -0
  74. package/dist/host/part-checks.d.ts +2 -0
  75. package/dist/host/part-checks.js +19 -0
  76. package/dist/host/serve-host.js +10 -6
  77. package/dist/manifest/parts.d.ts +3 -0
  78. package/dist/manifest/parts.js +3 -0
  79. package/dist/mcp/mcp-app.d.ts +4 -0
  80. package/dist/mcp/mcp-app.js +11 -11
  81. package/dist/runtime/part-mounts.d.ts +31 -0
  82. package/dist/runtime/part-mounts.js +57 -0
  83. package/dist/runtime/part-runners.d.ts +2 -15
  84. package/dist/runtime/part-runners.js +13 -58
  85. package/dist/server/app.d.ts +5 -3
  86. package/dist/server/app.js +16 -17
  87. package/dist/tool/build.d.ts +1 -0
  88. package/dist/tool/build.js +3 -2
  89. package/dist/tool/check.d.ts +3 -1
  90. package/dist/tool/check.js +25 -9
  91. package/dist/tool/container-parts.d.ts +1 -1
  92. package/dist/tool/container-parts.js +6 -6
  93. package/dist/tool/format.d.ts +1 -0
  94. package/dist/tool/format.js +17 -8
  95. package/dist/tool/kit-version.d.ts +2 -0
  96. package/dist/tool/kit-version.js +12 -0
  97. package/dist/tool/record-extras.js +5 -12
  98. package/dist/worker/clock.d.ts +6 -0
  99. package/dist/worker/clock.js +21 -0
  100. package/dist/worker/scheduler.d.ts +1 -0
  101. package/dist/worker/scheduler.js +6 -2
  102. package/package.json +1 -1
  103. package/schemas/extension-discovery.schema.json +61 -34
  104. package/schemas/extension-record.schema.json +1 -1
  105. package/schemas/health.schema.json +17 -0
package/README.md CHANGED
@@ -12,7 +12,9 @@ npm install @agentage/extension express zod
12
12
  ```
13
13
 
14
14
  `agentage extension check [dir] --json` prints the conformance report (exit 1 when `conforms` is
15
- false); `file` and `line` are there only when a problem has them:
15
+ false); `file` and `line` are there only when a problem has them. `warnings` is there only when a
16
+ rule warned: an `engines.agentage` of an older kit minor from the floor `0.12` up conforms with a
17
+ warning; below the floor or above the running kit it is a problem:
16
18
 
17
19
  ```json
18
20
  {
@@ -1,5 +1,5 @@
1
1
  export { AGCID_HEADER, isAgcid } from '../agcid/header.js';
2
- export { DiscoveryDocumentSchema, ExtensionRecordSchema, type DiscoveryDocument, type ExtensionRecord, } from '../discovery/discovery.schema.js';
2
+ export { CloudDiscoveryDocumentSchema, DiscoveryDocumentSchema, ExtensionRecordSchema, type DiscoveryDocument, type ExtensionRecord, } from '../discovery/discovery.schema.js';
3
3
  export { ERROR_CODES, type ErrorCode } from '../envelope/codes.js';
4
4
  export { ErrorEnvelopeSchema, OkEnvelopeSchema } from '../envelope/envelope.schema.js';
5
5
  export { type ErrorEnvelope, type OkEnvelope } from '../envelope/envelope.js';
@@ -1,5 +1,5 @@
1
1
  export { AGCID_HEADER, isAgcid } from '../agcid/header.js';
2
- export { DiscoveryDocumentSchema, ExtensionRecordSchema, } from '../discovery/discovery.schema.js';
2
+ export { CloudDiscoveryDocumentSchema, DiscoveryDocumentSchema, ExtensionRecordSchema, } from '../discovery/discovery.schema.js';
3
3
  export { ERROR_CODES } from '../envelope/codes.js';
4
4
  export { ErrorEnvelopeSchema, OkEnvelopeSchema } from '../envelope/envelope.schema.js';
5
5
  export {} from '../envelope/envelope.js';
@@ -1,6 +1,7 @@
1
1
  import { type ExtensionPackage } from '../manifest/manifest.schema.js';
2
+ import { type HostPartKind } from '../manifest/parts.js';
2
3
  import { type ImagePartKind } from '../manifest/primitives.schema.js';
3
- import { type ExtensionRecord } from './discovery.schema.js';
4
+ import { type DiscoveryDocument, type ExtensionRecord } from './discovery.schema.js';
4
5
  export interface BuildInfo {
5
6
  commit: string;
6
7
  buildTime: string;
@@ -21,34 +22,18 @@ export interface RecordExtras {
21
22
  migrations?: number;
22
23
  }
23
24
  export declare const recordOf: (pkg: ExtensionPackage, build: BuildInfo, images: PartImages, extras?: RecordExtras) => ExtensionRecord;
25
+ export type ServedRecord = Omit<ExtensionRecord, 'parts'> & {
26
+ parts: DiscoveryDocument['parts'];
27
+ };
28
+ export declare const hostedRecordOf: (pkg: ExtensionPackage, build: BuildInfo, hosted: readonly HostPartKind[], extras: RecordExtras) => ServedRecord;
24
29
  export declare const validateRecord: (value: unknown) => ExtensionRecord;
25
30
  export declare const loadRecord: (file: string) => Promise<ExtensionRecord | null>;
26
- export declare const discoveryDocument: (record: ExtensionRecord, host: string) => {
27
- parts: {
28
- pages?: {
29
- image: string;
30
- } | undefined;
31
- ui?: {
32
- image: string;
33
- } | undefined;
34
- api?: {
35
- image: string;
36
- } | undefined;
37
- mcp?: {
38
- image: string;
39
- } | undefined;
40
- worker?: {
41
- image: string;
42
- } | undefined;
43
- store?: {
44
- kind: "postgres" | "signoz" | "git" | "clickhouse";
45
- migrations?: number | undefined;
46
- } | undefined;
47
- };
31
+ export declare const discoveryDocument: (record: ServedRecord, host: string) => {
32
+ commands?: string[] | undefined;
48
33
  secrets?: string[] | undefined;
49
- secretParts?: Record<string, ("pages" | "api" | "mcp" | "worker")[]> | undefined;
50
34
  image?: string | undefined;
51
35
  openapi?: string | undefined;
36
+ secretParts?: Record<string, ("pages" | "api" | "mcp" | "worker")[]> | undefined;
52
37
  tools?: {
53
38
  name: string;
54
39
  scope: string;
@@ -58,7 +43,7 @@ export declare const discoveryDocument: (record: ExtensionRecord, host: string)
58
43
  element: string;
59
44
  module: string;
60
45
  }[] | undefined;
61
- commands?: string[] | undefined;
46
+ parts: DiscoveryDocument["parts"];
62
47
  id: string;
63
48
  version: string;
64
49
  commit: string;
@@ -2,7 +2,7 @@ import { formatIssues, readJsonIfExists } from '../manifest/read-manifest.js';
2
2
  import {} from '../manifest/manifest.schema.js';
3
3
  import { normalizeParts, scopedSecrets } from '../manifest/parts.js';
4
4
  import {} from '../manifest/primitives.schema.js';
5
- import { ExtensionRecordSchema } from './discovery.schema.js';
5
+ import { ExtensionRecordSchema, } from './discovery.schema.js';
6
6
  export const DEFAULT_RECORD_FILE = '/run/agentage/agentage-extension.json';
7
7
  const partsOf = (pkg, images, migrations) => {
8
8
  const parts = {};
@@ -34,6 +34,12 @@ export const recordOf = (pkg, build, images, extras = {}) => {
34
34
  record.secretParts = scopedSecrets(pkg);
35
35
  return record;
36
36
  };
37
+ // The kit host never knows its digest: the parts it runs have no image; pages and ui are not listed.
38
+ export const hostedRecordOf = (pkg, build, hosted, extras) => {
39
+ const record = recordOf(pkg, build, {}, extras);
40
+ const bare = Object.fromEntries(hosted.map((kind) => [kind, {}]));
41
+ return { ...record, parts: { ...bare, ...record.parts } };
42
+ };
37
43
  export const validateRecord = (value) => {
38
44
  const result = ExtensionRecordSchema.safeParse(value);
39
45
  if (result.success)
@@ -57,6 +57,51 @@ export declare const ExtensionRecordSchema: z.ZodObject<{
57
57
  commands: z.ZodOptional<z.ZodArray<z.ZodString>>;
58
58
  }, z.core.$strict>;
59
59
  export declare const DiscoveryDocumentSchema: z.ZodObject<{
60
+ parts: z.ZodObject<{
61
+ pages: z.ZodOptional<z.ZodObject<{
62
+ image: z.ZodString;
63
+ }, z.core.$strict>>;
64
+ ui: z.ZodOptional<z.ZodObject<{
65
+ image: z.ZodString;
66
+ }, z.core.$strict>>;
67
+ api: z.ZodOptional<z.ZodUnion<readonly [z.ZodObject<{
68
+ image: z.ZodString;
69
+ }, z.core.$strict>, z.ZodObject<{}, z.core.$strict>]>>;
70
+ mcp: z.ZodOptional<z.ZodUnion<readonly [z.ZodObject<{
71
+ image: z.ZodString;
72
+ }, z.core.$strict>, z.ZodObject<{}, z.core.$strict>]>>;
73
+ worker: z.ZodOptional<z.ZodUnion<readonly [z.ZodObject<{
74
+ image: z.ZodString;
75
+ }, z.core.$strict>, z.ZodObject<{}, z.core.$strict>]>>;
76
+ store: z.ZodOptional<z.ZodObject<{
77
+ kind: z.ZodEnum<{
78
+ postgres: "postgres";
79
+ signoz: "signoz";
80
+ git: "git";
81
+ clickhouse: "clickhouse";
82
+ }>;
83
+ migrations: z.ZodOptional<z.ZodInt>;
84
+ }, z.core.$strict>>;
85
+ }, z.core.$strict>;
86
+ host: z.ZodString;
87
+ id: z.ZodString;
88
+ version: z.ZodString;
89
+ commit: z.ZodString;
90
+ buildTime: z.ZodISODateTime;
91
+ image: z.ZodOptional<z.ZodString>;
92
+ openapi: z.ZodOptional<z.ZodString>;
93
+ tools: z.ZodOptional<z.ZodArray<z.ZodObject<{
94
+ name: z.ZodString;
95
+ scope: z.ZodString;
96
+ }, z.core.$strict>>>;
97
+ widgets: z.ZodOptional<z.ZodArray<z.ZodObject<{
98
+ name: z.ZodString;
99
+ element: z.ZodString;
100
+ module: z.ZodString;
101
+ }, z.core.$strict>>>;
102
+ commands: z.ZodOptional<z.ZodArray<z.ZodString>>;
103
+ }, z.core.$strict>;
104
+ export declare const CloudDiscoveryDocumentSchema: z.ZodObject<{
60
105
  host: z.ZodString;
61
106
  id: z.ZodString;
62
107
  version: z.ZodString;
@@ -11,15 +11,27 @@ const OneImageRefSchema = z
11
11
  .string()
12
12
  .max(256)
13
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 StoreRecordSchema = z.strictObject({
15
+ kind: StoreKindSchema,
16
+ migrations: z.int().min(0).optional(),
17
+ });
14
18
  const PartsRecordSchema = z.strictObject({
15
19
  pages: PartImageSchema.optional(),
16
20
  ui: PartImageSchema.optional(),
17
21
  api: PartImageSchema.optional(),
18
22
  mcp: PartImageSchema.optional(),
19
23
  worker: PartImageSchema.optional(),
20
- store: z
21
- .strictObject({ kind: StoreKindSchema, migrations: z.int().min(0).optional() })
22
- .optional(),
24
+ store: StoreRecordSchema.optional(),
25
+ });
26
+ // A part the kit host runs has no image: the host never knows its own digest.
27
+ const HostedPartSchema = z.strictObject({});
28
+ const ServedPartsSchema = z.strictObject({
29
+ pages: PartImageSchema.optional(),
30
+ ui: PartImageSchema.optional(),
31
+ api: z.union([PartImageSchema, HostedPartSchema]).optional(),
32
+ mcp: z.union([PartImageSchema, HostedPartSchema]).optional(),
33
+ worker: z.union([PartImageSchema, HostedPartSchema]).optional(),
34
+ store: StoreRecordSchema.optional(),
23
35
  });
24
36
  export const OriginSchema = z
25
37
  .string()
@@ -40,7 +52,7 @@ const recordShape = {
40
52
  commit: CommitSchema,
41
53
  buildTime: z.iso.datetime(),
42
54
  parts: PartsRecordSchema,
43
- image: OneImageRefSchema.optional().describe('The one image (build --container). A record has part images or this image: never both, never none.'),
55
+ image: OneImageRefSchema.optional().describe('The one image (build --container). A build record has part images or this image: never both, never none.'),
44
56
  // /api/v{N}: an extension still on a kit before 0.13, read by a newer one; it goes in phase 4.
45
57
  openapi: z
46
58
  .string()
@@ -63,6 +75,17 @@ const FORM_RULE = {
63
75
  message: 'at least one part with an image, or the one image and no part image',
64
76
  path: ['parts'],
65
77
  };
78
+ // Discovery also takes the kit host's form: one or more parts, none with an image, no one image.
79
+ const servedForm = (doc) => {
80
+ const bare = IMAGE_PART_KINDS.filter((kind) => doc.parts[kind] && !doc.parts[kind].image);
81
+ if (!bare.length)
82
+ return oneImageForm(doc);
83
+ return !doc.image && IMAGE_PART_KINDS.every((kind) => doc.parts[kind]?.image === undefined);
84
+ };
85
+ const HOSTED_RULE = {
86
+ message: 'at least one part with an image, the one image, or only parts with no image',
87
+ path: ['parts'],
88
+ };
66
89
  // The api prefix is /api/{id}, or the old /api/v{N}: never another extension's id.
67
90
  const openapiNamesItsExtension = ({ id, openapi }) => !openapi || /^\/api\/v[0-9]+\//.test(openapi) || openapi === `/api/${id}/openapi.json`;
68
91
  const OPENAPI_RULE = { message: 'openapi is /api/{id}/openapi.json', path: ['openapi'] };
@@ -86,6 +109,12 @@ export const ExtensionRecordSchema = z
86
109
  });
87
110
  // What a deployment serves at /.well-known/agentage-extension.json: the record plus its host.
88
111
  export const DiscoveryDocumentSchema = z
112
+ .strictObject({ ...recordShape, parts: ServedPartsSchema, host: OriginSchema })
113
+ .refine(servedForm, HOSTED_RULE)
114
+ .refine(imagesNameTheirExtension, IMAGE_RULE)
115
+ .refine(openapiNamesItsExtension, OPENAPI_RULE);
116
+ // The form the cloud serves: every part by its image, or the one image; never a part with no image.
117
+ export const CloudDiscoveryDocumentSchema = z
89
118
  .strictObject({ ...recordShape, host: OriginSchema })
90
119
  .refine(oneImageForm, FORM_RULE)
91
120
  .refine(imagesNameTheirExtension, IMAGE_RULE)
@@ -0,0 +1,8 @@
1
+ import { type ExtensionPackage } from '../manifest/manifest.schema.js';
2
+ import { type ToolEntry } from '../mcp/tools.js';
3
+ import { type RecordExtras } from './discovery.js';
4
+ export declare const toolRecords: (id: string, tools: Pick<ToolEntry, "name" | "spec">[]) => {
5
+ name: string;
6
+ scope: string;
7
+ }[];
8
+ export declare const migrationsOf: (dir: string, pkg: ExtensionPackage) => Promise<RecordExtras>;
@@ -0,0 +1,10 @@
1
+ import { join } from 'node:path';
2
+ import { scopeOf } from '../auth/token-check.js';
3
+ import {} from '../manifest/manifest.schema.js';
4
+ import { migratesStore } from '../manifest/parts.js';
5
+ import { prefixed } from '../mcp/tools.js';
6
+ import { sqlFiles } from '../store/migrations.js';
7
+ import {} from './discovery.js';
8
+ // Each tool as tools/list names it, with the scope tools/call needs.
9
+ export const toolRecords = (id, tools) => tools.map((tool) => ({ name: prefixed(id, tool.name), scope: scopeOf(id, tool.spec.scope) }));
10
+ export const migrationsOf = async (dir, pkg) => migratesStore(pkg) ? { migrations: (await sqlFiles(join(dir, 'migrations'))).length } : {};
@@ -12,7 +12,9 @@ export interface HealthOptions {
12
12
  checks?: Record<string, HealthCheck>;
13
13
  instance?: string;
14
14
  startedAt?: number;
15
+ parts?: ImagePartKind[];
15
16
  now?: () => Date;
17
+ clockRate?: number;
16
18
  log?: Log;
17
19
  }
18
20
  export declare const worstOf: (statuses: HealthStatus[]) => HealthStatus;
@@ -36,9 +36,11 @@ export const healthBody = async (options) => {
36
36
  const now = (options.now ?? (() => new Date()))();
37
37
  const checks = await runChecks(options.checks ?? {});
38
38
  const status = worstOf(Object.values(checks));
39
- const { extension, part, version, build, instance } = options;
39
+ const { extension, part, parts, version, build, instance } = options;
40
40
  const uptimeSeconds = Math.max(0, Math.floor((now.getTime() - options.startedAt) / 1000));
41
- const data = { status, extension, part, version, ...build, instance };
41
+ const clock = options.clockRate && options.clockRate !== 1 ? { clockRate: options.clockRate } : {};
42
+ const listed = parts ? { parts } : {};
43
+ const data = { status, extension, part, ...listed, version, ...build, instance, ...clock };
42
44
  return {
43
45
  success: status !== 'unavailable',
44
46
  data: { ...data, uptimeSeconds, checkedAt: isoSeconds(now), checks },
@@ -21,9 +21,18 @@ export declare const HealthSchema: z.ZodObject<{
21
21
  worker: "worker";
22
22
  store: "store";
23
23
  }>;
24
+ parts: z.ZodOptional<z.ZodArray<z.ZodEnum<{
25
+ pages: "pages";
26
+ ui: "ui";
27
+ api: "api";
28
+ mcp: "mcp";
29
+ worker: "worker";
30
+ store: "store";
31
+ }>>>;
24
32
  version: z.ZodString;
25
33
  commit: z.ZodString;
26
34
  buildTime: z.ZodISODateTime;
35
+ clockRate: z.ZodOptional<z.ZodNumber>;
27
36
  instance: z.ZodString;
28
37
  uptimeSeconds: z.ZodInt;
29
38
  checkedAt: z.ZodISODateTime;
@@ -9,9 +9,12 @@ export const HealthSchema = z.strictObject({
9
9
  status: HealthStatusSchema,
10
10
  extension: ExtensionIdSchema,
11
11
  part: DeployedPartKindSchema,
12
+ // A host process that runs several parts (the daemon's child, the one container) lists them.
13
+ parts: z.array(DeployedPartKindSchema).optional(),
12
14
  version: VersionSchema,
13
15
  commit: z.string().regex(/^[0-9a-f]{7,40}$/),
14
16
  buildTime: z.iso.datetime(),
17
+ clockRate: z.number().optional(),
15
18
  instance: z.string().regex(/^[0-9a-f]{8,32}$/),
16
19
  uptimeSeconds: z.int().min(0),
17
20
  checkedAt: z.iso.datetime(),
@@ -0,0 +1 @@
1
+ export declare const startHostClock: (env: Record<string, string | undefined>) => number;
@@ -0,0 +1,12 @@
1
+ import { createLog } from '../log/log.js';
2
+ import { CLOCK_RATE_ENV, parseClockRate, setHostClockRate } from '../worker/clock.js';
3
+ // Only the kit host child reads the test clock from env; a bad value stops the boot.
4
+ export const startHostClock = (env) => {
5
+ const rate = parseClockRate(env[CLOCK_RATE_ENV]);
6
+ setHostClockRate(rate);
7
+ if (rate !== 1) {
8
+ const log = createLog({ extension: 'host', part: 'api' });
9
+ log.warn('test clock on: job times run faster, for tests only', { clockRate: rate });
10
+ }
11
+ return rate;
12
+ };
@@ -1,4 +1,7 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { rm } from 'node:fs/promises';
1
3
  import { isAbsolute } from 'node:path';
4
+ import { validRange } from 'semver';
2
5
  import { z } from 'zod';
3
6
  import { fail } from '../../envelope/envelope.js';
4
7
  import { parse } from '../../envelope/parse.js';
@@ -7,13 +10,18 @@ import { readManifest } from '../../manifest/read-manifest.js';
7
10
  import { persist, summary } from './entries.js';
8
11
  import { runInstaller } from './installer-call.js';
9
12
  import {} from './installation.js';
10
- import { startEntry } from './supervisor.js';
13
+ import { clearRunDir, dataDirOf } from './daemon-files.js';
14
+ import { needsSecret } from './start-checks.js';
15
+ import { startEntry, startFailed } from './supervisor.js';
11
16
  const RESERVED_ID = 'host';
17
+ // The cli's rule for what follows `<id>@`: a version, a range or a dist-tag; never a path, URL or flag.
18
+ const DIST_TAG = /^[A-Za-z][\w.-]*$/;
19
+ const isVersionSpec = (spec) => !/\s/.test(spec) && (validRange(spec) !== null || DIST_TAG.test(spec));
12
20
  // enabled: false records the extension and never starts it (a profile "off" entry).
13
21
  const AddSchema = z.union([
14
22
  z.strictObject({
15
23
  id: ExtensionIdSchema,
16
- version: z.string().min(1).optional(),
24
+ version: z.string().min(1).refine(isVersionSpec, 'a version, a range or a dist-tag').optional(),
17
25
  enabled: z.boolean().optional(),
18
26
  }),
19
27
  z.strictObject({
@@ -45,7 +53,24 @@ const marketEntry = async (deps, entries, id, version) => {
45
53
  const got = await runInstaller(deps, { id, version });
46
54
  return { install: { id: got.id, version: got.version }, dir: got.dir, version: got.version };
47
55
  };
48
- // POST: installs (or links a folder), records it, then starts it; a failed start stays listed as failed.
56
+ // C6: a new id that did not start leaves no row; only a data folder this start made goes too.
57
+ const rollBack = async (deps, entries, entry, fresh) => {
58
+ entries.delete(entry.id);
59
+ await persist(deps, entry.id);
60
+ await clearRunDir(deps.configDir, entry.id);
61
+ if (fresh)
62
+ await rm(dataDirOf(deps.configDir, entry.id), { recursive: true, force: true });
63
+ };
64
+ // The first start; refused and rolled back unless it waits for a secret or the daemon stops (kept).
65
+ const firstStart = async (deps, entries, entry) => {
66
+ const fresh = !existsSync(dataDirOf(deps.configDir, entry.id));
67
+ const err = await startEntry(deps, entry);
68
+ if (!err || needsSecret(err) || deps.stopping.signal.aborted)
69
+ return;
70
+ await rollBack(deps, entries, entry, fresh);
71
+ throw startFailed(entry, err);
72
+ };
73
+ // POST: installs (or links a folder), records it, then starts it (C6: a failed start is refused).
49
74
  export const addExtension = async (deps, entries, body) => {
50
75
  const spec = parse(AddSchema, body, 'Invalid body');
51
76
  const got = 'source' in spec
@@ -58,6 +83,6 @@ export const addExtension = async (deps, entries, body) => {
58
83
  const entry = { ...got, id: install.id, install, state: 'disabled' };
59
84
  entries.set(entry.id, entry);
60
85
  if (!off)
61
- await startEntry(deps, entry);
86
+ await firstStart(deps, entries, entry);
62
87
  return summary(entry);
63
88
  };
@@ -0,0 +1,20 @@
1
+ interface RunSpec {
2
+ id: string;
3
+ dir: string;
4
+ dataDir: string;
5
+ secrets: Record<string, string>;
6
+ }
7
+ export interface RunFolders {
8
+ runDir: string;
9
+ secretsDir: string;
10
+ tmpDir: string;
11
+ made: {
12
+ run: boolean;
13
+ data: boolean;
14
+ };
15
+ }
16
+ export declare const runDirFor: (spec: Pick<RunSpec, "id" | "dataDir">) => string;
17
+ export declare const makeRun: (spec: RunSpec) => Promise<RunFolders>;
18
+ export declare const fillRun: (run: RunFolders, spec: RunSpec) => Promise<void>;
19
+ export declare const undoRun: ({ runDir, made }: RunFolders, dataDir: string) => Promise<void>;
20
+ export {};
@@ -0,0 +1,45 @@
1
+ import { mkdir, rm, rmdir, writeFile } from 'node:fs/promises';
2
+ import { dirname, join } from 'node:path';
3
+ import { secretNames } from '../../manifest/parts.js';
4
+ import { SecretNameSchema } from '../../manifest/primitives.schema.js';
5
+ import { readManifest } from '../../manifest/read-manifest.js';
6
+ import { clearOldLock } from '../data-lock.js';
7
+ import { runDirOf } from './daemon-files.js';
8
+ import { clearRunLock } from './run-lock.js';
9
+ // The supervisor's dataDir is <configDir>/data/{id}, so run/{id} sits beside data/ (C2).
10
+ export const runDirFor = (spec) => runDirOf(dirname(dirname(spec.dataDir)), spec.id);
11
+ // Only the names the package declares now: a row can still hold one an older version declared.
12
+ const declared = async (spec) => {
13
+ const names = new Set(secretNames(await readManifest(spec.dir)));
14
+ return Object.entries(spec.secrets).filter(([name]) => names.has(name));
15
+ };
16
+ // The folders first, so undoRun knows what this launch made; data/{id} before the fork (PGlite).
17
+ export const makeRun = async (spec) => {
18
+ const runDir = runDirFor(spec);
19
+ const run = await mkdir(runDir, { recursive: true, mode: 0o700 });
20
+ const data = await mkdir(spec.dataDir, { recursive: true }).catch(async (err) => {
21
+ if (run !== undefined)
22
+ await rm(runDir, { recursive: true, force: true });
23
+ throw err;
24
+ });
25
+ const made = { run: run !== undefined, data: data !== undefined };
26
+ return { runDir, secretsDir: join(runDir, 'secrets'), tmpDir: join(runDir, 'tmp'), made };
27
+ };
28
+ // Fresh secrets and tmp; the old lock beside data/{id} and a left-over run lock are cleared.
29
+ export const fillRun = async (run, spec) => {
30
+ for (const dir of [run.secretsDir, run.tmpDir]) {
31
+ await rm(dir, { recursive: true, force: true });
32
+ await mkdir(dir, { mode: 0o700 });
33
+ }
34
+ await clearOldLock(`${spec.dataDir}.lock`);
35
+ await clearRunLock(join(run.runDir, 'store.lock'), run.runDir);
36
+ for (const [name, value] of await declared(spec))
37
+ await writeFile(join(run.secretsDir, SecretNameSchema.parse(name)), value, { mode: 0o600 });
38
+ };
39
+ // A child that never reported its port: what this launch made goes; data/{id} only while empty.
40
+ export const undoRun = async ({ runDir, made }, dataDir) => {
41
+ if (made.run)
42
+ await rm(runDir, { recursive: true, force: true });
43
+ if (made.data)
44
+ await rmdir(dataDir).catch(() => undefined);
45
+ };
@@ -1,3 +1,4 @@
1
+ import { type Seal } from './seal.js';
1
2
  interface LaunchSpec {
2
3
  id: string;
3
4
  dir: string;
@@ -10,6 +11,7 @@ interface LaunchSpec {
10
11
  export interface Exit {
11
12
  code: number | null;
12
13
  signal: string | null;
14
+ words?: string;
13
15
  }
14
16
  export interface Child {
15
17
  port: number;
@@ -17,7 +19,11 @@ export interface Child {
17
19
  exited: Promise<Exit>;
18
20
  stop(): Promise<void>;
19
21
  }
20
- export type Launch = (spec: LaunchSpec) => Promise<Child>;
21
- export declare const childEnv: (spec: LaunchSpec, secretsDir: string) => Record<string, string>;
22
- export declare const forkLaunch: (main?: string, startMs?: number) => Launch;
23
- export {};
22
+ export type Launch = ((spec: LaunchSpec) => Promise<Child>) & {
23
+ clockRate?: number;
24
+ seal?: Seal;
25
+ node?: string;
26
+ };
27
+ export declare const childEnv: (spec: LaunchSpec, secretsDir: string, runDir?: string) => Record<string, string>;
28
+ export { lastWords } from './last-words.js';
29
+ export declare const forkLaunch: (main?: string, startMs?: number, rate?: number, node?: string) => Launch;
@@ -1,55 +1,47 @@
1
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';
2
+ import { rm } from 'node:fs/promises';
3
+ import { dirname } from 'node:path';
5
4
  import { fileURLToPath } from 'node:url';
6
- import { SecretNameSchema } from '../../manifest/primitives.schema.js';
5
+ import { CLOCK_RATE_ENV, parseClockRate } from '../../worker/clock.js';
6
+ import { fillRun, makeRun, undoRun } from './child-files.js';
7
+ import { lastWords } from './last-words.js';
7
8
  import { LIMITS } from './limits.js';
9
+ import { pipeRedacted } from './redact-stream.js';
10
+ import { permissionFlag, sealFlags, sealOf } from './seal.js';
8
11
  const HOST_MAIN = fileURLToPath(new URL('../main.js', import.meta.url));
9
12
  const STOP_MS = 5_000;
10
13
  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
14
  // What dist/host/main.js reads (docs/part-image.md), on a port the OS picks.
19
- export const childEnv = (spec, secretsDir) => ({
15
+ export const childEnv = (spec, secretsDir, runDir) => ({
20
16
  PORT: '0',
21
17
  AGENTAGE_EXTENSION_DIR: spec.dir,
22
18
  AGENTAGE_DATA_DIR: spec.dataDir,
23
19
  AGENTAGE_SETTINGS: JSON.stringify(spec.settings),
24
20
  AGENTAGE_SECRETS_DIR: secretsDir,
25
21
  AGENTAGE_ORIGIN: spec.origin,
22
+ ...(runDir && { AGENTAGE_RUN_DIR: runDir }),
26
23
  ...(spec.storeOpenMs && { AGENTAGE_STORE_OPEN_MS: String(spec.storeOpenMs) }),
27
24
  });
25
+ export { lastWords } from './last-words.js';
28
26
  const passedEnv = () => Object.fromEntries(PASSED.flatMap((k) => (process.env[k] ? [[k, process.env[k]]] : [])));
29
- // The child's last stderr line, its msg when it is a log row: why it did not start.
30
- const lastWords = (tail, how) => {
31
- const lines = tail
32
- .trim()
33
- .split('\n')
34
- .filter((l) => !/^Node\.js v\d/.test(l));
35
- const line = lines.at(-1) ?? '';
36
- try {
37
- const msg = String(JSON.parse(line).msg ?? line);
38
- return msg.replace(/^[A-Za-z]*Error: /, '');
39
- }
40
- catch {
41
- return line || `exited with ${how.signal ? `signal ${how.signal}` : `code ${how.code}`}`;
42
- }
43
- };
44
- const captured = (child) => {
27
+ const captured = (child, secrets) => {
45
28
  let tail = '';
46
- child.stdout?.pipe(process.stdout);
47
- child.stderr?.on('data', (chunk) => {
48
- process.stderr.write(chunk);
49
- tail = (tail + chunk.toString()).slice(-4000);
50
- });
29
+ pipeRedacted(child.stdout, process.stdout, secrets);
30
+ pipeRedacted(child.stderr, process.stderr, secrets);
31
+ child.stderr?.on('data', (chunk) => (tail = (tail + chunk.toString()).slice(-4000)));
51
32
  return () => tail;
52
33
  };
34
+ // 'exit' can come before the last stderr chunk: wait for the stream end, at most 500 ms.
35
+ const flushed = (child) => new Promise((resolve) => {
36
+ if (!child.stderr || child.stderr.readableEnded)
37
+ return resolve();
38
+ child.stderr.once('end', resolve);
39
+ setTimeout(resolve, 500).unref();
40
+ });
41
+ const exitOf = (child, tail) => new Promise((resolve) => child.once('exit', (code, signal) => {
42
+ const how = { code, signal };
43
+ void flushed(child).then(() => resolve({ ...how, words: lastWords(tail(), how) }));
44
+ }));
53
45
  const portOf = (msg) => {
54
46
  const { type, port } = (msg ?? {});
55
47
  return type === 'ready' && typeof port === 'number' ? port : undefined;
@@ -82,19 +74,52 @@ const stopOf = (child, exited) => async () => {
82
74
  await exited;
83
75
  clearTimeout(kill);
84
76
  };
85
- // One child process per extension: node dist/host/main.js on a port the OS picks.
86
- export const forkLaunch = (main = HOST_MAIN, startMs = LIMITS.startMs) => async (spec) => {
87
- const secretsDir = await secretFiles(spec);
77
+ // The daemon's own node flags (a loader, --input-type) are never the child's; C2 where Node has --permission.
78
+ const execArgvOf = (node, main, spec, run) => {
79
+ if (!permissionFlag(node))
80
+ return [];
81
+ const configDir = dirname(dirname(spec.dataDir));
82
+ const { id, dir, dataDir } = spec;
83
+ return sealFlags({ id, main, dir, configDir, runDir: run.runDir, dataDir });
84
+ };
85
+ // The listed env of the daemon, then the child's own: TMPDIR in run/{id}, the test clock when not 1.
86
+ const envOf = (spec, run, clockRate) => ({
87
+ ...passedEnv(),
88
+ ...childEnv(spec, run.secretsDir, run.runDir),
89
+ TMPDIR: run.tmpDir,
90
+ ...(clockRate === 1 ? {} : { [CLOCK_RATE_ENV]: String(clockRate) }),
91
+ });
92
+ const started = async (at, spec, run) => {
93
+ const execArgv = execArgvOf(at.node, at.main, spec, run);
94
+ await fillRun(run, spec);
88
95
  const stdio = ['ignore', 'pipe', 'pipe', 'ipc'];
89
- // execArgv []: the daemon's own node flags (a loader, --input-type) are not the child's.
90
- const env = { ...passedEnv(), ...childEnv(spec, secretsDir) };
91
- const child = fork(main, [], { env, execArgv: [], stdio: [...stdio] });
92
- const exited = new Promise((resolve) => child.once('exit', (code, signal) => resolve({ code, signal })));
96
+ const child = fork(at.main, [], {
97
+ env: envOf(spec, run, at.clockRate),
98
+ execArgv,
99
+ stdio: [...stdio],
100
+ });
101
+ const tail = captured(child, spec.secrets);
102
+ const exited = exitOf(child, tail);
103
+ const port = await readyOf(child, tail, at.startMs);
104
+ return { port, pid: child.pid ?? 0, exited, stop: stopOf(child, exited) };
105
+ };
106
+ // Anything before the port (files, the seal check, the start) undoes the folders this launch made.
107
+ const launchAt = (at) => async (spec) => {
108
+ const run = await makeRun(spec);
93
109
  try {
94
- const port = await readyOf(child, captured(child), startMs);
95
- return { port, pid: child.pid ?? 0, exited, stop: stopOf(child, exited) };
110
+ return await started(at, spec, run);
111
+ }
112
+ catch (err) {
113
+ await undoRun(run, spec.dataDir);
114
+ throw err;
96
115
  }
97
116
  finally {
98
- await rm(secretsDir, { recursive: true, force: true });
117
+ await rm(run.secretsDir, { recursive: true, force: true });
99
118
  }
100
119
  };
120
+ // One child process per extension on a port the OS picks; node: the version the seal gate reads.
121
+ export const forkLaunch = (main = HOST_MAIN, startMs = LIMITS.startMs, rate, node = process.versions.node) => {
122
+ const clockRate = parseClockRate(rate);
123
+ const launch = launchAt({ main, startMs, clockRate, node });
124
+ return Object.assign(launch, { clockRate, seal: sealOf(node), node });
125
+ };
@@ -5,10 +5,13 @@ interface DaemonFile {
5
5
  version: string;
6
6
  protocol: number;
7
7
  startedBy: string;
8
+ hostToken: string;
8
9
  }
9
10
  export declare const writeDaemonFile: (configDir: string, file: DaemonFile) => Promise<void>;
10
11
  export declare const removeDaemonFile: (configDir: string) => Promise<void>;
11
12
  export declare const dataDirOf: (configDir: string, id: string) => string;
13
+ export declare const runDirOf: (configDir: string, id: string) => string;
14
+ export declare const clearRunDir: (configDir: string, id: string) => Promise<void>;
12
15
  export declare const purgeData: (configDir: string, id: string) => Promise<void>;
13
16
  type ValueKind = 'settings' | 'secrets';
14
17
  type Values = Record<string, unknown>;