@agentage/extension 0.16.0 → 0.18.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 (147) hide show
  1. package/dist/api/download.d.ts +14 -0
  2. package/dist/api/download.js +10 -0
  3. package/dist/api/files-registry.d.ts +17 -0
  4. package/dist/api/files-registry.js +10 -0
  5. package/dist/api/files.d.ts +8 -0
  6. package/dist/api/files.js +82 -0
  7. package/dist/api/openapi-doc.js +21 -12
  8. package/dist/api/routes.d.ts +10 -1
  9. package/dist/api/routes.js +15 -2
  10. package/dist/auth/token-check.d.ts +1 -1
  11. package/dist/auth/verify-token.js +9 -9
  12. package/dist/context/test-context.d.ts +5 -1
  13. package/dist/context/test-context.js +2 -1
  14. package/dist/host/daemon/app-files.d.ts +13 -0
  15. package/dist/host/daemon/app-files.js +51 -0
  16. package/dist/host/daemon/app-header.d.ts +3 -0
  17. package/dist/host/daemon/app-header.js +12 -0
  18. package/dist/host/daemon/app-reload.d.ts +10 -0
  19. package/dist/host/daemon/app-reload.js +18 -0
  20. package/dist/host/daemon/child.d.ts +1 -0
  21. package/dist/host/daemon/child.js +7 -4
  22. package/dist/host/daemon/cli-user-watch.d.ts +8 -0
  23. package/dist/host/daemon/cli-user-watch.js +43 -0
  24. package/dist/host/daemon/cli-user.d.ts +2 -0
  25. package/dist/host/daemon/cli-user.js +42 -0
  26. package/dist/host/daemon/daemon.d.ts +1 -0
  27. package/dist/host/daemon/daemon.js +13 -1
  28. package/dist/host/daemon/health-routes.d.ts +2 -0
  29. package/dist/host/daemon/health-routes.js +29 -15
  30. package/dist/host/daemon/limits.d.ts +1 -0
  31. package/dist/host/daemon/limits.js +2 -0
  32. package/dist/host/daemon/routes.js +25 -7
  33. package/dist/host/daemon/seal.d.ts +6 -2
  34. package/dist/host/daemon/seal.js +9 -2
  35. package/dist/host/daemon/shell-events.d.ts +9 -0
  36. package/dist/host/daemon/shell-events.js +36 -0
  37. package/dist/host/daemon/shell-routes.d.ts +28 -0
  38. package/dist/host/daemon/shell-routes.js +63 -0
  39. package/dist/host/daemon/supervisor.d.ts +2 -0
  40. package/dist/host/daemon/supervisor.js +2 -1
  41. package/dist/host/data-lock.js +5 -5
  42. package/dist/host/host-env.js +14 -2
  43. package/dist/host/host-extension.js +4 -3
  44. package/dist/host/host-git-store.d.ts +10 -0
  45. package/dist/host/host-git-store.js +36 -0
  46. package/dist/host/host-migrations.d.ts +1 -1
  47. package/dist/host/host-migrations.js +2 -2
  48. package/dist/host/host-parts.d.ts +2 -2
  49. package/dist/host/host-parts.js +1 -1
  50. package/dist/host/host-url-store.d.ts +4 -2
  51. package/dist/host/host-url-store.js +18 -15
  52. package/dist/host/open-store.d.ts +6 -0
  53. package/dist/host/open-store.js +6 -0
  54. package/dist/index.d.ts +3 -1
  55. package/dist/index.js +3 -1
  56. package/dist/manifest/manifest.schema.d.ts +13 -0
  57. package/dist/manifest/manifest.schema.js +16 -2
  58. package/dist/manifest/parts.d.ts +7 -0
  59. package/dist/manifest/parts.js +5 -0
  60. package/dist/manifest/primitives.schema.js +3 -3
  61. package/dist/mcp/connector.d.ts +4 -0
  62. package/dist/mcp/connector.js +11 -0
  63. package/dist/mcp/mcp-app.d.ts +4 -1
  64. package/dist/mcp/mcp-app.js +28 -18
  65. package/dist/mcp/server.d.ts +6 -3
  66. package/dist/mcp/server.js +70 -18
  67. package/dist/mcp/tools.d.ts +40 -4
  68. package/dist/mcp/tools.js +34 -12
  69. package/dist/runtime/part-mounts.js +12 -6
  70. package/dist/runtime/run-part.js +22 -6
  71. package/dist/server/api-routes.d.ts +5 -2
  72. package/dist/server/api-routes.js +41 -14
  73. package/dist/server/app.d.ts +3 -0
  74. package/dist/server/app.js +11 -1
  75. package/dist/server/send-download.d.ts +3 -0
  76. package/dist/server/send-download.js +29 -0
  77. package/dist/shell/dist/index.html +46 -0
  78. package/dist/shell/dist/shell.css +2 -0
  79. package/dist/shell/dist/shell.js +68 -0
  80. package/dist/shell/dist/vendor/app.js +1 -0
  81. package/dist/shell/dist/vendor/chunk-AOJ3DQEL.js +14 -0
  82. package/dist/shell/dist/vendor/chunk-LW5HXGAJ.js +14 -0
  83. package/dist/shell/dist/vendor/chunk-PQJPUKWH.js +14 -0
  84. package/dist/shell/dist/vendor/chunk-SQE76S5B.js +1 -0
  85. package/dist/shell/dist/vendor/jsx-runtime.js +1 -0
  86. package/dist/shell/dist/vendor/react-dom-client.js +33 -0
  87. package/dist/shell/dist/vendor/react-dom.js +1 -0
  88. package/dist/shell/dist/vendor/react.js +1 -0
  89. package/dist/shell/package.json +5 -0
  90. package/dist/store/git-env.d.ts +11 -0
  91. package/dist/store/git-env.js +44 -0
  92. package/dist/store/store-url.d.ts +1 -1
  93. package/dist/store/store-url.js +2 -0
  94. package/dist/store/store.types.d.ts +3 -0
  95. package/dist/store/store.types.js +1 -1
  96. package/dist/testing/test-server.js +11 -12
  97. package/dist/tool/app-build.d.ts +13 -0
  98. package/dist/tool/app-build.js +126 -0
  99. package/dist/tool/app-load.d.ts +4 -0
  100. package/dist/tool/app-load.js +34 -0
  101. package/dist/tool/build.js +5 -2
  102. package/dist/tool/check.js +4 -2
  103. package/dist/tool/container-recipe.d.ts +9 -2
  104. package/dist/tool/container-recipe.js +14 -9
  105. package/dist/tool/container-stage.js +1 -1
  106. package/dist/tool/index.d.ts +1 -0
  107. package/dist/tool/index.js +1 -0
  108. package/dist/tool/main.d.ts +2 -0
  109. package/dist/tool/main.js +8 -1
  110. package/dist/tool/recipe.d.ts +1 -1
  111. package/dist/tool/recipe.js +16 -6
  112. package/dist/tool/record-extras.js +4 -3
  113. package/dist/tool/rules/folders.js +1 -1
  114. package/dist/tool/rules/sealing.js +4 -0
  115. package/dist/tool/rules/store.js +0 -3
  116. package/dist/tool/rules/surface.js +4 -1
  117. package/dist/tool/stage.js +2 -2
  118. package/dist/tool/up/compose.d.ts +4 -0
  119. package/dist/tool/up/compose.js +41 -3
  120. package/dist/tool/up/gateway.js +16 -3
  121. package/dist/tool/up/secrets.d.ts +1 -0
  122. package/dist/tool/up/secrets.js +13 -1
  123. package/dist/tool/up/up.js +8 -5
  124. package/dist/vendor/app/api.d.ts +9 -0
  125. package/dist/vendor/app/api.js +63 -0
  126. package/dist/vendor/app/app.types.d.ts +65 -0
  127. package/dist/vendor/app/app.types.js +1 -0
  128. package/dist/vendor/app/boundary.d.ts +15 -0
  129. package/dist/vendor/app/boundary.js +17 -0
  130. package/dist/vendor/app/context.d.ts +5 -0
  131. package/dist/vendor/app/context.js +22 -0
  132. package/dist/vendor/app/index.d.ts +7 -0
  133. package/dist/vendor/app/index.js +6 -0
  134. package/dist/vendor/app/region.d.ts +6 -0
  135. package/dist/vendor/app/region.js +14 -0
  136. package/dist/vendor/app/split.d.ts +20 -0
  137. package/dist/vendor/app/split.js +38 -0
  138. package/dist/vendor/app/state-store.d.ts +3 -0
  139. package/dist/vendor/app/state-store.js +35 -0
  140. package/dist/vendor/app/test-host.d.ts +29 -0
  141. package/dist/vendor/app/test-host.js +66 -0
  142. package/dist/vendor/app/theme.css +32 -0
  143. package/package.json +35 -2
  144. package/schemas/extension-discovery.schema.json +1 -1
  145. package/schemas/extension-package.schema.json +28 -1
  146. package/schemas/extension-record.schema.json +1 -1
  147. package/schemas/health.schema.json +1 -1
