@agentage/extension 0.17.0 → 0.18.2

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 (122) hide show
  1. package/README.md +3 -0
  2. package/dist/api/download.d.ts +14 -0
  3. package/dist/api/download.js +10 -0
  4. package/dist/api/openapi-doc.js +21 -12
  5. package/dist/api/routes.d.ts +4 -1
  6. package/dist/api/routes.js +12 -1
  7. package/dist/host/daemon/app-files.d.ts +13 -0
  8. package/dist/host/daemon/app-files.js +51 -0
  9. package/dist/host/daemon/app-header.d.ts +3 -0
  10. package/dist/host/daemon/app-header.js +12 -0
  11. package/dist/host/daemon/app-reload.d.ts +10 -0
  12. package/dist/host/daemon/app-reload.js +18 -0
  13. package/dist/host/daemon/child.d.ts +1 -0
  14. package/dist/host/daemon/child.js +1 -0
  15. package/dist/host/daemon/cli-user-watch.d.ts +9 -0
  16. package/dist/host/daemon/cli-user-watch.js +47 -0
  17. package/dist/host/daemon/cli-user.d.ts +2 -0
  18. package/dist/host/daemon/cli-user.js +42 -0
  19. package/dist/host/daemon/daemon.d.ts +1 -0
  20. package/dist/host/daemon/daemon.js +16 -2
  21. package/dist/host/daemon/health-routes.d.ts +2 -0
  22. package/dist/host/daemon/health-routes.js +16 -7
  23. package/dist/host/daemon/limits.d.ts +1 -0
  24. package/dist/host/daemon/limits.js +2 -0
  25. package/dist/host/daemon/routes.d.ts +2 -1
  26. package/dist/host/daemon/routes.js +25 -10
  27. package/dist/host/daemon/shell-events.d.ts +9 -0
  28. package/dist/host/daemon/shell-events.js +36 -0
  29. package/dist/host/daemon/shell-routes.d.ts +28 -0
  30. package/dist/host/daemon/shell-routes.js +63 -0
  31. package/dist/host/daemon/supervisor.d.ts +2 -0
  32. package/dist/host/daemon/supervisor.js +2 -1
  33. package/dist/host/data-lock.js +5 -5
  34. package/dist/host/host-env.js +14 -2
  35. package/dist/host/host-extension.js +3 -5
  36. package/dist/host/host-migrations.d.ts +1 -1
  37. package/dist/host/host-migrations.js +2 -2
  38. package/dist/host/host-store.d.ts +1 -0
  39. package/dist/host/host-store.js +1 -1
  40. package/dist/host/host-url-store.d.ts +2 -1
  41. package/dist/host/host-url-store.js +18 -15
  42. package/dist/host/open-store.d.ts +6 -0
  43. package/dist/host/open-store.js +6 -0
  44. package/dist/index.d.ts +2 -1
  45. package/dist/index.js +2 -1
  46. package/dist/manifest/manifest.schema.d.ts +13 -0
  47. package/dist/manifest/manifest.schema.js +16 -2
  48. package/dist/manifest/parts.d.ts +7 -0
  49. package/dist/manifest/parts.js +5 -0
  50. package/dist/manifest/primitives.schema.js +2 -2
  51. package/dist/mcp/mcp-app.d.ts +1 -0
  52. package/dist/mcp/mcp-app.js +1 -1
  53. package/dist/mcp/server.js +19 -5
  54. package/dist/mcp/tools.d.ts +19 -1
  55. package/dist/mcp/tools.js +12 -0
  56. package/dist/runtime/run-part.js +22 -6
  57. package/dist/server/api-routes.js +33 -8
  58. package/dist/server/send-download.d.ts +3 -0
  59. package/dist/server/send-download.js +29 -0
  60. package/dist/shell/dist/index.html +46 -0
  61. package/dist/shell/dist/shell.css +2 -0
  62. package/dist/shell/dist/shell.js +68 -0
  63. package/dist/shell/dist/vendor/app.js +1 -0
  64. package/dist/shell/dist/vendor/chunk-AOJ3DQEL.js +14 -0
  65. package/dist/shell/dist/vendor/chunk-LW5HXGAJ.js +14 -0
  66. package/dist/shell/dist/vendor/chunk-PQJPUKWH.js +14 -0
  67. package/dist/shell/dist/vendor/chunk-SQE76S5B.js +1 -0
  68. package/dist/shell/dist/vendor/jsx-runtime.js +1 -0
  69. package/dist/shell/dist/vendor/react-dom-client.js +33 -0
  70. package/dist/shell/dist/vendor/react-dom.js +1 -0
  71. package/dist/shell/dist/vendor/react.js +1 -0
  72. package/dist/shell/package.json +5 -0
  73. package/dist/tool/app-build.d.ts +13 -0
  74. package/dist/tool/app-build.js +126 -0
  75. package/dist/tool/app-load.d.ts +4 -0
  76. package/dist/tool/app-load.js +34 -0
  77. package/dist/tool/build.js +5 -2
  78. package/dist/tool/check.js +10 -2
  79. package/dist/tool/container-recipe.d.ts +4 -0
  80. package/dist/tool/container-recipe.js +10 -6
  81. package/dist/tool/index.d.ts +1 -0
  82. package/dist/tool/index.js +1 -0
  83. package/dist/tool/main.d.ts +2 -0
  84. package/dist/tool/main.js +8 -1
  85. package/dist/tool/recipe.d.ts +1 -1
  86. package/dist/tool/recipe.js +16 -6
  87. package/dist/tool/rules/app-deps.d.ts +3 -0
  88. package/dist/tool/rules/app-deps.js +25 -0
  89. package/dist/tool/rules/folders.js +1 -1
  90. package/dist/tool/rules/sealing.js +4 -0
  91. package/dist/tool/stage.js +2 -2
  92. package/dist/tool/up/compose.d.ts +4 -0
  93. package/dist/tool/up/compose.js +41 -3
  94. package/dist/tool/up/gateway.js +16 -3
  95. package/dist/tool/up/secrets.d.ts +1 -0
  96. package/dist/tool/up/secrets.js +13 -1
  97. package/dist/tool/up/up.js +8 -5
  98. package/dist/vendor/app/api.d.ts +9 -0
  99. package/dist/vendor/app/api.js +63 -0
  100. package/dist/vendor/app/app.types.d.ts +79 -0
  101. package/dist/vendor/app/app.types.js +1 -0
  102. package/dist/vendor/app/boundary.d.ts +15 -0
  103. package/dist/vendor/app/boundary.js +17 -0
  104. package/dist/vendor/app/context.d.ts +5 -0
  105. package/dist/vendor/app/context.js +24 -0
  106. package/dist/vendor/app/index.d.ts +7 -0
  107. package/dist/vendor/app/index.js +6 -0
  108. package/dist/vendor/app/region.d.ts +6 -0
  109. package/dist/vendor/app/region.js +14 -0
  110. package/dist/vendor/app/split.d.ts +20 -0
  111. package/dist/vendor/app/split.js +38 -0
  112. package/dist/vendor/app/state-store.d.ts +3 -0
  113. package/dist/vendor/app/state-store.js +35 -0
  114. package/dist/vendor/app/test-host.d.ts +31 -0
  115. package/dist/vendor/app/test-host.js +68 -0
  116. package/dist/vendor/app/theme.css +32 -0
  117. package/dist/vendor/logs/events-client.js +38 -13
  118. package/package.json +39 -2
  119. package/schemas/extension-discovery.schema.json +1 -1
  120. package/schemas/extension-package.schema.json +28 -1
  121. package/schemas/extension-record.schema.json +1 -1
  122. package/schemas/health.schema.json +1 -1
