@agentage/extension 0.4.3 → 0.5.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 (53) hide show
  1. package/dist/context/context.d.ts +5 -0
  2. package/dist/context/context.js +7 -1
  3. package/dist/context/secrets.d.ts +5 -0
  4. package/dist/context/secrets.js +15 -0
  5. package/dist/context/test-context.d.ts +8 -0
  6. package/dist/context/test-context.js +10 -2
  7. package/dist/discovery/discovery.d.ts +2 -1
  8. package/dist/discovery/discovery.js +4 -1
  9. package/dist/discovery/discovery.schema.d.ts +3 -2
  10. package/dist/discovery/discovery.schema.js +3 -2
  11. package/dist/index.d.ts +4 -2
  12. package/dist/index.js +2 -0
  13. package/dist/log/log.js +2 -1
  14. package/dist/manifest/manifest.schema.d.ts +4 -4
  15. package/dist/manifest/manifest.schema.js +3 -1
  16. package/dist/manifest/parts.d.ts +3 -1
  17. package/dist/manifest/parts.js +8 -2
  18. package/dist/manifest/primitives.schema.d.ts +14 -2
  19. package/dist/manifest/primitives.schema.js +8 -1
  20. package/dist/mcp/snapshot.d.ts +3 -0
  21. package/dist/mcp/snapshot.js +7 -0
  22. package/dist/runtime/part-runners.js +2 -2
  23. package/dist/runtime/run-part.d.ts +1 -0
  24. package/dist/runtime/run-part.js +7 -3
  25. package/dist/testing/test-server.d.ts +4 -1
  26. package/dist/testing/test-server.js +5 -2
  27. package/dist/tool/check.d.ts +1 -0
  28. package/dist/tool/check.js +6 -3
  29. package/dist/tool/contracts.d.ts +1 -0
  30. package/dist/tool/contracts.js +48 -0
  31. package/dist/tool/index.d.ts +1 -0
  32. package/dist/tool/index.js +1 -0
  33. package/dist/tool/record-extras.js +2 -2
  34. package/dist/tool/rules/folders.d.ts +4 -0
  35. package/dist/tool/rules/folders.js +38 -0
  36. package/dist/tool/rules/sealing.js +3 -1
  37. package/dist/tool/rules/store.js +8 -2
  38. package/dist/tool/rules/surface.d.ts +4 -0
  39. package/dist/tool/rules/surface.js +9 -5
  40. package/dist/tool/stage.js +2 -2
  41. package/dist/tool/up/compose.d.ts +15 -0
  42. package/dist/tool/up/compose.js +11 -6
  43. package/dist/tool/up/down.js +2 -0
  44. package/dist/tool/up/health.d.ts +3 -0
  45. package/dist/tool/up/health.js +40 -0
  46. package/dist/tool/up/local-record.d.ts +2 -1
  47. package/dist/tool/up/secrets.d.ts +6 -0
  48. package/dist/tool/up/secrets.js +36 -0
  49. package/dist/tool/up/up.js +17 -9
  50. package/package.json +1 -1
  51. package/schemas/extension-discovery.schema.json +2 -2
  52. package/schemas/extension-package.schema.json +4 -4
  53. package/schemas/extension-record.schema.json +11 -2
@@ -1,7 +1,9 @@
1
1
  import { type Caller } from '../auth/token-check.js';
2
2
  import { type ExtensionPackage } from '../manifest/manifest.schema.js';
3
+ import { type StoreKind } from '../manifest/primitives.schema.js';
3
4
  import { type Log } from '../log/log.js';
4
5
  import { type Store } from '../store/store.types.js';
6
+ import { type Secrets } from './secrets.js';
5
7
  export type ServerPartKind = 'pages' | 'api' | 'mcp' | 'worker';
6
8
  export type SettingValue = string | number | boolean;