@@ -1,7 +1,6 @@
1
1
  import { readFile } from 'node:fs/promises';
2
2
  import { join, resolve } from 'node:path';
3
3
  import { migratesStore, storeOf } from '../../manifest/parts.js';
4
- import { SERVED_KINDS } from '../../manifest/primitives.schema.js';
5
4
  import { sqlFiles } from '../../store/migrations.js';
6
5
  import {} from '../check.js';
7
6
  import {} from '../exec.js';
@@ -45,8 +44,6 @@ export const store = {
45
44
  const kind = storeOf(pkg);
46
45
  if (!kind)
47
46
  return { skipped: 'no store' };
48
- if (!SERVED_KINDS.includes(kind))
49
- return [{ problem: `kind ${kind} is not served yet; served: ${SERVED_KINDS.join(', ')}` }];
50
47
  if (!migratesStore(pkg))
51
48
  return { skipped: `kind ${kind} has no migrations` };
52
49
  const files = await sqlFiles(join(dir, 'migrations'));
@@ -71,11 +71,14 @@ const apiSurface = async ({ dir, pkg }) => {
71
71
  : routerProblems(pkg, doc, returned);
72
72
  return found.map((problem) => ({ file: OPENAPI_FILE, problem }));
73
73
  };
74
+ // As the server lists it: title, annotations and outputSchema only when set.
74
75
  const listed = (id, { name, spec }) => ({
75
76
  name: prefixed(id, name),
77
+ ...(spec.title !== undefined && { title: spec.title }),
76
78
  description: spec.description,
77
79
  inputSchema: schemaOf(spec.input, 'input'),
78
- outputSchema: schemaOf(spec.output, 'output'),
80
+ ...(spec.output && { outputSchema: schemaOf(spec.output, 'output') }),
81
+ ...(spec.annotations && { annotations: spec.annotations }),
79
82
  });
80
83
  const byName = ({ serverInfo, tools }) => ({
81
84
  serverInfo,
@@ -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, migratesStore } from '../manifest/parts.js';
5
+ import { entryOf, hasStore, 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';
@@ -78,6 +78,6 @@ export const stageContext = async (dir, pkg, part, tmpRoot = tmpdir()) => {
78
78
  const root = await mkdtemp(join(tmpRoot, `agentage-${pkg.agentage.id}-${part}-`));
79
79
  await copyDeps(dir, root, pkg);
80
80
  await copyApp(dir, root, pkg, part);
81
- await writeFile(join(root, 'Dockerfile'), serverPartRecipe(part));
81
+ await writeFile(join(root, 'Dockerfile'), serverPartRecipe(part, part !== 'ui' && hasStore(pkg, 'git')));
82
82
  return root;
83
83
  };
@@ -1,5 +1,7 @@
1
1
  import { type ExtensionPackage } from '../../manifest/manifest.schema.js';
2
2
  export declare const STORE_IMAGE = "postgres:18-alpine";
3
+ export declare const CLICKHOUSE_IMAGE = "clickhouse/clickhouse-server:26.8@sha256:d426d2f612e1e189c90f9a3f8dcd85a03c6851273833817a296bb327e63aa7a7";
4
+ export declare const STORE_URL_SECRET = "store-url";
3
5
  export interface ComposeInput {
4
6
  pkg: ExtensionPackage;
5
7
  project: string;
@@ -9,6 +11,8 @@ export interface ComposeInput {
9
11
  seedsDir?: string;
10
12
  secretFiles?: Record<string, string>;
11
13
  }
14
+ export declare const clickhouseUrl: (id: string) => string;
15
+ export declare const runsStore: (pkg: ExtensionPackage) => boolean;
12
16
  export declare const composeFile: (input: ComposeInput) => {
13
17
  secrets: {
14
18
  [k: string]: {
@@ -1,14 +1,27 @@
1
1
  import {} from '../../manifest/manifest.schema.js';
2
2
  import { hasStore, imageParts, mountedIn } from '../../manifest/parts.js';
3
3
  import {} from '../../manifest/primitives.schema.js';
4
+ import { DATA_VOLUME } from '../container-recipe.js';
4
5
  import { DEV_AUDIENCE, DEV_ISSUER, UP_ISSUER } from './dev-issuer-app.js';
5
6
  import { GATEWAY_PORT, ISSUER_PORT, PART_PORT, TRAEFIK_COMMAND, TRAEFIK_IMAGE } from './gateway.js';
6
7
  export const STORE_IMAGE = 'postgres:18-alpine';
8
+ // The estate's image (its src/store.ts); the host mounts the URL at /run/secrets/store-url the same way.
9
+ export const CLICKHOUSE_IMAGE = 'clickhouse/clickhouse-server:26.8@sha256:d426d2f612e1e189c90f9a3f8dcd85a03c6851273833817a296bb327e63aa7a7';
10
+ export const STORE_URL_SECRET = 'store-url';
11
+ const STORE_URL_FILE = `/run/secrets/${STORE_URL_SECRET}`;
7
12
  const RECORD_TARGET = '/run/agentage/agentage-extension.json';
8
13
  const ISSUER_ENTRY = 'node_modules/@agentage/extension/dist/tool/up/dev-issuer.js';
9
14
  // A local-only credential: the store has no published port, only the parts' network reaches it.
10
15
  const STORE_PASSWORD = 'agentage-local';
11
16
  const storeUrl = (id) => `postgres://${id}:${STORE_PASSWORD}@store:5432/${id}`;
17
+ // ClickHouse names its user and database with underscores; the id may hold a hyphen.
18
+ const chName = (id) => id.replaceAll('-', '_');
19
+ export const clickhouseUrl = (id) => `http://${chName(id)}:${STORE_PASSWORD}@store:8123/${chName(id)}`;
20
+ // A part that serves reads a store: postgres by URL in the env, clickhouse by the URL file (G1, G2).
21
+ export const runsStore = (pkg) => hasStore(pkg, 'postgres') || hasStore(pkg, 'clickhouse');
22
+ const servesStore = (pkg, part) => runsStore(pkg) && part !== 'ui';
23
+ // A git store: the parts share its folder on one volume; each keeps its own lock in /tmp (no lock across containers: docs/tool.md).
24
+ const gitPart = (pkg, part) => hasStore(pkg, 'git') && part !== 'ui' && part !== 'migrate';
12
25
  // Only the ui under `up` names the dev issuer: its CSP then lets the harness ask it for a token.
13
26
  const partEnv = (pkg, part) => ({
14
27
  AGENTAGE_ORIGIN: `http://localhost:${GATEWAY_PORT}`,
@@ -18,9 +31,29 @@ const partEnv = (pkg, part) => ({
18
31
  ...(hasStore(pkg, 'postgres') && part !== 'ui'
19
32
  ? { AGENTAGE_STORE_URL: storeUrl(pkg.agentage.id) }
20
33
  : {}),
34
+ ...(hasStore(pkg, 'clickhouse') && part !== 'ui' && part !== 'migrate'
35
+ ? { AGENTAGE_STORE_URL_FILE: STORE_URL_FILE }
36
+ : {}),
37
+ ...(gitPart(pkg, part) ? { AGENTAGE_RUN_DIR: '/tmp' } : {}),
21
38
  ...(part === 'ui' ? { AGENTAGE_DEV_ISSUER: DEV_ISSUER } : {}),
22
39
  });
23
40
  const QUICK_CHECK = { interval: '2s', timeout: '3s', retries: 30 };
41
+ const clickhouseService = (id) => ({
42
+ image: CLICKHOUSE_IMAGE,
43
+ environment: {
44
+ CLICKHOUSE_USER: chName(id),
45
+ CLICKHOUSE_PASSWORD: STORE_PASSWORD,
46
+ CLICKHOUSE_DB: chName(id),
47
+ },
48
+ volumes: ['store:/var/lib/clickhouse'],
49
+ healthcheck: {
50
+ test: [
51
+ 'CMD-SHELL',
52
+ `clickhouse-client --user ${chName(id)} --password ${STORE_PASSWORD} -q 'SELECT 1'`,
53
+ ],
54
+ ...QUICK_CHECK,
55
+ },
56
+ });
24
57
  const storeService = (id) => ({
25
58
  image: STORE_IMAGE,
26
59
  environment: { POSTGRES_USER: id, POSTGRES_PASSWORD: STORE_PASSWORD, POSTGRES_DB: id },
@@ -30,14 +63,17 @@ const storeService = (id) => ({
30
63
  const HEALTHY = { condition: 'service_healthy' };
31
64
  // api and mcp read the issuer's keys and revoked list before they serve.
32
65
  const dependsOn = (pkg, part) => ({
33
- ...(hasStore(pkg, 'postgres') && part !== 'ui' ? { store: HEALTHY } : {}),
66
+ ...(servesStore(pkg, part) ? { store: HEALTHY } : {}),
34
67
  ...(part === 'api' || part === 'mcp' ? { issuer: HEALTHY } : {}),
35
68
  });
36
69
  const withSecrets = (names) => (names.length ? { secrets: names } : {});
37
70
  const partService = (input, part) => ({
38
71
  image: input.tags[part],
39
72
  environment: partEnv(input.pkg, part),
40
- volumes: [`${input.recordFile}:${RECORD_TARGET}:ro`],
73
+ volumes: [
74
+ `${input.recordFile}:${RECORD_TARGET}:ro`,
75
+ ...(gitPart(input.pkg, part) ? [`store:${DATA_VOLUME}`] : []),
76
+ ],
41
77
  ...withSecrets(mountedIn(input.pkg, part, Object.keys(input.secretFiles ?? {}))),
42
78
  depends_on: dependsOn(input.pkg, part),
43
79
  });
@@ -79,7 +115,9 @@ export const composeFile = (input) => {
79
115
  if (input.tags['api'])
80
116
  services['migrate'] = migrateService(input);
81
117
  }
82
- const volumes = hasStore(input.pkg, 'postgres') ? { store: {} } : {};
118
+ if (hasStore(input.pkg, 'clickhouse'))
119
+ services['store'] = clickhouseService(input.pkg.agentage.id);
120
+ const volumes = runsStore(input.pkg) || hasStore(input.pkg, 'git') ? { store: {} } : {};
83
121
  const secrets = input.secretFiles ? { secrets: secretsOf(input.secretFiles) } : {};
84
122
  return { name: input.project, services, volumes, ...secrets };
85
123
  };
@@ -4,13 +4,23 @@ export const ISSUER_PORT = 4281;
4
4
  export const PART_PORT = 3000;
5
5
  export const TRAEFIK_IMAGE = 'traefik:v3.7.17@sha256:68ae5fe5b64ca166704b746a9e8afcd385e36b3f569a5691401bf652d57b3748';
6
6
  // The URL layout of api-standards section 1, as the estate's gateway renders it.
7
- const RESERVED = 'PathPrefix(`/api/`) || Path(`/mcp`) || PathPrefix(`/mcp/`) || PathPrefix(`/ui/`) || PathPrefix(`/.well-known/`) || PathPrefix(`/git/`) || Path(`/health`)';
7
+ const RESERVED = 'PathPrefix(`/api/`) || Path(`/mcp`) || PathPrefix(`/mcp/`) || PathPrefix(`/ui/`) || PathPrefix(`/.well-known/`) || PathPrefix(`/git/`) || PathPrefix(`/files/`) || Path(`/connector`) || PathPrefix(`/connector/`) || Path(`/health`)';
8
8
  // Each routed part's path, in the order `up` prints them; /mcp is exact, the rest are prefixes.
9
9
  export const PART_PATHS = { pages: '/', ui: '/ui/{version}/', api: '/api/{id}/', mcp: '/mcp' };
10
10
  // In this order, so the first present serves /.well-known/ (api-standards section 1).
11
11
  const ROUTED = ['api', 'mcp', 'pages', 'ui'];
12
12
  export const partPath = (part, { id, version }) => PART_PATHS[part].replace('{version}', version).replace('{id}', id);
13
- const ruleOf = (part, of) => part === 'mcp' ? 'Path(`/mcp`)' : `PathPrefix(\`${partPath(part, of)}\`)`;
13
+ // mcp: bare /mcp, and /mcp/{id}, /connector/{id} and their RFC 9728 documents as the app host routes them.
14
+ const mcpRule = ({ id }) => [
15
+ 'Path(`/mcp`)',
16
+ `Path(\`/mcp/${id}\`)`,
17
+ 'Path(`/connector`)',
18
+ `Path(\`/connector/${id}\`)`,
19
+ `PathRegexp(\`^/\\.well-known/oauth-protected-resource/(mcp|connector)(/${id})?$\`)`,
20
+ ].join(' || ');
21
+ const ruleOf = (part, of) => part === 'mcp' ? mcpRule(of) : `PathPrefix(\`${partPath(part, of)}\`)`;
22
+ // mcp above well-known (api): it serves its own RFC 9728 documents.
23
+ const PRIORITY = { pages: 1, mcp: 110 };
14
24
  const router = (rule, priority, service) => ({
15
25
  rule,
16
26
  priority,
@@ -21,10 +31,13 @@ const router = (rule, priority, service) => ({
21
31
  const partRouters = (routed, of) => {
22
32
  const routers = {};
23
33
  for (const part of routed)
24
- routers[part] = router(ruleOf(part, of), part === 'pages' ? 1 : 100, part);
34
+ routers[part] = router(ruleOf(part, of), PRIORITY[part] ?? 100, part);
25
35
  // The old api prefix, as runPart serves it, until phase 4.
26
36
  if (routed.includes('api'))
27
37
  routers['api-v1'] = router('PathPrefix(`/api/v1/`)', 100, 'api');
38
+ // ctx.files (git smart-HTTP) is on the api part.
39
+ if (routed.includes('api'))
40
+ routers['files'] = router(`PathPrefix(\`/files/${of.id}/\`)`, 100, 'api');
28
41
  if (routed[0])
29
42
  routers['well-known'] = router('PathPrefix(`/.well-known/`)', 100, routed[0]);
30
43
  return routers;
@@ -4,3 +4,4 @@ export declare const secretEnvName: (name: string) => string;
4
4
  export declare const writeUpSecrets: (dir: string, pkg: ExtensionPackage, env: Env) => Promise<{
5
5
  [k: string]: string;
6
6
  } | undefined>;
7
+ export declare const withStoreUrl: (dir: string, pkg: ExtensionPackage, files: Record<string, string> | undefined) => Promise<Record<string, string> | undefined>;
@@ -1,9 +1,10 @@
1
1
  import { chmod, mkdir, writeFile } from 'node:fs/promises';
2
2
  import { join } from 'node:path';
3
3
  import {} from '../../manifest/manifest.schema.js';
4
- import { secretNames } from '../../manifest/parts.js';
4
+ import { hasStore, secretNames } from '../../manifest/parts.js';
5
5
  import { readJsonIfExists } from '../../manifest/read-manifest.js';
6
6
  import {} from '../../runtime/build-info.js';
7
+ import { clickhouseUrl, STORE_URL_SECRET } from './compose.js';
7
8
  import { LOCAL_DIR } from './local-record.js';
8
9
  const FILE = `${LOCAL_DIR}/secrets.json`;
9
10
  export const secretEnvName = (name) => `AGENTAGE_SECRET_${name.toUpperCase().replace(/-/g, '_')}`;
@@ -35,3 +36,14 @@ export const writeUpSecrets = async (dir, pkg, env) => {
35
36
  await writeFile(path, value, { mode: 0o644 }).then(() => chmod(path, 0o644));
36
37
  return Object.fromEntries(files.map(({ name, path }) => [name, path]));
37
38
  };
39
+ // A clickhouse store's URL as one more secret file: mounted at /run/secrets/store-url like the estate does.
40
+ export const withStoreUrl = async (dir, pkg, files) => {
41
+ if (!hasStore(pkg, 'clickhouse'))
42
+ return files;
43
+ if (files?.[STORE_URL_SECRET])
44
+ throw new Error(`up stopped: the declared secret ${STORE_URL_SECRET} would be replaced by the clickhouse store URL: rename it`);
45
+ const path = join(dir, LOCAL_DIR, 'secrets', STORE_URL_SECRET);
46
+ await mkdir(join(dir, LOCAL_DIR, 'secrets'), { recursive: true, mode: 0o700 });
47
+ await writeFile(path, clickhouseUrl(pkg.agentage.id), { mode: 0o644 }).then(() => chmod(path, 0o644));
48
+ return { ...files, [STORE_URL_SECRET]: path };
49
+ };
@@ -9,12 +9,12 @@ import { quietly, runCommand } from '../exec.js';
9
9
  import { exists } from '../stage.js';
10
10
  import { TIMEOUTS } from '../timeouts.js';
11
11
  import { compose } from './compose-run.js';
12
- import { composeFile, STORE_IMAGE } from './compose.js';
12
+ import { CLICKHOUSE_IMAGE, composeFile, runsStore, STORE_IMAGE } from './compose.js';
13
13
  import { GATEWAY_PORT, gatewayConfig, ISSUER_PORT, PART_PATHS, partPath } from './gateway.js';
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
+ import { withStoreUrl, writeUpSecrets } from './secrets.js';
18
18
  import { projectName, workingCopy } from './project.js';
19
19
  import { storePhrase, summaryOf } from './store-line.js';
20
20
  import { assertHealthBodies } from './health.js';
@@ -44,6 +44,8 @@ const buildStep = async (s, env) => {
44
44
  const storeStep = async (s) => {
45
45
  await compose(s.deps.run, s.target, ['up', '-d', 'store'], TIMEOUTS.start);
46
46
  await waitHealthy(s.target, ['store'], s.deps);
47
+ if (hasStore(s.pkg, 'clickhouse'))
48
+ return s.line('store', CLICKHOUSE_IMAGE, 'clickhouse, no migrations');
47
49
  const run = ['run', '--rm', '--no-deps', 'migrate'];
48
50
  const out = await compose(s.deps.run, s.target, run, TIMEOUTS.migrate).catch((err) => {
49
51
  throw new Error(`the migrate job failed, no part was started: ${err.message}`);
@@ -71,7 +73,8 @@ const sessionOf = async (options, deps) => {
71
73
  const file = join(dir, LOCAL_DIR, 'compose.json');
72
74
  const target = { file, project: projectName(pkg.agentage.id, dir) };
73
75
  const line = (label, what, detail) => options.onLine?.(stepLine(label, what, detail));
74
- const secretFiles = await writeUpSecrets(dir, pkg, options.env ?? process.env);
76
+ const declared = await writeUpSecrets(dir, pkg, options.env ?? process.env);
77
+ const secretFiles = await withStoreUrl(dir, pkg, declared);
75
78
  return { dir, pkg, target, line, deps: { ...deps, run: quietly(deps.run) }, secretFiles };
76
79
  };
77
80
  // The laptop shape of a deployment: the release images, a local record, store, issuer, gateway.
@@ -82,10 +85,10 @@ export const up = async (options = {}, deps = { run: runCommand }) => {
82
85
  const commit = await buildStep(s, options.env ?? process.env);
83
86
  // Again after the build: another up may have started meanwhile, and the store comes next.
84
87
  await assertPortsFree(s.deps.run, s.target.project);
85
- if (hasStore(s.pkg, 'postgres'))
88
+ if (runsStore(s.pkg))
86
89
  await storeStep(s);
87
90
  await partsStep(s, commit);
88
- const parts = imageParts(s.pkg).length + (hasStore(s.pkg, 'postgres') ? 1 : 0) + cliParts(s.pkg);
91
+ const parts = imageParts(s.pkg).length + (runsStore(s.pkg) ? 1 : 0) + cliParts(s.pkg);
89
92
  const seconds = Math.round((Date.now() - started) / 1000);
90
93
  s.line('ready', `${plural(parts, 'part')} healthy`, `${seconds} s`);
91
94
  return { parts, seconds, project: s.target.project };
@@ -0,0 +1,9 @@
1
+ import type { HostAdapter } from './app.types.js';
2
+ export declare class AppApiError extends Error {
3
+ readonly code: string;
4
+ readonly status: number;
5
+ constructor(code: string, message: string, status: number);
6
+ }
7
+ export declare const checkApiPath: (path: string) => string;
8
+ export declare const newAgcid: () => string;
9
+ export declare const callApi: <T>(host: HostAdapter, id: string, path: string, init?: RequestInit) => Promise<T>;
@@ -0,0 +1,63 @@
1
+ export class AppApiError extends Error {
2
+ code;
3
+ status;
4
+ constructor(code, message, status) {
5
+ super(message);
6
+ this.code = code;
7
+ this.status = status;
8
+ this.name = 'AppApiError';
9
+ }
10
+ }
11
+ // One path under the app's own api: no scheme, `//`, backslash, or `..` in the path (also encoded).
12
+ export const checkApiPath = (path) => {
13
+ let decoded = path;
14
+ try {
15
+ decoded = decodeURIComponent(path);
16
+ }
17
+ catch {
18
+ throw new AppApiError('FORBIDDEN', `api path refused: ${path}`, 403);
19
+ }
20
+ const bad = !decoded.startsWith('/') ||
21
+ decoded.startsWith('//') ||
22
+ decoded.includes('\\') ||
23
+ /^[a-z][a-z0-9+.-]*:/i.test(decoded) ||
24
+ (decoded.split(/[?#]/)[0] ?? '')
25
+ .split('/')
26
+ .some((segment) => segment === '..' || segment === '.');
27
+ if (bad)
28
+ throw new AppApiError('FORBIDDEN', `api path refused: ${path}`, 403);
29
+ return path;
30
+ };
31
+ const hex = (bytes) => Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
32
+ // A UUIDv7 as 32 lowercase hex, the agcid the kit reads (api-standards section 6).
33
+ export const newAgcid = () => {
34
+ const bytes = crypto.getRandomValues(new Uint8Array(16));
35
+ const ms = Date.now();
36
+ for (let i = 0; i < 6; i++)
37
+ bytes[i] = Math.floor(ms / 2 ** (8 * (5 - i))) & 0xff;
38
+ bytes[6] = 0x70 | ((bytes[6] ?? 0) & 0x0f);
39
+ bytes[8] = 0x80 | ((bytes[8] ?? 0) & 0x3f);
40
+ return hex(bytes);
41
+ };
42
+ const readBody = async (res) => {
43
+ try {
44
+ return (await res.json());
45
+ }
46
+ catch {
47
+ return null;
48
+ }
49
+ };
50
+ export const callApi = async (host, id, path, init = {}) => {
51
+ checkApiPath(path);
52
+ const headers = new Headers(init.headers);
53
+ headers.set('X-Agentage-App', id);
54
+ if (!headers.has('agcid'))
55
+ headers.set('agcid', newAgcid());
56
+ const res = await host.request(id, path, { ...init, headers });
57
+ const body = await readBody(res);
58
+ if (!res.ok || body?.success === false) {
59
+ const code = body?.error?.code ?? `HTTP_${res.status}`;
60
+ throw new AppApiError(code, body?.error?.message ?? res.statusText, res.status);
61
+ }
62
+ return (body && 'success' in body ? body.data : body);
63
+ };
@@ -0,0 +1,65 @@
1
+ export type RegionName = 'lead' | 'actions' | 'aside' | 'notices' | 'bottom' | 'side';
2
+ export type AsideKey = 'inspect' | 'details' | 'inbox';
3
+ export type NoticeKind = 'info' | 'ok' | 'error';
4
+ export interface Notice {
5
+ text: string;
6
+ kind?: NoticeKind;
7
+ }
8
+ export interface AppUser {
9
+ id: string;
10
+ name?: string;
11
+ email?: string;
12
+ }
13
+ export interface ShellPort {
14
+ notify: (notice: Notice) => void;
15
+ openAside: (key: AsideKey) => void;
16
+ closeAside: () => void;
17
+ navigate: (page: string) => void;
18
+ setPages: (pages: PageLink[]) => void;
19
+ setBottomBar: (bar: BottomBar | null) => void;
20
+ }
21
+ export interface PageLink {
22
+ title: string;
23
+ path: string;
24
+ }
25
+ export interface BottomBar {
26
+ title: string;
27
+ count?: number;
28
+ }
29
+ export interface AppRoute {
30
+ path: string;
31
+ query: Readonly<Record<string, string>>;
32
+ }
33
+ export interface AppShell extends ShellPort {
34
+ id: string;
35
+ route: AppRoute;
36
+ }
37
+ export interface HostAdapter {
38
+ user: AppUser | null;
39
+ scopes: string[];
40
+ request: (id: string, path: string, init: RequestInit) => Promise<Response>;
41
+ }
42
+ export interface AppHost {
43
+ id: string;
44
+ user: AppUser | null;
45
+ scopes: string[];
46
+ api: <T = unknown>(path: string, init?: RequestInit) => Promise<T>;
47
+ }
48
+ export interface StateStore {
49
+ has: (key: string) => boolean;
50
+ get: (key: string) => unknown;
51
+ set: (key: string, value: unknown) => void;
52
+ subscribe: (key: string, listener: () => void) => () => void;
53
+ }
54
+ export interface RegionHost {
55
+ node: (name: RegionName) => HTMLElement | null;
56
+ subscribe: (listener: () => void) => () => void;
57
+ }
58
+ export interface AppContextValue {
59
+ id: string;
60
+ route: AppRoute;
61
+ shell: ShellPort;
62
+ host: HostAdapter;
63
+ store: StateStore;
64
+ regions: RegionHost;
65
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,15 @@
1
+ import { Component, type ReactNode } from 'react';
2
+ interface Props {
3
+ name: string;
4
+ children: ReactNode;
5
+ fallback?: (error: Error) => ReactNode;
6
+ }
7
+ interface State {
8
+ error: Error | null;
9
+ }
10
+ export declare class AppBoundary extends Component<Props, State> {
11
+ state: State;
12
+ static getDerivedStateFromError(error: Error): State;
13
+ render(): ReactNode;
14
+ }
15
+ export {};
@@ -0,0 +1,17 @@
1
+ import { jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { Component } from 'react';
3
+ // Around each app root and each Region: a broken app shows a card, the frame keeps working.
4
+ export class AppBoundary extends Component {
5
+ state = { error: null };
6
+ static getDerivedStateFromError(error) {
7
+ return { error };
8
+ }
9
+ render() {
10
+ const { error } = this.state;
11
+ if (!error)
12
+ return this.props.children;
13
+ if (this.props.fallback)
14
+ return this.props.fallback(error);
15
+ return (_jsxs("div", { role: "alert", className: "card-err", "data-error-card": this.props.name, children: [_jsxs("strong", { children: [this.props.name, " failed."] }), " ", error.message] }));
16
+ }
17
+ }
@@ -0,0 +1,5 @@
1
+ import type { AppContextValue, AppHost, AppShell } from './app.types.js';
2
+ export declare const AppContext: import("react").Context<AppContextValue | null>;
3
+ export declare const useAppContext: () => AppContextValue;
4
+ export declare const useAppShell: () => AppShell;
5
+ export declare const useAppHost: () => AppHost;
@@ -0,0 +1,22 @@
1
+ import { createContext, useContext, useMemo } from 'react';
2
+ import { callApi } from './api.js';
3
+ export const AppContext = createContext(null);
4
+ export const useAppContext = () => {
5
+ const ctx = useContext(AppContext);
6
+ if (!ctx)
7
+ throw new Error('@agentage/app: a hook ran outside the shell (no AppContext)');
8
+ return ctx;
9
+ };
10
+ export const useAppShell = () => {
11
+ const { id, route, shell } = useAppContext();
12
+ return useMemo(() => ({ id, route, ...shell }), [id, route, shell]);
13
+ };
14
+ export const useAppHost = () => {
15
+ const { id, host } = useAppContext();
16
+ return useMemo(() => ({
17
+ id,
18
+ user: host.user,
19
+ scopes: host.scopes,
20
+ api: (path, init) => callApi(host, id, path, init),
21
+ }), [id, host]);
22
+ };
@@ -0,0 +1,7 @@
1
+ export type { AppContextValue, AppHost, AppRoute, AppShell, AppUser, AsideKey, HostAdapter, BottomBar, Notice, NoticeKind, RegionHost, RegionName, PageLink, ShellPort, StateStore, } from './app.types.js';
2
+ export { AppApiError, checkApiPath, newAgcid } from './api.js';
3
+ export { AppBoundary } from './boundary.js';
4
+ export { AppContext, useAppHost, useAppShell } from './context.js';
5
+ export { Region } from './region.js';
6
+ export { Split, SPLIT_PREPAINT, splitKey, splitVar, useSplit, type SplitApi, type SplitProps, } from './split.js';
7
+ export { createStateStore, useAppState } from './state-store.js';
@@ -0,0 +1,6 @@
1
+ export { AppApiError, checkApiPath, newAgcid } from './api.js';
2
+ export { AppBoundary } from './boundary.js';
3
+ export { AppContext, useAppHost, useAppShell } from './context.js';
4
+ export { Region } from './region.js';
5
+ export { Split, SPLIT_PREPAINT, splitKey, splitVar, useSplit, } from './split.js';
6
+ export { createStateStore, useAppState } from './state-store.js';
@@ -0,0 +1,6 @@
1
+ import { type ReactNode } from 'react';
2
+ import type { RegionName } from './app.types.js';
3
+ export declare const Region: ({ name, children }: {
4
+ name: RegionName;
5
+ children: ReactNode;
6
+ }) => import("react").ReactPortal | null;
@@ -0,0 +1,14 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { useSyncExternalStore } from 'react';
3
+ import { createPortal } from 'react-dom';
4
+ import { AppBoundary } from './boundary.js';
5
+ import { useAppContext } from './context.js';
6
+ // Renders children into a frame region (a portal), so the app keeps one React tree and one state.
7
+ export const Region = ({ name, children }) => {
8
+ const { id, regions } = useAppContext();
9
+ const read = () => regions.node(name);
10
+ const node = useSyncExternalStore(regions.subscribe, read, () => null);
11
+ if (!node)
12
+ return null;
13
+ return createPortal(_jsx(AppBoundary, { name: `${id} ${name}`, children: children }), node);
14
+ };
@@ -0,0 +1,20 @@
1
+ import { type ResizableSplitApi } from '@agentage/design-system/resizable-split';
2
+ import { type ReactNode, type Ref } from 'react';
3
+ export { useResizableSplit as useSplit } from '@agentage/design-system/resizable-split';
4
+ export type { ResizableSplitApi as SplitApi } from '@agentage/design-system/resizable-split';
5
+ export declare const splitKey: (app: string, id: string) => string;
6
+ export declare const splitVar: (app: string, id: string) => string;
7
+ export declare const SPLIT_PREPAINT = "try{var d=document.documentElement,L=localStorage,E=function(k){return k.replace(/[^A-Za-z0-9-]/g,function(c){return '_'+c.charCodeAt(0).toString(16)+'_'})};for(var i=0;i<L.length;i++){var k=L.key(i),m=/^ag\\.split\\.[a-z0-9-]+\\.[a-z0-9-]+$/.test(k),n=parseInt(L.getItem(k),10);if(m&&n>0&&n<8000)d.style.setProperty('--split-'+E(k),n+'px');if(m&&L.getItem(k+'.collapsed')==='1')d.style.setProperty('--splitc-'+E(k),'0px')}}catch(e){}";
8
+ export interface SplitProps {
9
+ id: string;
10
+ init: number;
11
+ min: number;
12
+ max: number;
13
+ label?: string;
14
+ orientation?: 'horizontal' | 'vertical';
15
+ collapsible?: boolean;
16
+ apiRef?: Ref<ResizableSplitApi>;
17
+ pane?: 0 | 1;
18
+ children: [ReactNode, ReactNode];
19
+ }
20
+ export declare const Split: ({ id, pane, children, ...rest }: SplitProps) => import("react").JSX.Element;
@@ -0,0 +1,38 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { ResizableSplit } from '@agentage/design-system/resizable-split';
3
+ import { useEffect, useState } from 'react';
4
+ import { useAppContext } from './context.js';
5
+ export { useResizableSplit as useSplit } from '@agentage/design-system/resizable-split';
6
+ const NAME = /^[a-z0-9-]+$/;
7
+ const PHONE = '(max-width: 759px)';
8
+ // The stored size key; the design-system split names its CSS variables from it.
9
+ export const splitKey = (app, id) => `ag.split.${app}.${id}`;
10
+ // The design-system encoding of a storage key in a CSS variable name (`.` -> `_2e_`).
11
+ const encode = (key) => key.replace(/[^A-Za-z0-9-]/g, (c) => `_${(c.codePointAt(0) ?? 0).toString(16)}_`);
12
+ export const splitVar = (app, id) => `--split-${encode(splitKey(app, id))}`;
13
+ // Runs in the page head before any module: every stored `ag.split.{app}.{id}` (size and collapsed)
14
+ // is registered by its key pattern and set as the design-system split variables, so the first
15
+ // paint is final. A test holds the names equal to resizableSplitVar and resizableSplitCollapsedVar.
16
+ export const SPLIT_PREPAINT = `try{var d=document.documentElement,L=localStorage,E=function(k){return k.replace(/[^A-Za-z0-9-]/g,function(c){return '_'+c.charCodeAt(0).toString(16)+'_'})};for(var i=0;i<L.length;i++){var k=L.key(i),m=/^ag\\.split\\.[a-z0-9-]+\\.[a-z0-9-]+$/.test(k),n=parseInt(L.getItem(k),10);if(m&&n>0&&n<8000)d.style.setProperty('--split-'+E(k),n+'px');if(m&&L.getItem(k+'.collapsed')==='1')d.style.setProperty('--splitc-'+E(k),'0px')}}catch(e){}`;
17
+ const usePhone = () => {
18
+ const query = () => typeof window !== 'undefined' && !!window.matchMedia?.(PHONE).matches;
19
+ const [phone, setPhone] = useState(query);
20
+ useEffect(() => {
21
+ const m = window.matchMedia?.(PHONE);
22
+ const on = () => setPhone(m.matches);
23
+ m?.addEventListener?.('change', on);
24
+ return () => m?.removeEventListener?.('change', on);
25
+ }, []);
26
+ return phone;
27
+ };
28
+ // Two panes of an app on the design-system ResizableSplit (px, pre-paint, collapsible).
29
+ export const Split = ({ id, pane = 1, children, ...rest }) => {
30
+ const { id: app } = useAppContext();
31
+ if (!NAME.test(id))
32
+ throw new Error(`Split id "${id}" must match [a-z0-9-]+`);
33
+ const phone = usePhone();
34
+ // Both panes stay mounted (the hidden one keeps its state for the back button).
35
+ if (phone)
36
+ return (_jsxs("div", { className: "split", "data-split": id, "data-phone": pane, style: { height: '100%' }, children: [_jsx("div", { hidden: pane !== 0, children: children[0] }), _jsx("div", { hidden: pane !== 1, children: children[1] })] }));
37
+ return (_jsx(ResizableSplit, { storageKey: splitKey(app, id), "data-split": id, className: "split", ...rest, children: children }));
38
+ };
@@ -0,0 +1,3 @@
1
+ import type { StateStore } from './app.types.js';
2
+ export declare const createStateStore: () => StateStore;
3
+ export declare const useAppState: <T>(key: string, init: T) => [T, (value: T) => void];
@@ -0,0 +1,35 @@
1
+ import { useCallback, useState, useSyncExternalStore } from 'react';
2
+ import { useAppContext } from './context.js';
3
+ // One store for every app; keys are `{id}:{key}` so two apps never share a value.
4
+ export const createStateStore = () => {
5
+ const values = new Map();
6
+ const listeners = new Map();
7
+ return {
8
+ has: (key) => values.has(key),
9
+ get: (key) => values.get(key),
10
+ set: (key, value) => {
11
+ if (Object.is(values.get(key), value) && values.has(key))
12
+ return;
13
+ values.set(key, value);
14
+ listeners.get(key)?.forEach((listener) => listener());
15
+ },
16
+ subscribe: (key, listener) => {
17
+ const set = listeners.get(key) ?? new Set();
18
+ set.add(listener);
19
+ listeners.set(key, set);
20
+ return () => void set.delete(listener);
21
+ },
22
+ };
23
+ };
24
+ // `state(key)` of the sheet: kept by the shell across a remount; every reader of a key sees one value.
25
+ export const useAppState = (key, init) => {
26
+ const { id, store } = useAppContext();
27
+ // The first init only: a new `[]` or `{}` each render must not be a new snapshot.
28
+ const [first] = useState(() => init);
29
+ const full = `${id}:${key}`;
30
+ const subscribe = useCallback((fn) => store.subscribe(full, fn), [store, full]);
31
+ const read = () => (store.has(full) ? store.get(full) : first);
32
+ const value = useSyncExternalStore(subscribe, read, read);
33
+ const set = useCallback((next) => store.set(full, next), [store, full]);
34
+ return [value, set];
35
+ };