@@ -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,79 @@
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 type HostKind = 'cloud' | 'local' | 'desktop';
38
+ export interface HostInfo {
39
+ kind: HostKind;
40
+ url: string;
41
+ }
42
+ export interface ExtensionInfo {
43
+ id: string;
44
+ version: string;
45
+ }
46
+ export interface HostAdapter {
47
+ kind: HostKind;
48
+ url: string;
49
+ version: string;
50
+ user: AppUser | null;
51
+ scopes: string[];
52
+ request: (id: string, path: string, init: RequestInit) => Promise<Response>;
53
+ }
54
+ export interface AppHost {
55
+ id: string;
56
+ extension: ExtensionInfo;
57
+ host: HostInfo;
58
+ user: AppUser | null;
59
+ scopes: string[];
60
+ api: <T = unknown>(path: string, init?: RequestInit) => Promise<T>;
61
+ }
62
+ export interface StateStore {
63
+ has: (key: string) => boolean;
64
+ get: (key: string) => unknown;
65
+ set: (key: string, value: unknown) => void;
66
+ subscribe: (key: string, listener: () => void) => () => void;
67
+ }
68
+ export interface RegionHost {
69
+ node: (name: RegionName) => HTMLElement | null;
70
+ subscribe: (listener: () => void) => () => void;
71
+ }
72
+ export interface AppContextValue {
73
+ id: string;
74
+ route: AppRoute;
75
+ shell: ShellPort;
76
+ host: HostAdapter;
77
+ store: StateStore;
78
+ regions: RegionHost;
79
+ }
@@ -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,24 @@
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
+ extension: { id, version: host.version },
19
+ host: { kind: host.kind, url: host.url },
20
+ user: host.user,
21
+ scopes: host.scopes,
22
+ api: (path, init) => callApi(host, id, path, init),
23
+ }), [id, host]);
24
+ };
@@ -0,0 +1,7 @@
1
+ export type { AppContextValue, AppHost, AppRoute, AppShell, AppUser, AsideKey, HostAdapter, BottomBar, ExtensionInfo, HostInfo, HostKind, 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
+ };
@@ -0,0 +1,31 @@
1
+ import { type ReactNode } from 'react';
2
+ import type { AppRoute, AppUser, AsideKey, BottomBar, HostInfo, Notice, PageLink, StateStore } from './app.types.js';
3
+ export interface TestCall {
4
+ id: string;
5
+ path: string;
6
+ method: string;
7
+ headers: Record<string, string>;
8
+ body?: unknown;
9
+ }
10
+ export interface TestRecord {
11
+ notices: Notice[];
12
+ calls: TestCall[];
13
+ aside: AsideKey | null;
14
+ pages: string[];
15
+ pageLinks: PageLink[];
16
+ bottomBar: BottomBar | null;
17
+ }
18
+ export interface TestHostProps {
19
+ id: string;
20
+ children: ReactNode;
21
+ user?: AppUser | null;
22
+ scopes?: string[];
23
+ version?: string;
24
+ at?: HostInfo;
25
+ reply?: (call: TestCall) => unknown;
26
+ record?: TestRecord;
27
+ store?: StateStore;
28
+ route?: AppRoute;
29
+ }
30
+ export declare const createTestRecord: () => TestRecord;
31
+ export declare const TestHost: (props: TestHostProps) => import("react").JSX.Element;
@@ -0,0 +1,68 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { useMemo, useState } from 'react';
3
+ import { AppContext } from './context.js';
4
+ import { createStateStore } from './state-store.js';
5
+ const REGIONS = ['lead', 'actions', 'aside', 'notices', 'bottom', 'side'];
6
+ const TEST_USER = { id: 'u-test', name: 'Test User' };
7
+ const NO_SCOPES = [];
8
+ const TEST_AT = { kind: 'local', url: 'http://127.0.0.1:4243' };
9
+ const HOME = { path: '', query: {} };
10
+ const echo = (call) => ({ path: call.path });
11
+ export const createTestRecord = () => ({
12
+ notices: [],
13
+ calls: [],
14
+ aside: null,
15
+ pages: [],
16
+ pageLinks: [],
17
+ bottomBar: null,
18
+ });
19
+ const testRequest = (record, reply) => async (id, path, init) => {
20
+ const headers = Object.fromEntries(new Headers(init.headers).entries());
21
+ const body = typeof init.body === 'string' ? JSON.parse(init.body) : undefined;
22
+ const call = { id, path, method: init.method ?? 'GET', headers, body };
23
+ record.calls.push(call);
24
+ return new Response(JSON.stringify({ success: true, data: reply(call) }), {
25
+ headers: { 'Content-Type': 'application/json' },
26
+ });
27
+ };
28
+ const testShell = (record) => ({
29
+ notify: (n) => void record.notices.push(n),
30
+ openAside: (key) => void (record.aside = key),
31
+ closeAside: () => void (record.aside = null),
32
+ navigate: (page) => void record.pages.push(page),
33
+ setPages: (pages) => void (record.pageLinks = pages),
34
+ setBottomBar: (bar) => void (record.bottomBar = bar),
35
+ });
36
+ const useRegionHost = () => {
37
+ const [nodes] = useState(() => new Map());
38
+ const [listeners] = useState(() => new Set());
39
+ const host = useMemo(() => ({
40
+ node: (name) => nodes.get(name) ?? null,
41
+ subscribe: (fn) => (listeners.add(fn), () => void listeners.delete(fn)),
42
+ }), [nodes, listeners]);
43
+ const ref = (name) => (el) => {
44
+ if (el)
45
+ nodes.set(name, el);
46
+ else
47
+ nodes.delete(name);
48
+ listeners.forEach((fn) => fn());
49
+ };
50
+ return [host, ref];
51
+ };
52
+ // A small shell for unit tests of an app: the six regions as divs and an in-memory host.
53
+ export const TestHost = (props) => {
54
+ const [record] = useState(() => props.record ?? createTestRecord());
55
+ const [store] = useState(() => props.store ?? createStateStore());
56
+ const [regions, regionRef] = useRegionHost();
57
+ const { id, user = TEST_USER, scopes = NO_SCOPES, reply = echo, route = HOME } = props;
58
+ const { version = '0.0.0', at = TEST_AT } = props;
59
+ const value = useMemo(() => ({
60
+ id,
61
+ route,
62
+ store,
63
+ regions,
64
+ host: { ...at, version, user, scopes, request: testRequest(record, reply) },
65
+ shell: testShell(record),
66
+ }), [id, route, store, regions, user, scopes, record, reply, version, at]);
67
+ return (_jsxs(AppContext.Provider, { value: value, children: [_jsx("div", { "data-region": "main", children: props.children }), REGIONS.map((name) => (_jsx("div", { "data-region": name, ref: regionRef(name) }, name)))] }));
68
+ };
@@ -0,0 +1,32 @@
1
+ /* K11: the shell-samples/index.html hex values under the design-system token names, dark only. */
2
+ @theme {
3
+ --color-background: #1f2028;
4
+ --color-foreground: #ffffff;
5
+ --color-card: #2e3039;
6
+ --color-card-foreground: #ffffff;
7
+ --color-popover: #2e3039;
8
+ --color-popover-foreground: #ffffff;
9
+ --color-sidebar: #1f2028;
10
+ --color-sidebar-foreground: #ffffff;
11
+ --color-sidebar-border: #3a3d4a;
12
+ --color-primary: #f5a623;
13
+ --color-primary-foreground: #1f2028;
14
+ --color-primary-emphasis: #f5a623;
15
+ --color-primary-soft: rgb(245 166 35 / 0.12);
16
+ --color-primary-hover: #d97706;
17
+ --color-secondary: #2e3039;
18
+ --color-secondary-foreground: #ffffff;
19
+ --color-accent: #3a3d4a;
20
+ --color-accent-foreground: #ffffff;
21
+ --color-muted: #2e3039;
22
+ --color-muted-foreground: #a9adc1;
23
+ --color-destructive: #f08a7e;
24
+ --color-destructive-foreground: #1f2028;
25
+ --color-success: #5fd08f;
26
+ --color-success-foreground: #1f2028;
27
+ --color-border: #3a3d4a;
28
+ --color-input: #3a3d4a;
29
+ --color-ring: #f5a623;
30
+ --font-sans: system-ui, -apple-system, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
31
+ --font-mono: ui-monospace, SFMono-Regular, Menlo, Consolas, 'Liberation Mono', monospace;
32
+ }