7
9
  export interface ExtensionInfo {
@@ -10,6 +12,7 @@ export interface ExtensionInfo {
10
12
  part: ServerPartKind;
11
13
  origin: string;
12
14
  commit: string;
15
+ store?: StoreKind;
13
16
  }
14
17
  export interface PartContext {
15
18
  readonly extension: Readonly<ExtensionInfo>;
@@ -19,6 +22,7 @@ export interface PartContext {
19
22
  readonly log: Log;
20
23
  readonly settings: Readonly<Record<string, SettingValue>>;
21
24
  readonly store: Store;
25
+ readonly secrets: Secrets;
22
26
  }
23
27
  export declare const NO_STORE: Store;
24
28
  export declare const settingDefaults: (pkg: ExtensionPackage) => Record<string, SettingValue>;
@@ -30,5 +34,6 @@ export interface ContextInput {
30
34
  log?: Log;
31
35
  settings?: Record<string, SettingValue>;
32
36
  store?: Store;
37
+ secrets?: Secrets;
33
38
  }
34
39
  export declare const createContext: (input: ContextInput) => PartContext;
@@ -1,7 +1,10 @@
1
1
  import { callerOf } from '../auth/token-check.js';
2
2
  import {} from '../manifest/manifest.schema.js';
3
+ import { storeOf } from '../manifest/parts.js';
4
+ import {} from '../manifest/primitives.schema.js';
3
5
  import { createLog } from '../log/log.js';
4
6
  import {} from '../store/store.types.js';
7
+ import {} from './secrets.js';
5
8
  // ctx.store is always there; without a store part in the manifest it says so on first use.
6
9
  export const NO_STORE = {
7
10
  query: async () => {
@@ -11,15 +14,18 @@ export const NO_STORE = {
11
14
  export const settingDefaults = (pkg) => Object.fromEntries(Object.entries(pkg.agentage.settings ?? {}).map(([key, setting]) => [key, setting.default]));
12
15
  export const createContext = (input) => {
13
16
  const { pkg, part, origin, commit, store } = input;
17
+ const kind = storeOf(pkg);
14
18
  const extension = Object.freeze({
15
19
  id: pkg.agentage.id,
16
20
  version: pkg.version,
17
21
  part,
18
22
  origin,
19
23
  commit,
24
+ ...(kind && { store: kind }),
20
25
  });
21
26
  const log = input.log ?? createLog({ extension: pkg.agentage.id, part });
22
27
  const settings = Object.freeze({ ...settingDefaults(pkg), ...input.settings });
23
28
  const auth = Object.freeze({ caller: callerOf });
24
- return Object.freeze({ extension, auth, log, settings, store: store ?? NO_STORE });
29
+ const secrets = input.secrets ?? {};
30
+ return Object.freeze({ extension, auth, log, settings, store: store ?? NO_STORE, secrets });
25
31
  };
@@ -0,0 +1,5 @@
1
+ export interface Secrets {
2
+ }
3
+ 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>>>;
@@ -0,0 +1,15 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ export const SECRETS_DIR = '/run/secrets';
4
+ export const camelName = (name) => name.replace(/-([a-z0-9])/g, (_, c) => c.toUpperCase());
5
+ const valueOf = (file) => readFile(file, 'utf8').then((text) => text.replace(/\r?\n$/, ''), () => '');
6
+ // Each declared name from its mounted file; a missing or empty file stops the part, named, never valued.
7
+ export const readSecrets = async (names, dir, part) => {
8
+ const read = names.map(async (name) => [name, await valueOf(join(dir, name))]);
9
+ const pairs = await Promise.all(read);
10
+ const missing = pairs.find(([, value]) => value === '');
11
+ if (missing)
12
+ throw new Error(`${part} refused to start: secret ${missing[0]} has no value`);
13
+ const secrets = Object.fromEntries(pairs.map(([name, value]) => [camelName(name), value]));
14
+ return Object.freeze(secrets);
15
+ };
@@ -1,6 +1,7 @@
1
1
  import { type CliContext } from '../command/command.types.js';
2
2
  import { type LogFields, type LogLevel } from '../log/log.js';
3
3
  import { type ToolEntry, type ToolRegistrar } from '../mcp/tools.js';
4
+ import { type JobOptions } from '../worker/job-options.js';
4
5
  import { type JobRun } from '../worker/runs.js';
5
6
  import { type Schedule } from '../worker/scheduler.js';
6
7
  import { type ExtensionInfo, type PartContext, type SettingValue } from './context.js';
@@ -16,8 +17,14 @@ export interface TestContext extends PartContext {
16
17
  readonly schedule: Schedule;
17
18
  readonly tool: ToolRegistrar;
18
19
  readonly tools: ToolEntry[];
20
+ readonly jobs: ScheduledJob[];
19
21
  runJob(name: string): Promise<JobRun | undefined>;
20
22
  }
23
+ export interface ScheduledJob {
24
+ name: string;
25
+ cron: string;
26
+ options?: JobOptions;
27
+ }
21
28
  export interface TestCommandContext extends CliContext {
22
29
  readonly output: {
23
30
  stdout: string[];
@@ -28,6 +35,7 @@ export interface TestCommandContext extends CliContext {
28
35
  export interface TestContextOptions {
29
36
  extension?: Partial<ExtensionInfo>;
30
37
  settings?: Record<string, SettingValue>;
38
+ secrets?: Record<string, string>;
31
39
  store?: boolean | {
32
40
  dir: string;
33
41
  };
@@ -4,6 +4,7 @@ import { messageOf } from '../log/log.js';
4
4
  import { createToolRegistry } from '../mcp/tools.js';
5
5
  import { migrate } from '../store/migrations.js';
6
6
  import { createTestStore } from '../store/test-store.js';
7
+ import {} from '../worker/job-options.js';
7
8
  import { runLog } from '../worker/run-log.js';
8
9
  import { memoryRuns } from '../worker/runs.js';
9
10
  import { createScheduler } from '../worker/scheduler.js';
@@ -34,13 +35,19 @@ const TEST_EXTENSION = {
34
35
  // Jobs run by hand with runJob, tools recorded as the mcp part registers them.
35
36
  const recorders = (log) => {
36
37
  const scheduler = createScheduler({ runs: memoryRuns(), log });
37
- return { ...createToolRegistry(), schedule: scheduler.schedule, runJob: scheduler.run };
38
+ const jobs = [];
39
+ const schedule = (name, cron, job, options) => {
40
+ scheduler.schedule(name, cron, job, options);
41
+ jobs.push({ name, cron, options });
42
+ };
43
+ return { ...createToolRegistry(), schedule, jobs, runJob: scheduler.run };
38
44
  };
39
45
  const serverContext = (options) => {
40
46
  const logs = [];
41
47
  const log = runLog(recordingLog(logs));
42
48
  const store = testStore(options.store, recordingLog([]));
43
- const extension = { ...TEST_EXTENSION, ...options.extension };
49
+ const kind = options.store ? { store: 'postgres' } : {};
50
+ const extension = { ...TEST_EXTENSION, ...kind, ...options.extension };
44
51
  const caller = { sub: 'usr_test', scopes: [`${extension.id}:read`] };
45
52
  return {
46
53
  extension,
@@ -49,6 +56,7 @@ const serverContext = (options) => {
49
56
  logs,
50
57
  settings: { ...options.settings },
51
58
  store: store ?? NO_STORE,
59
+ secrets: Object.freeze({ ...options.secrets }),
52
60
  close: async () => store?.close(),
53
61
  ...recorders(log),
54
62
  };
@@ -41,10 +41,11 @@ export declare const discoveryDocument: (record: ExtensionRecord, host: string)
41
41
  image: string;
42
42
  } | undefined;
43
43
  store?: {
44
- kind: "postgres" | "git" | "signoz";
44
+ kind: "postgres" | "signoz" | "git";
45
45
  migrations?: number | undefined;
46
46
  } | undefined;
47
47
  };
48
+ secrets?: string[] | undefined;
48
49
  openapi?: string | undefined;
49
50
  tools?: {
50
51
  name: string;
@@ -15,7 +15,7 @@ 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 } = pkg.agentage;
18
+ const { id, commands, secrets } = pkg.agentage;
19
19
  const { commit, buildTime } = build;
20
20
  const parts = partsOf(pkg, images, extras.migrations);
21
21
  const record = { id, version: pkg.version, commit, buildTime, parts };
@@ -27,6 +27,8 @@ export const recordOf = (pkg, build, images, extras = {}) => {
27
27
  record.commands = commands.map((command) => command.name);
28
28
  if (extras.widgets)
29
29
  record.widgets = extras.widgets;
30
+ if (secrets?.length)
31
+ record.secrets = secrets;
30
32
  return record;
31
33
  };
32
34
  export const validateRecord = (value) => {
@@ -42,5 +44,6 @@ export const loadRecord = async (file) => {
42
44
  };
43
45
  export const discoveryDocument = (record, host) => {
44
46
  const { id, version, commit, buildTime, ...rest } = record;
47
+ delete rest.secrets;
45
48
  return { id, version, commit, buildTime, host, ...rest };
46
49
  };
@@ -6,6 +6,7 @@ export declare const WidgetSchema: z.ZodObject<{
6
6
  module: z.ZodString;
7
7
  }, z.core.$strict>;
8
8
  export declare const ExtensionRecordSchema: z.ZodObject<{
9
+ secrets: z.ZodOptional<z.ZodArray<z.ZodString>>;
9
10
  id: z.ZodString;
10
11
  version: z.ZodString;
11
12
  commit: z.ZodString;
@@ -29,8 +30,8 @@ export declare const ExtensionRecordSchema: z.ZodObject<{
29
30
  store: z.ZodOptional<z.ZodObject<{
30
31
  kind: z.ZodEnum<{
31
32
  postgres: "postgres";
32
- git: "git";
33
33
  signoz: "signoz";
34
+ git: "git";
34
35
  }>;
35
36
  migrations: z.ZodOptional<z.ZodInt>;
36
37
  }, z.core.$strict>>;
@@ -72,8 +73,8 @@ export declare const DiscoveryDocumentSchema: z.ZodObject<{
72
73
  store: z.ZodOptional<z.ZodObject<{
73
74
  kind: z.ZodEnum<{
74
75
  postgres: "postgres";
75
- git: "git";
76
76
  signoz: "signoz";
77
+ git: "git";
77
78
  }>;
78
79
  migrations: z.ZodOptional<z.ZodInt>;
79
80
  }, z.core.$strict>>;
@@ -1,5 +1,5 @@
1
1
  import { z } from 'zod';
2
- import { CommandNameSchema, CommitSchema, ExtensionIdSchema, IMAGE_PART_KINDS, PrefixedToolNameSchema, StoreKindSchema, VersionSchema, } from '../manifest/primitives.schema.js';
2
+ import { CommandNameSchema, CommitSchema, ExtensionIdSchema, IMAGE_PART_KINDS, PrefixedToolNameSchema, SecretNameSchema, 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()
@@ -53,8 +53,9 @@ const imagesNameTheirExtension = (doc) => IMAGE_PART_KINDS.every((kind) => {
53
53
  });
54
54
  const IMAGE_RULE = { message: 'every image is {id}-{part}', path: ['parts'] };
55
55
  // 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.
56
57
  export const ExtensionRecordSchema = z
57
- .strictObject(recordShape)
58
+ .strictObject({ ...recordShape, secrets: z.array(SecretNameSchema).min(1).optional() })
58
59
  .refine(imagesNameTheirExtension, IMAGE_RULE);
59
60
  // What a deployment serves at /.well-known/agentage-extension.json: the record plus its host.
60
61
  export const DiscoveryDocumentSchema = z
package/dist/index.d.ts CHANGED
@@ -2,7 +2,8 @@ export { type ArgValue } from './command/args.js';
2
2
  export { type CliContext, type CliCreate, type CommandExtension, type CommandHandler, } from './command/command.types.js';
3
3
  export { type Out } from './command/out.js';
4
4
  export { type ExtensionInfo, type PartContext, type ServerPartKind, type SettingValue, } from './context/context.js';
5
- export { createTestContext, type LogEntry, type TestCommandContext, type TestCommandOptions, type TestContext, type TestContextOptions, } from './context/test-context.js';
5
+ export { type Secrets } from './context/secrets.js';
6
+ export { createTestContext, type LogEntry, type ScheduledJob, type TestCommandContext, type TestCommandOptions, type TestContext, type TestContextOptions, } from './context/test-context.js';
6
7
  export { DiscoveryDocumentSchema, ExtensionRecordSchema, type DiscoveryDocument, type ExtensionRecord, } from './discovery/discovery.schema.js';
7
8
  export { AGCID_HEADER, isAgcid } from './agcid/agcid.js';
8
9
  export { ERROR_CODES, ERROR_STATUS, type ErrorCode } from './envelope/codes.js';
@@ -13,13 +14,14 @@ export { HealthSchema, type HealthBody, type HealthStatus } from './health/healt
13
14
  export { type Log, type LogFields } from './log/log.js';
14
15
  export { PackageSchema, type CommandSpec, type ExtensionPackage, } from './manifest/manifest.schema.js';
15
16
  export { imageParts } from './manifest/parts.js';
17
+ export { SERVED_KINDS, STORE_KINDS, type StoreKind } from './manifest/primitives.schema.js';
16
18
  export { readManifest, validateManifest } from './manifest/read-manifest.js';
17
19
  export { canonical, mcpSnapshot, PROTOCOL_VERSIONS, type McpSnapshot, type ProtocolVersion, } from './mcp/snapshot.js';
18
20
  export { type McpContext, type ToolHandler, type ToolRegistrar, type ToolSpec, } from './mcp/tools.js';
19
21
  export { versionPage, type PagesContext, type PagesSite } from './pages/pages.js';
20
22
  export { type ApiCreate, type ApiHandler, type ApiPart } from './server/part.types.js';
21
23
  export { type QueryResult, type Row, type Store } from './store/store.types.js';
22
- export { startTestMcp, startTestServer, type TestMcpOptions, type TestServer, type TestServerOptions, } from './testing/test-server.js';
24
+ export { startTestMcp, startTestServer, type TestMcp, type TestMcpOptions, type TestServer, type TestServerOptions, } from './testing/test-server.js';
23
25
  export { type JobOptions } from './worker/job-options.js';
24
26
  export { type JobRun, type RunStatus } from './worker/runs.js';
25
27
  export { type Job, type Schedule } from './worker/scheduler.js';
package/dist/index.js CHANGED
@@ -2,6 +2,7 @@ export {} from './command/args.js';
2
2
  export {} from './command/command.types.js';
3
3
  export {} from './command/out.js';
4
4
  export {} from './context/context.js';
5
+ export {} from './context/secrets.js';
5
6
  export { createTestContext, } from './context/test-context.js';
6
7
  export { DiscoveryDocumentSchema, ExtensionRecordSchema, } from './discovery/discovery.schema.js';
7
8
  export { AGCID_HEADER, isAgcid } from './agcid/agcid.js';
@@ -13,6 +14,7 @@ export { HealthSchema } from './health/health.schema.js';
13
14
  export {} from './log/log.js';
14
15
  export { PackageSchema, } from './manifest/manifest.schema.js';
15
16
  export { imageParts } from './manifest/parts.js';
17
+ export { SERVED_KINDS, STORE_KINDS } from './manifest/primitives.schema.js';
16
18
  export { readManifest, validateManifest } from './manifest/read-manifest.js';
17
19
  export { canonical, mcpSnapshot, PROTOCOL_VERSIONS, } from './mcp/snapshot.js';
18
20
  export {} from './mcp/tools.js';
package/dist/log/log.js CHANGED
@@ -8,7 +8,8 @@ const errorFields = (error) => {
8
8
  // Spread twice: the key order stays, and a field never overwrites time, level, msg, tags or agcid.
9
9
  const line = (level, message, tags, fields) => {
10
10
  const agcid = currentAgcid();
11
- const own = { time: new Date().toISOString(), level, msg: message, ...tags };
11
+ const ids = { 'extension.id': tags.extension, 'extension.part': tags.part };
12
+ const own = { time: new Date().toISOString(), level, msg: message, ...ids };
12
13
  const fixed = agcid ? { ...own, agcid } : own;
13
14
  return `${JSON.stringify({ ...fixed, ...fields, ...fixed })}\n`;
14
15
  };
@@ -23,13 +23,13 @@ declare const PartsSchema: z.ZodObject<{
23
23
  }, z.core.$strict>]>>;
24
24
  store: z.ZodOptional<z.ZodUnion<readonly [z.ZodEnum<{
25
25
  postgres: "postgres";
26
- git: "git";
27
26
  signoz: "signoz";
27
+ git: "git";
28
28
  }>, z.ZodObject<{
29
29
  kind: z.ZodEnum<{
30
30
  postgres: "postgres";
31
- git: "git";
32
31
  signoz: "signoz";
32
+ git: "git";
33
33
  }>;
34
34
  }, z.core.$strict>]>>;
35
35
  }, z.core.$strict>;
@@ -77,13 +77,13 @@ export declare const PackageSchema: z.ZodObject<{
77
77
  }, z.core.$strict>]>>;
78
78
  store: z.ZodOptional<z.ZodUnion<readonly [z.ZodEnum<{
79
79
  postgres: "postgres";
80
- git: "git";
81
80
  signoz: "signoz";
81
+ git: "git";
82
82
  }>, z.ZodObject<{
83
83
  kind: z.ZodEnum<{
84
84
  postgres: "postgres";
85
- git: "git";
86
85
  signoz: "signoz";
86
+ git: "git";
87
87
  }>;
88
88
  }, z.core.$strict>]>>;
89
89
  }, z.core.$strict>;
@@ -4,7 +4,9 @@ const CodePartSchema = z.union([
4
4
  z.boolean(),
5
5
  z.strictObject({ entry: PackagePathSchema.optional() }),
6
6
  ]);
7
- const StorePartSchema = z.union([StoreKindSchema, z.strictObject({ kind: StoreKindSchema })]);
7
+ const StorePartSchema = z.union([StoreKindSchema, z.strictObject({ kind: StoreKindSchema })], {
8
+ error: `one of ${StoreKindSchema.options.join(', ')}`,
9
+ });
8
10
  const ROUTED = ['pages', 'ui', 'api', 'mcp'];
9
11
  const PartsSchema = z
10
12
  .strictObject({
@@ -9,4 +9,6 @@ export interface NormalizedParts {
9
9
  export declare const normalizeParts: (parts: Parts) => NormalizedParts;
10
10
  export declare const imageParts: (pkg: ExtensionPackage) => ImagePartKind[];
11
11
  export declare const entryOf: (pkg: ExtensionPackage, part: ImagePartKind | "cli") => string;
12
- export declare const hasPostgres: (pkg: ExtensionPackage) => boolean;
12
+ export declare const storeOf: (pkg: ExtensionPackage) => StoreKind | undefined;
13
+ export declare const hasStore: (pkg: ExtensionPackage, kind: StoreKind) => boolean;
14
+ export declare const migratesStore: (pkg: ExtensionPackage) => boolean;
@@ -1,5 +1,5 @@
1
1
  import {} from './manifest.schema.js';
2
- import { IMAGE_PART_KINDS } from './primitives.schema.js';
2
+ import { IMAGE_PART_KINDS, STORE_KINDS, } from './primitives.schema.js';
3
3
  const normalizeCode = (part) => {
4
4
  if (part === undefined || part === false)
5
5
  return undefined;
@@ -22,4 +22,10 @@ export const imageParts = (pkg) => {
22
22
  return IMAGE_PART_KINDS.filter((kind) => code[kind] !== undefined);
23
23
  };
24
24
  export const entryOf = (pkg, part) => normalizeParts(pkg.agentage.parts).code[part]?.entry ?? `./dist/${part}/index.js`;
25
- export const hasPostgres = (pkg) => normalizeParts(pkg.agentage.parts).store === 'postgres';
25
+ export const storeOf = (pkg) => normalizeParts(pkg.agentage.parts).store;
26
+ export const hasStore = (pkg, kind) => storeOf(pkg) === kind;
27
+ // The migrate rule: the api image carries migrations/ and a migrate job only for such a kind.
28
+ export const migratesStore = (pkg) => {
29
+ const kind = storeOf(pkg);
30
+ return kind !== undefined && STORE_KINDS[kind].migrations;
31
+ };
@@ -8,14 +8,26 @@ export declare const CommandNameSchema: z.ZodString;
8
8
  export declare const SettingKeySchema: z.ZodString;
9
9
  export declare const SecretNameSchema: z.ZodString;
10
10
  export declare const PackagePathSchema: z.ZodString;
11
+ export declare const STORE_KINDS: {
12
+ readonly postgres: {
13
+ readonly migrations: true;
14
+ };
15
+ readonly signoz: {
16
+ readonly migrations: false;
17
+ };
18
+ readonly git: {
19
+ readonly migrations: false;
20
+ };
21
+ };
22
+ export declare const SERVED_KINDS: readonly StoreKind[];
11
23
  export declare const StoreKindSchema: z.ZodEnum<{
12
24
  postgres: "postgres";
13
- git: "git";
14
25
  signoz: "signoz";
26
+ git: "git";
15
27
  }>;
16
28
  export declare const FULL_SHA: RegExp;
17
29
  export declare const CommitSchema: z.ZodString;
18
30
  export declare const PrefixedToolNameSchema: z.ZodString;
19
31
  export declare const IMAGE_PART_KINDS: readonly ["pages", "ui", "api", "mcp", "worker"];
20
32
  export type ImagePartKind = (typeof IMAGE_PART_KINDS)[number];
21
- export type StoreKind = z.infer<typeof StoreKindSchema>;
33
+ export type StoreKind = keyof typeof STORE_KINDS;
@@ -44,7 +44,14 @@ export const PackagePathSchema = z
44
44
  .string()
45
45
  .max(256)
46
46
  .regex(/^\.\/[A-Za-z0-9._/-]+$/);
47
- export const StoreKindSchema = z.enum(['postgres', 'git', 'signoz']);
47
+ export const STORE_KINDS = {
48
+ postgres: { migrations: true },
49
+ signoz: { migrations: false },
50
+ git: { migrations: false },
51
+ };
52
+ // STORE_KINDS[kind].migrations: the api image carries a migrate job. SERVED_KINDS moves with the estate.
53
+ export const SERVED_KINDS = ['postgres', 'signoz'];
54
+ export const StoreKindSchema = z.enum(Object.keys(STORE_KINDS));
48
55
  export const FULL_SHA = /^[0-9a-f]{40}$/;
49
56
  export const CommitSchema = z.string().regex(FULL_SHA, { message: 'full 40-hex git sha' });
50
57
  export const PrefixedToolNameSchema = z
@@ -7,5 +7,8 @@ export interface McpSnapshot {
7
7
  };
8
8
  tools: Record<string, unknown>[];
9
9
  }
10
+ type Json = Record<string, unknown>;
10
11
  export declare const canonical: (value: unknown) => unknown;
11
12
  export declare const mcpSnapshot: (url: string, version: ProtocolVersion) => Promise<McpSnapshot>;
13
+ export declare const callTool: (url: string, name: string, args: Json) => Promise<unknown>;
14
+ export {};
@@ -67,3 +67,10 @@ export const mcpSnapshot = async (url, version) => {
67
67
  tools: listed['tools'],
68
68
  });
69
69
  };
70
+ // One tools/call as a stateless 2025-11-25 client sends it: the structured result, or a tool error thrown.
71
+ export const callTool = async (url, name, args) => {
72
+ const result = await post(url, '2025-11-25', 'tools/call', { name, arguments: args });
73
+ if (result['isError'])
74
+ throw new Error(`tool ${name}: ${JSON.stringify(result['content'])}`);
75
+ return result['structuredContent'];
76
+ };
@@ -3,7 +3,7 @@ import {} from 'express';
3
3
  import {} from '../context/context.js';
4
4
  import {} from '../manifest/manifest.schema.js';
5
5
  import { loadCreate } from '../manifest/entry.js';
6
- import { hasPostgres } from '../manifest/parts.js';
6
+ import { hasStore } from '../manifest/parts.js';
7
7
  import {} from '../manifest/primitives.schema.js';
8
8
  import { createMcpApp } from '../mcp/mcp-app.js';
9
9
  import { createToolRegistry } from '../mcp/tools.js';
@@ -42,7 +42,7 @@ const ui = async (input) => ({
42
42
  const worker = async (input) => {
43
43
  const ctx = input.ctx();
44
44
  const log = runLog(ctx.log);
45
- const runs = hasPostgres(input.pkg) ? storeRuns(ctx.store) : memoryRuns();
45
+ const runs = hasStore(input.pkg, 'postgres') ? storeRuns(ctx.store) : memoryRuns();
46
46
  const scheduler = createScheduler({ runs, log });
47
47
  await callCreate(input, 'worker', { ...ctx, log, schedule: scheduler.schedule });
48
48
  const checks = { ...input.base.checks, ...scheduler.checks() };
@@ -9,6 +9,7 @@ export interface RunPartOptions {
9
9
  part: string;
10
10
  env: Env;
11
11
  importModule?: ImportModule;
12
+ secretsDir?: string;
12
13
  serve?: Pick<ServeOptions, 'signals' | 'exit'>;
13
14
  }
14
15
  export declare const partOf: (pkg: ExtensionPackage, part: string) => ImagePartKind;
@@ -1,5 +1,6 @@
1
1
  import {} from 'node:http';
2
2
  import { createContext } from '../context/context.js';
3
+ import { readSecrets, SECRETS_DIR } from '../context/secrets.js';
3
4
  import { settingsFromEnv } from '../context/settings.js';
4
5
  import { DEFAULT_RECORD_FILE, loadRecord } from '../discovery/discovery.js';
5
6
  import {} from '../discovery/discovery.schema.js';
@@ -8,7 +9,7 @@ import { readOpenapi } from '../discovery/openapi.js';
8
9
  import { createLog } from '../log/log.js';
9
10
  import {} from '../manifest/entry.js';
10
11
  import {} from '../manifest/manifest.schema.js';
11
- import { hasPostgres, imageParts } from '../manifest/parts.js';
12
+ import { hasStore, imageParts } from '../manifest/parts.js';
12
13
  import {} from '../manifest/primitives.schema.js';
13
14
  import { readManifest } from '../manifest/read-manifest.js';
14
15
  import {} from '../server/app.js';
@@ -31,7 +32,7 @@ export const partOf = (pkg, part) => {
31
32
  return part;
32
33
  };
33
34
  // ui serves files and gets no ctx; every other part gets the store when the manifest has postgres.
34
- const storeFor = ({ pkg, part, env, log }) => part !== 'ui' && hasPostgres(pkg) ? createStore(env, log) : undefined;
35
+ const storeFor = ({ pkg, part, env, log }) => part !== 'ui' && hasStore(pkg, 'postgres') ? createStore(env, log) : undefined;
35
36
  const contextFor = (start, part, store) => createContext({
36
37
  pkg: start.pkg,
37
38
  part,
@@ -40,6 +41,7 @@ const contextFor = (start, part, store) => createContext({
40
41
  log: start.log,
41
42
  settings: settingsFromEnv(start.pkg, start.env, start.log),
42
43
  store,
44
+ secrets: start.secrets,
43
45
  });
44
46
  // Built on first use, so the ui runner, which never asks, has no ctx at all.
45
47
  const lazyContext = (start, store) => {
@@ -88,7 +90,9 @@ export const runPart = async (options) => {
88
90
  const pkg = await readManifest(options.dir);
89
91
  const part = partOf(pkg, options.part);
90
92
  const log = createLog({ extension: pkg.agentage.id, part });
91
- const start = { pkg, part, env: options.env, log };
93
+ const names = part === 'ui' ? [] : (pkg.agentage.secrets ?? []);
94
+ const secrets = await readSecrets(names, options.secretsDir ?? SECRETS_DIR, part);
95
+ const start = { pkg, part, env: options.env, log, secrets };
92
96
  const { app, stop } = await RUNNERS[part](await inputFor(options, start));
93
97
  if (stop)
94
98
  for (const signal of options.serve?.signals ?? ['SIGTERM', 'SIGINT'])
@@ -14,5 +14,8 @@ export interface TestServer {
14
14
  fetch(path: string, init?: RequestInit): Promise<Response>;
15
15
  close(): Promise<void>;
16
16
  }
17
+ export interface TestMcp extends TestServer {
18
+ call(name: string, args?: Record<string, unknown>): Promise<unknown>;
19
+ }
17
20
  export declare const startTestServer: <C extends PartContext = PartContext>(options: TestServerOptions<C>) => Promise<TestServer>;
18
- export declare const startTestMcp: (options: TestMcpOptions) => Promise<TestServer>;
21
+ export declare const startTestMcp: (options: TestMcpOptions) => Promise<TestMcp>;
@@ -4,7 +4,8 @@ import {} from '../context/context.js';
4
4
  import { createTestContext } from '../context/test-context.js';
5
5
  import {} from '../manifest/manifest.schema.js';
6
6
  import { createMcpApp } from '../mcp/mcp-app.js';
7
- import { createToolRegistry } from '../mcp/tools.js';
7
+ import { callTool } from '../mcp/snapshot.js';
8
+ import { createToolRegistry, prefixed } from '../mcp/tools.js';
8
9
  import { createApiApp } from '../server/app.js';
9
10
  import {} from '../server/part.types.js';
10
11
  import { listen } from '../server/serve.js';
@@ -44,5 +45,7 @@ export const startTestMcp = async (options) => {
44
45
  tools: registry.tools,
45
46
  listing: 'open',
46
47
  });
47
- return startOn(app);
48
+ const server = await startOn(app);
49
+ const call = (name, args = {}) => callTool(`${server.url}/mcp`, prefixed(ctx.extension.id, name), args);
50
+ return { ...server, call };
48
51
  };
@@ -32,6 +32,7 @@ export interface CheckReport {
32
32
  problems: CheckProblem[];
33
33
  skipped: Record<string, string>;
34
34
  }
35
+ export declare const NOT_BUILT = "is missing: build the package first (npm run build)";
35
36
  export declare const RULES: readonly CheckRule[];
36
37
  export declare const check: (at: string, options?: CheckOptions) => Promise<CheckReport>;
37
38
  export declare const assertConforms: (dir: string, options?: CheckOptions) => Promise<void>;
@@ -10,12 +10,14 @@ import {} from '../manifest/primitives.schema.js';
10
10
  import { formatIssues, readJsonIfExists } from '../manifest/read-manifest.js';
11
11
  import { runCommand } from './exec.js';
12
12
  import { problemLines } from './format.js';
13
+ import { exportedPartCode } from './rules/folders.js';
13
14
  import { sealing } from './rules/sealing.js';
14
15
  import { store } from './rules/store.js';
15
16
  import { surface } from './rules/surface.js';
16
17
  import { KIT_VERSION } from './kit-version.js';
17
18
  import { assertBuilt, exists } from './stage.js';
18
19
  const RECIPE = /^(?:dockerfile|containerfile)(?:\..+)?$|^(?:docker-)?compose(?:\.[\w-]+)?\.ya?ml$/i;
20
+ export const NOT_BUILT = 'is missing: build the package first (npm run build)';
19
21
  const NO_PACKAGE = 'is missing: run it in an extension package folder';
20
22
  const manifest = {
21
23
  name: 'manifest',
@@ -52,15 +54,16 @@ const partProblem = async ({ dir, pkg }, part) => {
52
54
  return `${normalize(entryOf(pkg, part))} not found: the package build must write the cli part there`;
53
55
  return part === 'ui' ? null : exportProblem(dir, pkg, part);
54
56
  };
55
- // Every part built where its image looks, exporting create and nothing else; cli handlers = commands.
57
+ // Every part built and exporting only create; cli handlers = commands; exports hold no part code.
56
58
  const entries = {
57
59
  name: 'entries',
58
60
  run: async (input) => {
59
61
  if (!(await exists(join(input.dir, 'dist'))))
60
- return [{ file: 'dist', problem: 'is missing: build the package first (npm run build)' }];
62
+ return [{ file: 'dist', problem: NOT_BUILT }];
61
63
  const parts = Object.keys(normalizeParts(input.pkg.agentage.parts).code);
62
64
  const found = parts.map((part) => partProblem(input, part).catch(messageOf));
63
- return (await Promise.all(found)).flatMap((problem) => (problem ? [{ problem }] : []));
65
+ const problems = (await Promise.all(found)).flatMap((problem) => problem ? [{ problem }] : []);
66
+ return [...problems, ...exportedPartCode(input.pkg)];
64
67
  },
65
68
  };
66
69
  const MAJORS = { express: '^5', zod: '^4', '@modelcontextprotocol/server': '^2' };
@@ -0,0 +1 @@
1
+ export declare const writeContracts: (at: string) => Promise<string[]>;
@@ -0,0 +1,48 @@
1
+ import { readFile, writeFile } from 'node:fs/promises';
2
+ import { join, resolve } from 'node:path';
3
+ import { OPENAPI_FILE } from '../discovery/openapi.js';
4
+ import { loadCreate } from '../manifest/entry.js';
5
+ import {} from '../manifest/manifest.schema.js';
6
+ import { normalizeParts } from '../manifest/parts.js';
7
+ import { readManifest } from '../manifest/read-manifest.js';
8
+ import { canonical } from '../mcp/snapshot.js';
9
+ import {} from '../mcp/tools.js';
10
+ import { NOT_BUILT } from './check.js';
11
+ import { generatedMcp } from './rules/surface.js';
12
+ import { exists } from './stage.js';
13
+ const readText = (file) => readFile(file, 'utf8').catch(() => undefined);
14
+ const sameJson = (text, value) => text !== undefined &&
15
+ JSON.stringify(canonical(JSON.parse(text))) === JSON.stringify(canonical(value));
16
+ const json = (value) => `${JSON.stringify(value, null, 2)}\n`;
17
+ const writeMcp = async (dir, pkg) => {
18
+ const file = `${pkg.agentage.id}.mcpc.json`;
19
+ const create = await loadCreate(dir, pkg, 'mcp');
20
+ const snapshot = canonical(await generatedMcp(create, pkg));
21
+ if (sameJson(await readText(join(dir, file)), snapshot))
22
+ return [];
23
+ await writeFile(join(dir, file), json(snapshot));
24
+ return [file];
25
+ };
26
+ const INFO_VERSION = /("info"\s*:\s*\{[^{}]*?"version"\s*:\s*)"[^"]*"/;
27
+ // Only info.version, in place so the file keeps its formatting; check reports any other drift.
28
+ const writeOpenapiVersion = async (dir, version) => {
29
+ const file = join(dir, OPENAPI_FILE);
30
+ const text = await readText(file);
31
+ if (text === undefined)
32
+ return [];
33
+ const inPlace = text.replace(INFO_VERSION, `$1${JSON.stringify(version)}`);
34
+ if (inPlace === text)
35
+ return [];
36
+ await writeFile(file, inPlace);
37
+ return [OPENAPI_FILE];
38
+ };
39
+ // check --write: the committed contracts regenerated from the built code; returns the files it changed.
40
+ export const writeContracts = async (at) => {
41
+ const dir = resolve(at);
42
+ const pkg = await readManifest(dir);
43
+ if (!(await exists(join(dir, 'dist'))))
44
+ throw new Error(`dist ${NOT_BUILT}`);
45
+ const { code } = normalizeParts(pkg.agentage.parts);
46
+ const mcp = code.mcp ? await writeMcp(dir, pkg) : [];
47
+ return [...mcp, ...(code.api ? await writeOpenapiVersion(dir, pkg.version) : [])];
48
+ };
@@ -4,6 +4,7 @@ export { type ExtensionPackage, type CommandSpec } from '../manifest/manifest.sc
4
4
  export { readManifest, validateManifest } from '../manifest/read-manifest.js';
5
5
  export { build, type BuildDeps, type BuildOptions, type BuildResult, type BuiltImage, } from './build.js';
6
6
  export { check, type CheckProblem, type CheckReport } from './check.js';
7
+ export { writeContracts } from './contracts.js';
7
8
  export { buildLines, checkLines } from './format.js';
8
9
  export { KIT_VERSION } from './kit-version.js';
9
10
  export { down, type DownOptions, type DownResult } from './up/down.js';
@@ -4,6 +4,7 @@ export {} from '../manifest/manifest.schema.js';
4
4
  export { readManifest, validateManifest } from '../manifest/read-manifest.js';
5
5
  export { build, } from './build.js';
6
6
  export { check } from './check.js';
7
+ export { writeContracts } from './contracts.js';
7
8
  export { buildLines, checkLines } from './format.js';
8
9
  export { KIT_VERSION } from './kit-version.js';
9
10
  export { down } from './up/down.js';
@@ -9,7 +9,7 @@ import { createLog } from '../log/log.js';
9
9
  import { loadCreate } from '../manifest/entry.js';
10
10
  import { readJsonIfExists } from '../manifest/read-manifest.js';
11
11
  import {} from '../manifest/manifest.schema.js';
12
- import { hasPostgres, normalizeParts } from '../manifest/parts.js';
12
+ import { migratesStore, normalizeParts } from '../manifest/parts.js';
13
13
  import { createToolRegistry, prefixed } from '../mcp/tools.js';
14
14
  import { sqlFiles } from '../store/migrations.js';
15
15
  import {} from '../store/store.types.js';
@@ -59,7 +59,7 @@ export const recordExtras = async (dir, pkg) => {
59
59
  extras.widgets = await widgetsOf(dir);
60
60
  if (code.api && (await readOpenapi(dir)))
61
61
  extras.openapi = OPENAPI_PATH;
62
- if (hasPostgres(pkg))
62
+ if (migratesStore(pkg))
63
63
  extras.migrations = (await sqlFiles(join(dir, 'migrations'))).length;
64
64
  return extras;
65
65
  };
@@ -0,0 +1,4 @@
1
+ import { type ExtensionPackage } from '../../manifest/manifest.schema.js';
2
+ import { type Finding } from '../check.js';
3
+ export declare const crossPartImports: (file: string, code: string) => Finding[];
4
+ export declare const exportedPartCode: (pkg: ExtensionPackage) => Finding[];
@@ -0,0 +1,38 @@
1
+ import { normalize, posix } from 'node:path';
2
+ import {} from '../../manifest/manifest.schema.js';
3
+ import { entryOf, normalizeParts } from '../../manifest/parts.js';
4
+ import { IMAGE_PART_KINDS } from '../../manifest/primitives.schema.js';
5
+ import {} from '../check.js';
6
+ const PARTS = [...IMAGE_PART_KINDS, 'cli'];
7
+ const PART_FOLDER = /^(?:src|dist)\/(?:pages|ui|api|mcp|worker|cli)(?:\/|$)/;
8
+ // Erased at build, so a type crosses no image; blanked keeping newlines for the line count.
9
+ const TYPE_ONLY = /\b(?:import|export)\s+type\b[^;'"]*?from\s*(['"])[^'"]*\1/g;
10
+ const RELATIVE = /\b(?:from|import)\s*\(?\s*(['"])(\.{1,2}\/[^'"]*)\1/g;
11
+ // Each image carries one part folder and src/lib, so a part imports nothing else.
12
+ export const crossPartImports = (file, code) => {
13
+ const [src, part = ''] = file.split('/');
14
+ if (src !== 'src' || !PARTS.includes(part))
15
+ return [];
16
+ const values = code.replace(TYPE_ONLY, (t) => t.replace(/[^\n]/g, ''));
17
+ return [...values.matchAll(RELATIVE)].flatMap((m) => {
18
+ const target = posix.join(posix.dirname(file), m[2] ?? '');
19
+ if (target.startsWith(`src/${part}/`) || target.startsWith('src/lib/'))
20
+ return [];
21
+ const line = values.slice(0, m.index).split('\n').length;
22
+ return [
23
+ { file, line, problem: `imports ${m[2]}: a part imports only its own folder and src/lib` },
24
+ ];
25
+ });
26
+ };
27
+ const targets = (value) => typeof value === 'string' ? [value] : Object.values(Object(value)).flatMap(targets);
28
+ // The package is the manifest and the record; part code reaches users only through its image.
29
+ export const exportedPartCode = (pkg) => {
30
+ const parts = Object.keys(normalizeParts(pkg.agentage.parts).code);
31
+ const entries = parts.map((part) => normalize(entryOf(pkg, part)));
32
+ const partCode = (target) => PART_FOLDER.test(normalize(target)) || entries.includes(normalize(target));
33
+ const exported = targets(pkg.exports).filter(partCode);
34
+ return exported.map((target) => ({
35
+ file: 'package.json',
36
+ problem: `exports ${target}: the package exports no part code`,
37
+ }));
38
+ };
@@ -2,6 +2,7 @@ import { lstat, readdir, readFile } from 'node:fs/promises';
2
2
  import { join, relative } from 'node:path';
3
3
  import { readJsonIfExists } from '../../manifest/read-manifest.js';
4
4
  import {} from '../check.js';
5
+ import { crossPartImports } from './folders.js';
5
6
  const CODE = /\.[cm]?[jt]sx?$/;
6
7
  const TEST = /\.(test|spec)\.[cm]?[jt]sx?$/;
7
8
  // Strings first, so a // inside one is no comment; a comment keeps its newlines for the line count.
@@ -36,7 +37,8 @@ const matches = (file, text, patterns) => patterns.flatMap(([pattern, problem])
36
37
  const fileFindings = (file, text) => {
37
38
  const kept = text.replace(TOKENS, (t) => (t.startsWith('/') ? t.replace(/[^\n]/g, '') : t));
38
39
  const code = kept.replace(QUOTED, (s) => (/\s/.test(s) ? "''" : s));
39
- return [...matches(file, code, ON_CODE), ...matches(file, kept, ON_STRINGS)];
40
+ const found = [...matches(file, code, ON_CODE), ...matches(file, kept, ON_STRINGS)];
41
+ return [...found, ...crossPartImports(file, kept)];
40
42
  };
41
43
  const LINKED = 'is a symlink: part code is plain files';
42
44
  // Every non-test source under src/; any symlink met is refused, since it could point anywhere.
@@ -1,6 +1,7 @@
1
1
  import { readFile } from 'node:fs/promises';
2
2
  import { join, resolve } from 'node:path';
3
- import { hasPostgres } from '../../manifest/parts.js';
3
+ import { migratesStore, storeOf } from '../../manifest/parts.js';
4
+ import { SERVED_KINDS } from '../../manifest/primitives.schema.js';
4
5
  import { sqlFiles } from '../../store/migrations.js';
5
6
  import {} from '../check.js';
6
7
  import {} from '../exec.js';
@@ -41,8 +42,13 @@ const dockerAnswers = (run) => run('docker', ['version'], { quiet: true }).then(
41
42
  export const store = {
42
43
  name: 'store',
43
44
  run: async ({ dir, pkg, run, requireDocker }) => {
44
- if (!hasPostgres(pkg))
45
+ const kind = storeOf(pkg);
46
+ if (!kind)
45
47
  return { skipped: 'no store' };
48
+ if (!SERVED_KINDS.includes(kind))
49
+ return [{ problem: `kind ${kind} is not served yet; served: ${SERVED_KINDS.join(', ')}` }];
50
+ if (!migratesStore(pkg))
51
+ return { skipped: `kind ${kind} has no migrations` };
46
52
  const files = await sqlFiles(join(dir, 'migrations'));
47
53
  const meta = await metaCommands(dir, files);
48
54
  if (files.length === 0 || meta.length > 0)
@@ -1,2 +1,6 @@
1
+ import { type ExtensionPackage } from '../../manifest/manifest.schema.js';
2
+ import { type McpSnapshot } from '../../mcp/snapshot.js';
3
+ import { type McpContext } from '../../mcp/tools.js';
1
4
  import { type CheckRule } from '../check.js';
5
+ export declare const generatedMcp: (create: (ctx: McpContext) => unknown, pkg: ExtensionPackage) => Promise<McpSnapshot>;
2
6
  export declare const surface: CheckRule;
@@ -2,6 +2,7 @@ import { join } from 'node:path';
2
2
  import {} from '../../context/context.js';
3
3
  import { OPENAPI_FILE, readOpenapi } from '../../discovery/openapi.js';
4
4
  import { loadCreate } from '../../manifest/entry.js';
5
+ import {} from '../../manifest/manifest.schema.js';
5
6
  import { normalizeParts } from '../../manifest/parts.js';
6
7
  import { readJsonIfExists } from '../../manifest/read-manifest.js';
7
8
  import { canonical } from '../../mcp/snapshot.js';
@@ -63,18 +64,21 @@ const byName = ({ serverInfo, tools }) => ({
63
64
  serverInfo,
64
65
  ...Object.fromEntries(tools.map((tool) => [String(tool['name']), tool])),
65
66
  });
67
+ // The tool list the mcp part serves, generated from its code: what {id}.mcpc.json must hold.
68
+ export const generatedMcp = async (create, pkg) => {
69
+ const { id } = pkg.agentage;
70
+ const tools = (await registeredTools(create, pkg)).map((tool) => listed(id, tool));
71
+ return { serverInfo: { name: `agentage-${id}`, version: pkg.version }, tools };
72
+ };
66
73
  const mcpSurface = async ({ dir, pkg }) => {
67
74
  const create = await loadCreate(dir, pkg, 'mcp').catch(() => null);
68
75
  if (!create)
69
76
  return [];
70
- const { id } = pkg.agentage;
71
- const file = `${id}.mcpc.json`;
77
+ const file = `${pkg.agentage.id}.mcpc.json`;
72
78
  const committed = (await readJsonIfExists(join(dir, file)));
73
79
  if (!committed)
74
80
  return [{ file, problem: 'is missing: the mcp part commits its tool list' }];
75
- const tools = (await registeredTools(create, pkg)).map((tool) => listed(id, tool));
76
- const serverInfo = { name: `agentage-${id}`, version: pkg.version };
77
- const diff = differing(byName({ serverInfo, tools }), byName(committed));
81
+ const diff = differing(byName(await generatedMcp(create, pkg)), byName(committed));
78
82
  const problem = `differs from the generated tool list (${diff.join(', ')})`;
79
83
  return diff.length > 0 ? [{ file, problem }] : [];
80
84
  };
@@ -2,7 +2,7 @@ import { access, cp, mkdir, mkdtemp, writeFile } from 'node:fs/promises';
2
2
  import { tmpdir } from 'node:os';
3
3
  import { dirname, isAbsolute, join, normalize, sep } from 'node:path';
4
4
  import {} from '../manifest/manifest.schema.js';
5
- import { entryOf, hasPostgres } from '../manifest/parts.js';
5
+ import { entryOf, migratesStore } from '../manifest/parts.js';
6
6
  import {} from '../manifest/primitives.schema.js';
7
7
  import { OPENAPI_FILE } from '../discovery/openapi.js';
8
8
  import { serverPartRecipe } from './recipe.js';
@@ -40,7 +40,7 @@ const copyDeps = async (dir, root, pkg) => {
40
40
  await copyInto(join(dir, path), join(root, 'deps', path));
41
41
  };
42
42
  // The api image runs the migrate job, so it alone carries the migrations; seeds never ship.
43
- const migrates = (pkg, part) => part === 'api' && hasPostgres(pkg);
43
+ const migrates = (pkg, part) => part === 'api' && migratesStore(pkg);
44
44
  // What a part image carries: its own dist/{part}, the shared dist/lib, and for api the migrations.
45
45
  export const appPaths = async (dir, pkg, part) => {
46
46
  const paths = ['package.json', join('dist', part)];
@@ -7,8 +7,23 @@ export interface ComposeInput {
7
7
  recordFile: string;
8
8
  gatewayFile: string;
9
9
  seedsDir?: string;
10
+ secretFiles?: Record<string, string>;
10
11
  }
11
12
  export declare const composeFile: (input: ComposeInput) => {
13
+ secrets: {
14
+ [k: string]: {
15
+ file: string;
16
+ };
17
+ };
18
+ name: string;
19
+ services: Record<string, unknown>;
20
+ volumes: {
21
+ store: {};
22
+ } | {
23
+ store?: undefined;
24
+ };
25
+ } | {
26
+ secrets?: undefined;
12
27
  name: string;
13
28
  services: Record<string, unknown>;
14
29
  volumes: {
@@ -1,5 +1,5 @@
1
1
  import {} from '../../manifest/manifest.schema.js';
2
- import { hasPostgres, imageParts } from '../../manifest/parts.js';
2
+ import { hasStore, imageParts } from '../../manifest/parts.js';
3
3
  import {} from '../../manifest/primitives.schema.js';
4
4
  import { DEV_AUDIENCE, DEV_ISSUER, UP_ISSUER } from './dev-issuer-app.js';
5
5
  import { GATEWAY_PORT, ISSUER_PORT, PART_PORT, TRAEFIK_COMMAND, TRAEFIK_IMAGE } from './gateway.js';
@@ -15,7 +15,9 @@ const partEnv = (pkg, part) => ({
15
15
  AGENTAGE_ISSUER: UP_ISSUER,
16
16
  AGENTAGE_AUDIENCE: DEV_AUDIENCE,
17
17
  AGENTAGE_RECORD_FILE: RECORD_TARGET,
18
- ...(hasPostgres(pkg) && part !== 'ui' ? { AGENTAGE_STORE_URL: storeUrl(pkg.agentage.id) } : {}),
18
+ ...(hasStore(pkg, 'postgres') && part !== 'ui'
19
+ ? { AGENTAGE_STORE_URL: storeUrl(pkg.agentage.id) }
20
+ : {}),
19
21
  ...(part === 'ui' ? { AGENTAGE_DEV_ISSUER: DEV_ISSUER } : {}),
20
22
  });
21
23
  const QUICK_CHECK = { interval: '2s', timeout: '3s', retries: 30 };
@@ -28,15 +30,17 @@ const storeService = (id) => ({
28
30
  const HEALTHY = { condition: 'service_healthy' };
29
31
  // api and mcp read the issuer's keys and revoked list before they serve.
30
32
  const dependsOn = (pkg, part) => ({
31
- ...(hasPostgres(pkg) && part !== 'ui' ? { store: HEALTHY } : {}),
33
+ ...(hasStore(pkg, 'postgres') && part !== 'ui' ? { store: HEALTHY } : {}),
32
34
  ...(part === 'api' || part === 'mcp' ? { issuer: HEALTHY } : {}),
33
35
  });
34
36
  const partService = (input, part) => ({
35
37
  image: input.tags[part],
36
38
  environment: partEnv(input.pkg, part),
37
39
  volumes: [`${input.recordFile}:${RECORD_TARGET}:ro`],
40
+ ...(part !== 'ui' && input.secretFiles ? { secrets: Object.keys(input.secretFiles) } : {}),
38
41
  depends_on: dependsOn(input.pkg, part),
39
42
  });
43
+ const secretsOf = (files) => Object.fromEntries(Object.entries(files).map(([name, file]) => [name, { file }]));
40
44
  const fixedServices = (input, anyImage) => ({
41
45
  gateway: {
42
46
  image: TRAEFIK_IMAGE,
@@ -69,11 +73,12 @@ export const composeFile = (input) => {
69
73
  for (const part of parts)
70
74
  services[part] = partService(input, part);
71
75
  Object.assign(services, fixedServices(input, input.tags[parts[0] ?? 'api'] ?? ''));
72
- if (hasPostgres(input.pkg)) {
76
+ if (hasStore(input.pkg, 'postgres')) {
73
77
  services['store'] = storeService(input.pkg.agentage.id);
74
78
  if (input.tags['api'])
75
79
  services['migrate'] = migrateService(input);
76
80
  }
77
- const volumes = hasPostgres(input.pkg) ? { store: {} } : {};
78
- return { name: input.project, services, volumes };
81
+ const volumes = hasStore(input.pkg, 'postgres') ? { store: {} } : {};
82
+ const secrets = input.secretFiles ? { secrets: secretsOf(input.secretFiles) } : {};
83
+ return { name: input.project, services, volumes, ...secrets };
79
84
  };
@@ -1,3 +1,4 @@
1
+ import { rm } from 'node:fs/promises';
1
2
  import { join } from 'node:path';
2
3
  import { readManifest } from '../../manifest/read-manifest.js';
3
4
  import { quietly, runCommand } from '../exec.js';
@@ -41,6 +42,7 @@ export const down = async (options = {}, run = runCommand) => {
41
42
  const log = result.stderr ?? '';
42
43
  if (result.code !== 0)
43
44
  throw new Error(`docker compose down failed: ${log.trim()}`);
45
+ await rm(join(dir, LOCAL_DIR, 'secrets'), { recursive: true, force: true });
44
46
  const removed = removedOf(log);
45
47
  options.onLine?.(stepLine('removed', summary(removed, options.keepData), target.project));
46
48
  return { project: target.project, ...removed };
@@ -0,0 +1,3 @@
1
+ import { type Run } from '../exec.js';
2
+ import { type ComposeTarget } from './compose-run.js';
3
+ export declare const assertHealthBodies: (run: Run, target: ComposeTarget, parts: string[], commit: string) => Promise<[part: string, checks: string][]>;
@@ -0,0 +1,40 @@
1
+ import {} from '../exec.js';
2
+ import { compose } from './compose-run.js';
3
+ import { PART_PORT } from './gateway.js';
4
+ // Inside the container: parts publish no host port, and the image always has node.
5
+ const FETCH = `fetch('http://127.0.0.1:${PART_PORT}/health').then(async (r) => process.stdout.write(await r.text()))`;
6
+ const dataOf = (text) => {
7
+ try {
8
+ return JSON.parse(text).data;
9
+ }
10
+ catch {
11
+ return undefined;
12
+ }
13
+ };
14
+ // 200 ok or degraded is an answering part (the /health standard); only unavailable fails.
15
+ const wants = (part, commit) => [
16
+ ['status', (v) => v === 'ok' || v === 'degraded', 'ok or degraded'],
17
+ ['commit', (v) => v === commit, commit],
18
+ ['part', (v) => v === part, part],
19
+ ];
20
+ // The first field that differs from the build, as one FAIL line.
21
+ const mismatch = (part, commit, data, text) => {
22
+ if (!data)
23
+ return `FAIL ${part} /health body is not the health envelope: ${text.slice(0, 120)}`;
24
+ const bad = wants(part, commit).find(([field, fits]) => !fits(data[field]));
25
+ return bad && `FAIL ${part} /health ${bad[0]} ${String(data[bad[0]])}, needs ${bad[2]}`;
26
+ };
27
+ const notOk = (data) => Object.entries(Object(data['checks']))
28
+ .filter(([, status]) => status !== 'ok')
29
+ .map(([name, status]) => `${name} ${String(status)}`)
30
+ .join(' · ');
31
+ // Docker's healthy only says the probe answered; the body must name this build and this part.
32
+ export const assertHealthBodies = async (run, target, parts, commit) => {
33
+ const read = parts.map((part) => compose(run, target, ['exec', '-T', part, 'node', '-e', FETCH]));
34
+ const bodies = await Promise.all(read);
35
+ const data = bodies.map(dataOf);
36
+ const failed = parts.flatMap((part, i) => mismatch(part, commit, data[i], bodies[i] ?? '') ?? []);
37
+ if (failed.length > 0)
38
+ throw new Error(failed.join('\n'));
39
+ return parts.flatMap((part, i) => data[i]?.['status'] === 'degraded' ? [[part, notOk(data[i])]] : []);
40
+ };
@@ -28,10 +28,11 @@ export declare const writeLocalRecord: (dir: string, pkg: ExtensionPackage, buil
28
28
  image: string;
29
29
  } | undefined;
30
30
  store?: {
31
- kind: "postgres" | "git" | "signoz";
31
+ kind: "postgres" | "signoz" | "git";
32
32
  migrations?: number | undefined;
33
33
  } | undefined;
34
34
  };
35
+ secrets?: string[] | undefined;
35
36
  openapi?: string | undefined;
36
37
  tools?: {
37
38
  name: string;
@@ -0,0 +1,6 @@
1
+ import { type ExtensionPackage } from '../../manifest/manifest.schema.js';
2
+ import { type Env } from '../../runtime/build-info.js';
3
+ export declare const secretEnvName: (name: string) => string;
4
+ export declare const writeUpSecrets: (dir: string, pkg: ExtensionPackage, env: Env) => Promise<{
5
+ [k: string]: string;
6
+ } | undefined>;
@@ -0,0 +1,36 @@
1
+ import { chmod, mkdir, writeFile } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import {} from '../../manifest/manifest.schema.js';
4
+ import { readJsonIfExists } from '../../manifest/read-manifest.js';
5
+ import {} from '../../runtime/build-info.js';
6
+ import { LOCAL_DIR } from './local-record.js';
7
+ const FILE = `${LOCAL_DIR}/secrets.json`;
8
+ export const secretEnvName = (name) => `AGENTAGE_SECRET_${name.toUpperCase().replace(/-/g, '_')}`;
9
+ // A parse error quotes the text, so any error is replaced by one that names only the file.
10
+ const fileValues = (dir) => readJsonIfExists(join(dir, FILE)).then((value) => (value ?? {}), (err) => {
11
+ const why = err.code ? 'cannot be read' : 'is not valid JSON';
12
+ return Promise.reject(new Error(`up stopped: ${FILE} ${why}`));
13
+ });
14
+ const valueOf = (name, env, file) => {
15
+ const value = env[secretEnvName(name)] || file[name];
16
+ if (typeof value === 'string' && value !== '')
17
+ return value;
18
+ throw new Error(`up stopped: secret ${name} has no value: set ${secretEnvName(name)} or "${name}" in ${FILE}`);
19
+ };
20
+ // Each value as a file compose mounts at /run/secrets/<name>; the env wins over the file.
21
+ export const writeUpSecrets = async (dir, pkg, env) => {
22
+ const names = pkg.agentage.secrets ?? [];
23
+ if (names.length === 0)
24
+ return undefined;
25
+ const file = await fileValues(dir);
26
+ const files = names.map((name) => ({
27
+ name,
28
+ path: join(dir, LOCAL_DIR, 'secrets', name),
29
+ value: valueOf(name, env, file),
30
+ }));
31
+ await mkdir(join(dir, LOCAL_DIR, 'secrets'), { recursive: true, mode: 0o700 });
32
+ // 0644 in a 0700 folder: the part's node user reads the bind mount; chmod fixes an older file.
33
+ for (const { path, value } of files)
34
+ await writeFile(path, value, { mode: 0o644 }).then(() => chmod(path, 0o644));
35
+ return Object.fromEntries(files.map(({ name, path }) => [name, path]));
36
+ };
@@ -1,7 +1,7 @@
1
1
  import { writeFile } from 'node:fs/promises';
2
2
  import { join } from 'node:path';
3
3
  import {} from '../../manifest/manifest.schema.js';
4
- import { hasPostgres, imageParts, normalizeParts } from '../../manifest/parts.js';
4
+ import { hasStore, imageParts, normalizeParts } from '../../manifest/parts.js';
5
5
  import { readManifest } from '../../manifest/read-manifest.js';
6
6
  import {} from '../../runtime/build-info.js';
7
7
  import { build } from '../build.js';
@@ -14,8 +14,10 @@ import { GATEWAY_PORT, gatewayConfig, ISSUER_PORT, PART_PATHS, partPath } from '
14
14
  import { plural, stepLine } from './lines.js';
15
15
  import { assertDiscoverable, LOCAL_DIR, writeLocalRecord } from './local-record.js';
16
16
  import { assertPortsFree } from './ports.js';
17
+ import { writeUpSecrets } from './secrets.js';
17
18
  import { projectName, workingCopy } from './project.js';
18
19
  import { storePhrase, summaryOf } from './store-line.js';
20
+ import { assertHealthBodies } from './health.js';
19
21
  import { waitHealthy } from './wait.js';
20
22
  const GATEWAY = `http://localhost:${GATEWAY_PORT}`;
21
23
  const jsonFile = (file, value) => writeFile(file, `${JSON.stringify(value, null, 2)}\n`);
@@ -24,8 +26,9 @@ const renderFiles = async (s, recordFile, tags) => {
24
26
  const seeds = join(s.dir, 'seeds');
25
27
  const seedsDir = (await exists(seeds)) ? seeds : undefined;
26
28
  await jsonFile(gatewayFile, gatewayConfig(imageParts(s.pkg), s.pkg.version));
27
- const project = s.target.project;
28
- await jsonFile(s.target.file, composeFile({ pkg: s.pkg, project, tags, recordFile, gatewayFile, seedsDir }));
29
+ const { pkg, secretFiles, target } = s;
30
+ const project = target.project;
31
+ await jsonFile(target.file, composeFile({ pkg, project, tags, recordFile, gatewayFile, seedsDir, secretFiles }));
29
32
  };
30
33
  const buildStep = async (s, env) => {
31
34
  const built = await build({ dir: s.dir, env }, { run: s.deps.run });
@@ -35,6 +38,7 @@ const buildStep = async (s, env) => {
35
38
  assertDiscoverable(record, GATEWAY);
36
39
  s.line('record', `${LOCAL_DIR}/record.json`, 'discovery valid');
37
40
  await renderFiles(s, file, Object.fromEntries(built.images.map((i) => [i.part, i.tag])));
41
+ return built.commit;
38
42
  };
39
43
  // The migrate job runs before any part starts; a kept volume reports what it already had.
40
44
  const storeStep = async (s) => {
@@ -50,9 +54,12 @@ const storeStep = async (s) => {
50
54
  export const routesOf = (pkg) => Object.keys(PART_PATHS)
51
55
  .filter((part) => imageParts(pkg).includes(part))
52
56
  .map((part) => partPath(part, pkg.version));
53
- const partsStep = async (s) => {
57
+ const partsStep = async (s, commit) => {
54
58
  await compose(s.deps.run, s.target, ['up', '-d', '--remove-orphans'], TIMEOUTS.start);
55
59
  await waitHealthy(s.target, [...imageParts(s.pkg), 'gateway', 'issuer'], s.deps);
60
+ const degraded = await assertHealthBodies(s.deps.run, s.target, imageParts(s.pkg), commit);
61
+ for (const [part, checks] of degraded)
62
+ s.line('degraded', part, checks);
56
63
  s.line('issuer', 'dev tokens', `http://localhost:${ISSUER_PORT}`);
57
64
  s.line('gateway', GATEWAY, routesOf(s.pkg).join(' · '));
58
65
  };
@@ -64,20 +71,21 @@ const sessionOf = async (options, deps) => {
64
71
  const file = join(dir, LOCAL_DIR, 'compose.json');
65
72
  const target = { file, project: projectName(pkg.agentage.id, dir) };
66
73
  const line = (label, what, detail) => options.onLine?.(stepLine(label, what, detail));
67
- return { dir, pkg, target, line, deps: { ...deps, run: quietly(deps.run) } };
74
+ const secretFiles = await writeUpSecrets(dir, pkg, options.env ?? process.env);
75
+ return { dir, pkg, target, line, deps: { ...deps, run: quietly(deps.run) }, secretFiles };
68
76
  };
69
77
  // The laptop shape of a deployment: the release images, a local record, store, issuer, gateway.
70
78
  export const up = async (options = {}, deps = { run: runCommand }) => {
71
79
  const started = Date.now();
72
80
  const s = await sessionOf(options, deps);
73
81
  await assertPortsFree(s.deps.run, s.target.project);
74
- await buildStep(s, options.env ?? process.env);
82
+ const commit = await buildStep(s, options.env ?? process.env);
75
83
  // Again after the build: another up may have started meanwhile, and the store comes next.
76
84
  await assertPortsFree(s.deps.run, s.target.project);
77
- if (hasPostgres(s.pkg))
85
+ if (hasStore(s.pkg, 'postgres'))
78
86
  await storeStep(s);
79
- await partsStep(s);
80
- const parts = imageParts(s.pkg).length + (hasPostgres(s.pkg) ? 1 : 0) + cliParts(s.pkg);
87
+ await partsStep(s, commit);
88
+ const parts = imageParts(s.pkg).length + (hasStore(s.pkg, 'postgres') ? 1 : 0) + cliParts(s.pkg);
81
89
  const seconds = Math.round((Date.now() - started) / 1000);
82
90
  s.line('ready', `${plural(parts, 'part')} healthy`, `${seconds} s`);
83
91
  return { parts, seconds, project: s.target.project };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentage/extension",
3
- "version": "0.4.3",
3
+ "version": "0.5.1",
4
4
  "description": "The agentage extension kit: create(ctx) per part (pages, ui, api, mcp, worker, cli), the store, /health, discovery, the envelope, and the build tool with up and token",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -102,8 +102,8 @@
102
102
  "type": "string",
103
103
  "enum": [
104
104
  "postgres",
105
- "git",
106
- "signoz"
105
+ "signoz",
106
+ "git"
107
107
  ]
108
108
  },
109
109
  "migrations": {
@@ -152,8 +152,8 @@
152
152
  "type": "string",
153
153
  "enum": [
154
154
  "postgres",
155
- "git",
156
- "signoz"
155
+ "signoz",
156
+ "git"
157
157
  ]
158
158
  },
159
159
  {
@@ -163,8 +163,8 @@
163
163
  "type": "string",
164
164
  "enum": [
165
165
  "postgres",
166
- "git",
167
- "signoz"
166
+ "signoz",
167
+ "git"
168
168
  ]
169
169
  }
170
170
  },
@@ -102,8 +102,8 @@
102
102
  "type": "string",
103
103
  "enum": [
104
104
  "postgres",
105
- "git",
106
- "signoz"
105
+ "signoz",
106
+ "git"
107
107
  ]
108
108
  },
109
109
  "migrations": {
@@ -182,6 +182,15 @@
182
182
  "maxLength": 32,
183
183
  "pattern": "^[a-z][a-z0-9-]*$"
184
184
  }
185
+ },
186
+ "secrets": {
187
+ "minItems": 1,
188
+ "type": "array",
189
+ "items": {
190
+ "type": "string",
191
+ "maxLength": 48,
192
+ "pattern": "^[a-z][a-z0-9-]*$"
193
+ }
185
194
  }
186
195
  },
187
196
  "required": [