@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
@@ -0,0 +1,14 @@
1
+ import { type Readable } from 'node:stream';
2
+ declare const FILE: unique symbol;
3
+ export type DownloadBody = string | Uint8Array | Readable | ReadableStream<Uint8Array>;
4
+ export interface DownloadOptions {
5
+ filename?: string;
6
+ contentType?: string;
7
+ }
8
+ export interface DownloadAnswer extends DownloadOptions {
9
+ readonly [FILE]: true;
10
+ body: DownloadBody;
11
+ }
12
+ export declare const download: (body: DownloadBody, options?: DownloadOptions) => DownloadAnswer;
13
+ export declare const isDownload: (value: unknown) => value is DownloadAnswer;
14
+ export {};
@@ -0,0 +1,10 @@
1
+ import {} from 'node:stream';
2
+ // A registry symbol, so a file made by a second copy of the kit is still recognised.
3
+ const FILE = Symbol.for('agentage.extension.download');
4
+ // What a route that declares produces returns: bytes or a stream sent as they are, not the envelope.
5
+ export const download = (body, options = {}) => ({
6
+ [FILE]: true,
7
+ body,
8
+ ...options,
9
+ });
10
+ export const isDownload = (value) => typeof value === 'object' && value !== null && value[FILE] === true;
@@ -0,0 +1,17 @@
1
+ import { type Caller } from '../auth/token-check.js';
2
+ export type FilesHandler = (...args: never[]) => unknown;
3
+ export interface FilesOptions {
4
+ owner?: (req: never, caller: Caller | null) => boolean | Promise<boolean>;
5
+ maxPushBytes?: number;
6
+ }
7
+ export interface FilesEntry {
8
+ handler: FilesHandler;
9
+ options: FilesOptions;
10
+ }
11
+ export type FilesRegistrar = (handler: FilesHandler, options?: FilesOptions) => void;
12
+ export declare const createFilesRegistry: () => {
13
+ files: FilesRegistrar;
14
+ served: {
15
+ files?: FilesEntry;
16
+ };
17
+ };
@@ -0,0 +1,10 @@
1
+ import {} from '../auth/token-check.js';
2
+ export const createFilesRegistry = () => {
3
+ const served = {};
4
+ const files = (handler, options = {}) => {
5
+ if (served.files)
6
+ throw new Error('files are registered twice');
7
+ served.files = { handler, options };
8
+ };
9
+ return { files, served };
10
+ };
@@ -0,0 +1,8 @@
1
+ import { type Express, type Request } from 'express';
2
+ import { type Access, type TokenCheck } from '../auth/token-check.js';
3
+ import { type FilesEntry } from './files-registry.js';
4
+ export declare const filesPathOf: (id: string) => string;
5
+ export declare const filesAccess: (req: Request) => Access;
6
+ export declare const hasDotSegment: (path: string) => boolean;
7
+ export declare const bearerOf: (authorization: string | undefined) => string | undefined;
8
+ export declare const mountFiles: (app: Express, id: string, entry: FilesEntry, check?: TokenCheck) => undefined;
@@ -0,0 +1,82 @@
1
+ import {} from 'express';
2
+ import { setCaller } from '../auth/token-check.js';
3
+ import { fail, isFailure } from '../envelope/envelope.js';
4
+ import {} from './files-registry.js';
5
+ export const filesPathOf = (id) => `/files/${id}`;
6
+ const UPLOAD = 'git-upload-pack';
7
+ // The raw query is exactly one service=git-upload-pack: no second or encoded key, no other text.
8
+ const onlyUploadService = (req) => {
9
+ const at = req.originalUrl.indexOf('?');
10
+ return at >= 0 && req.originalUrl.slice(at + 1) === `service=${UPLOAD}`;
11
+ };
12
+ // Default deny: only a clone or fetch reads; anything else (a push, any odd form) needs write.
13
+ export const filesAccess = (req) => {
14
+ if (req.method === 'GET' && req.path.endsWith('/info/refs') && onlyUploadService(req))
15
+ return 'read';
16
+ if (req.method === 'POST' && req.path.endsWith(`/${UPLOAD}`) && !req.originalUrl.includes('?'))
17
+ return 'read';
18
+ return 'write';
19
+ };
20
+ const decoded = (segment) => {
21
+ try {
22
+ return decodeURIComponent(segment);
23
+ }
24
+ catch {
25
+ return '..';
26
+ }
27
+ };
28
+ // A dot segment, raw or encoded (also one hidden behind an encoded slash), never reaches the handler.
29
+ export const hasDotSegment = (path) => path
30
+ .split('/')
31
+ .flatMap((segment) => decoded(segment).split(/[/\\]/))
32
+ .some((segment) => segment === '..' || segment === '.');
33
+ // git sends the token as the Basic password; a Bearer header passes as it is.
34
+ export const bearerOf = (authorization) => {
35
+ const [scheme = '', credential = ''] = (authorization ?? '').split(' ');
36
+ if (scheme.toLowerCase() !== 'basic')
37
+ return authorization;
38
+ const decodedBasic = Buffer.from(credential, 'base64').toString('utf8');
39
+ return `Bearer ${decodedBasic.slice(decodedBasic.indexOf(':') + 1)}`;
40
+ };
41
+ // git asks for credentials only after a 401 that names Basic.
42
+ const BASIC = { 'WWW-Authenticate': 'Basic realm="agentage"' };
43
+ const callerFor = async (req, access, check) => {
44
+ if (!check)
45
+ return null;
46
+ return check(bearerOf(req.get('authorization')), access).catch((err) => {
47
+ if (isFailure(err) && err.status === 401)
48
+ throw fail('UNAUTHORIZED', err.message, { headers: BASIC });
49
+ throw err;
50
+ });
51
+ };
52
+ const tooLarge = () => fail('PAYLOAD_TOO_LARGE', 'The push is too large');
53
+ // Counts the bytes as the socket delivers them, so a chunked push stops at the cap too.
54
+ const capBody = (req, max) => {
55
+ if (Number(req.get('content-length') ?? 0) > max)
56
+ throw tooLarge();
57
+ let bytes = 0;
58
+ const push = req.push.bind(req);
59
+ req.push = (chunk, encoding) => {
60
+ bytes += chunk ? chunk.length : 0;
61
+ if (bytes <= max)
62
+ return push(chunk, encoding);
63
+ req.destroy(tooLarge());
64
+ return false;
65
+ };
66
+ };
67
+ const filesGuard = (options, check) => async (req, res, next) => {
68
+ if (hasDotSegment(req.path))
69
+ throw fail('VALIDATION_ERROR', 'A path may not hold a dot segment');
70
+ const access = filesAccess(req);
71
+ const caller = await callerFor(req, access, check);
72
+ if (caller)
73
+ res.setHeader('Cache-Control', 'no-store');
74
+ setCaller(req, caller);
75
+ if (options.owner && !(await options.owner(req, caller)))
76
+ throw fail('FORBIDDEN', 'Not the owner of this path');
77
+ if (access === 'write' && options.maxPushBytes !== undefined)
78
+ capBody(req, options.maxPushBytes);
79
+ next();
80
+ };
81
+ // No token check (a daemon child): anonymous, but the dot, owner and size checks still run.
82
+ export const mountFiles = (app, id, entry, check) => void app.use(filesPathOf(id), filesGuard(entry.options, check), entry.handler);
@@ -14,16 +14,21 @@ const bare = (zod, io) => {
14
14
  const json = (schema) => ({ 'application/json': { schema } });
15
15
  const content = (description, schema) => ({ description, content: json(schema) });
16
16
  const STRING = { type: 'string' };
17
- const okResponse = (spec) => spec.status === 204 ? { description: 'no content' } : okBody(spec);
18
- const okBody = ({ output, etag }) => ({
19
- ...content('the envelope', {
20
- type: 'object',
21
- properties: {
22
- success: { type: 'boolean', const: true },
23
- data: output ? bare(output, 'output') : {},
24
- },
25
- required: ['success', 'data'],
26
- }),
17
+ const BINARY = { type: 'string', format: 'binary' };
18
+ const okResponse = (spec) => {
19
+ if (spec.produces)
20
+ return { description: 'the file', content: { [spec.produces]: { schema: BINARY } } };
21
+ return spec.status === 204 ? { description: 'no content' } : okBody(spec);
22
+ };
23
+ const envelopeOf = (data) => ({
24
+ type: 'object',
25
+ properties: { success: { type: 'boolean', const: true }, data },
26
+ required: ['success', 'data'],
27
+ });
28
+ const okBody = ({ output, etag, bare: asIs }) => ({
29
+ ...(asIs
30
+ ? content('the body', output ? bare(output, 'output') : {})
31
+ : content('the envelope', envelopeOf(output ? bare(output, 'output') : {}))),
27
32
  ...(etag && { headers: { ETag: { schema: STRING } } }),
28
33
  });
29
34
  const refusal = (code) => content(code, { $ref: '#/components/schemas/Error' });
@@ -52,10 +57,13 @@ const queryParameters = ({ method, spec }) => [
52
57
  ...(spec.query ? queryOf(spec.query) : []),
53
58
  ];
54
59
  const IF_MATCH = { name: 'If-Match', in: 'header', required: false, schema: STRING };
60
+ const IF_NONE_MATCH = { ...IF_MATCH, name: 'If-None-Match' };
61
+ // A bare GET with an ETag is a conditional GET: If-None-Match and 304, not If-Match and 412.
62
+ const conditionalGet = ({ method, spec }) => method === 'get' && spec.bare === true && spec.etag === true;
55
63
  const parameters = (entry) => [
56
64
  ...pathParameters(entry),
57
65
  ...queryParameters(entry),
58
- ...(entry.spec.etag ? [IF_MATCH] : []),
66
+ ...(entry.spec.etag ? [conditionalGet(entry) ? IF_NONE_MATCH : IF_MATCH] : []),
59
67
  ];
60
68
  const responses = (entry) => {
61
69
  const { input, params, scope, etag } = entry.spec;
@@ -64,8 +72,9 @@ const responses = (entry) => {
64
72
  ...((input || params) && { '400': refusal('VALIDATION_ERROR') }),
65
73
  ...(scope !== 'public' && { '401': refusal('UNAUTHORIZED'), '403': refusal('FORBIDDEN') }),
66
74
  ...(entry.path.includes('{') && { '404': refusal('NOT_FOUND') }),
75
+ ...(conditionalGet(entry) && { '304': { description: 'not modified' } }),
67
76
  // If-Match absent on a PUT overwrites (no 428); only a stale tag is refused.
68
- ...(etag && { '412': refusal('PRECONDITION_FAILED') }),
77
+ ...(etag && !conditionalGet(entry) && { '412': refusal('PRECONDITION_FAILED') }),
69
78
  };
70
79
  };
71
80
  const securityOf = (id, scope) => {
@@ -2,6 +2,8 @@ import { type z } from 'zod';
2
2
  import { type Access, type Caller } from '../auth/token-check.js';
3
3
  import { type PartContext } from '../context/context.js';
4
4
  import { type Reply } from '../envelope/envelope.js';
5
+ import { type DownloadAnswer } from './download.js';
6
+ import { type FilesRegistrar } from './files-registry.js';
5
7
  import { type WellKnownRegistrar } from './well-known.js';
6
8
  export declare const ROUTE_METHODS: readonly ["get", "post", "put", "patch", "delete"];
7
9
  export type RouteMethod = (typeof ROUTE_METHODS)[number];
@@ -15,6 +17,8 @@ export interface RouteSpec<I extends ObjectSchema, O extends z.ZodType, S extend
15
17
  query?: Y;
16
18
  etag?: true;
17
19
  status?: 200 | 201 | 204;
20
+ bare?: true;
21
+ produces?: string;
18
22
  }
19
23
  export type ParamsOf<P extends string> = P extends `${string}{${infer N}}${infer R}` ? {
20
24
  [K in N]: string;
@@ -28,7 +32,7 @@ export interface RouteRequest<I, P extends string, S extends Access = Access, Q
28
32
  ifMatch?: string;
29
33
  header: (name: string) => string | undefined;
30
34
  }
31
- type Answer<T> = T | Reply<T>;
35
+ type Answer<T> = T | Reply<T> | DownloadAnswer;
32
36
  export type RouteHandler<I extends ObjectSchema, O extends z.ZodType, P extends string, S extends Access = Access, Q extends ObjectSchema = never, Y extends ObjectSchema = never> = (request: RouteRequest<z.output<I>, P, S, [
33
37
  Q
34
38
  ] extends [never] ? never : z.output<Q>, [
@@ -38,6 +42,7 @@ export type RouteRegistrar = <P extends string, I extends ObjectSchema = z.ZodOb
38
42
  export interface ApiContext extends PartContext {
39
43
  readonly route: RouteRegistrar;
40
44
  readonly wellKnown: WellKnownRegistrar;
45
+ readonly files: FilesRegistrar;
41
46
  }
42
47
  type Params = Record<string, unknown>;
43
48
  export interface RouteEntry {
@@ -51,5 +56,9 @@ export declare const createRouteRegistry: () => {
51
56
  documents: import("./well-known.js").WellKnownEntry[];
52
57
  route: RouteRegistrar;
53
58
  routes: RouteEntry[];
59
+ files: FilesRegistrar;
60
+ filesServed: {
61
+ files?: import("./files-registry.js").FilesEntry;
62
+ };
54
63
  };
55
64
  export {};
@@ -2,9 +2,19 @@ import {} from 'zod';
2
2
  import { badScope } from '../auth/token-check.js';
3
3
  import {} from '../context/context.js';
4
4
  import {} from '../envelope/envelope.js';
5
+ import {} from './download.js';
6
+ import { createFilesRegistry } from './files-registry.js';
5
7
  import { createWellKnownRegistry } from './well-known.js';
6
8
  export const ROUTE_METHODS = ['get', 'post', 'put', 'patch', 'delete'];
7
9
  const PATH = /^(\/([A-Za-z0-9._~-]+|\{[A-Za-z_][A-Za-z0-9_]*\}))+$/;
10
+ const MEDIA_TYPE = /^[a-z0-9][\w.+-]*\/[a-z0-9][\w.+-]*$/i;
11
+ const producesProblem = ({ produces = '', output, status, etag }) => {
12
+ if (!MEDIA_TYPE.test(produces))
13
+ return `produces ${produces}: a media type, as application/zip`;
14
+ if (output || etag || (status ?? 200) !== 200)
15
+ return 'produces a file: no output, etag or status';
16
+ return null;
17
+ };
8
18
  const problemOf = (routes, { method, path, spec }) => {
9
19
  if (!ROUTE_METHODS.includes(method))
10
20
  return `method ${String(method)}: one of get, post, put, patch, delete`;
@@ -14,7 +24,9 @@ const problemOf = (routes, { method, path, spec }) => {
14
24
  return 'is registered twice';
15
25
  if (!spec.summary)
16
26
  return 'needs a summary: it documents the route';
17
- return badScope(spec.scope);
27
+ if (spec.bare && spec.produces)
28
+ return 'bare answers JSON, produces a download: pick one';
29
+ return (spec.produces !== undefined && producesProblem(spec)) || badScope(spec.scope);
18
30
  };
19
31
  export const createRouteRegistry = () => {
20
32
  const routes = [];
@@ -25,5 +37,6 @@ export const createRouteRegistry = () => {
25
37
  throw new Error(`route ${String(method).toUpperCase()} ${path} ${problem}`);
26
38
  routes.push(entry);
27
39
  };
28
- return { route, routes, ...createWellKnownRegistry() };
40
+ const { files, served } = createFilesRegistry();
41
+ return { route, routes, files, filesServed: served, ...createWellKnownRegistry() };
29
42
  };
@@ -7,7 +7,7 @@ export interface Caller {
7
7
  scopes: readonly string[];
8
8
  }
9
9
  export declare const withJti: (caller: Caller, jti: string | undefined) => Caller;
10
- export type TokenCheck = (authorization: string | undefined, access: Access) => Promise<Caller | null>;
10
+ export type TokenCheck = (authorization: string | undefined, access: Access, at?: string) => Promise<Caller | null>;
11
11
  export declare const setCaller: (request: object, caller: Caller | null) => void;
12
12
  export declare const callerOf: (request: object) => Caller | null;
13
13
  export declare const rank: (access: Access) => number;
@@ -10,9 +10,9 @@ const ClaimsSchema = z.object({
10
10
  jti: z.string().optional(),
11
11
  });
12
12
  const unavailable = (message) => fail('UNAVAILABLE', message, { retryAfter: 5 });
13
- const invalid = (origin, message = 'Invalid token') => fail('UNAUTHORIZED', message, {
13
+ const invalid = (origin, message = 'Invalid token', at = '') => fail('UNAUTHORIZED', message, {
14
14
  headers: {
15
- 'WWW-Authenticate': `Bearer resource_metadata="${origin}/.well-known/oauth-protected-resource"`,
15
+ 'WWW-Authenticate': `Bearer resource_metadata="${origin}/.well-known/oauth-protected-resource${at}"`,
16
16
  },
17
17
  });
18
18
  const forbidden = (scope) => fail('FORBIDDEN', `Needs ${scope}`, {
@@ -36,34 +36,34 @@ export const remoteKeys = (issuer) => {
36
36
  const held = () => set.jwks() !== undefined;
37
37
  return { keys: keysOrOutage(set), read: () => retryOnce(set.reload), held };
38
38
  };
39
- const claimsOf = async (authorization, deps) => {
39
+ const claimsOf = async (authorization, deps, at) => {
40
40
  const [scheme = '', credential = '', ...rest] = authorization.split(' ');
41
41
  const bearer = scheme.toLowerCase() === 'bearer' && rest.length === 0;
42
42
  const jwt = bearer && credential.startsWith('aga_') ? credential : '';
43
43
  const options = { ...VERIFY, issuer: deps.issuer, audience: deps.audience };
44
44
  const verified = await jwtVerify(jwt.slice(4), deps.keys, options).catch((err) => {
45
- throw isFailure(err) ? err : invalid(deps.origin);
45
+ throw isFailure(err) ? err : invalid(deps.origin, undefined, at);
46
46
  });
47
47
  const claims = ClaimsSchema.safeParse(verified.payload);
48
48
  if (!claims.success || verified.protectedHeader.typ !== 'at+jwt')
49
- throw invalid(deps.origin);
49
+ throw invalid(deps.origin, undefined, at);
50
50
  return claims.data;
51
51
  };
52
52
  export const grants = (scope, id, access) => {
53
53
  const held = new Set(scope.split(' '));
54
54
  return VERBS.some((verb) => rank(verb) >= rank(access) && held.has(`${id}:${verb}`));
55
55
  };
56
- export const createTokenCheck = (deps) => async (authorization, access) => {
56
+ export const createTokenCheck = (deps) => async (authorization, access, at) => {
57
57
  // optional: no bearer is anonymous, but a bearer sent is checked like read, never ignored.
58
58
  if (access === 'public' || (access === 'optional' && !authorization))
59
59
  return null;
60
60
  if (!authorization)
61
- throw invalid(deps.origin, 'Missing token');
62
- const { sub, scope, jti } = await claimsOf(authorization, deps);
61
+ throw invalid(deps.origin, 'Missing token', at);
62
+ const { sub, scope, jti } = await claimsOf(authorization, deps, at);
63
63
  if (jti !== undefined && !deps.revoked.loaded())
64
64
  throw unavailable('Revoked list unavailable');
65
65
  if (jti !== undefined && deps.revoked.has(jti))
66
- throw invalid(deps.origin, 'Token revoked');
66
+ throw invalid(deps.origin, 'Token revoked', at);
67
67
  if (!grants(scope, deps.id, access))
68
68
  throw forbidden(scopeOf(deps.id, access));
69
69
  return withJti({ sub, scopes: scope.split(' ') }, jti);
@@ -1,8 +1,9 @@
1
+ import { type FilesRegistrar } from '../api/files-registry.js';
1
2
  import { type RouteEntry, type RouteRegistrar } from '../api/routes.js';
2
3
  import { type WellKnownRegistrar } from '../api/well-known.js';
3
4
  import type { HealthCheck } from '../health/health.js';
4
5
  import { type SpanRecord } from '../log/span.js';
5
- import { type ToolEntry, type ToolRegistrar } from '../mcp/tools.js';
6
+ import { type McpContext, type ToolEntry, type ToolRegistrar } from '../mcp/tools.js';
6
7
  import { type JobOptions } from '../worker/job-options.js';
7
8
  import { type JobRun } from '../worker/runs.js';
8
9
  import { type Schedule } from '../worker/scheduler.js';
@@ -16,10 +17,13 @@ export interface TestContext extends PartContext {
16
17
  close(): Promise<void>;
17
18
  readonly schedule: Schedule;
18
19
  readonly tool: ToolRegistrar;
20
+ readonly instructions: McpContext['instructions'];
21
+ readonly connector: ToolRegistrar;
19
22
  readonly tools: ToolEntry[];
20
23
  readonly route: RouteRegistrar;
21
24
  readonly routes: RouteEntry[];
22
25
  readonly wellKnown: WellKnownRegistrar;
26
+ readonly files: FilesRegistrar;
23
27
  readonly jobs: ScheduledJob[];
24
28
  readonly spans: SpanRecord[];
25
29
  readonly exits: number[];
@@ -1,8 +1,9 @@
1
+ import {} from '../api/files-registry.js';
1
2
  import { createRouteRegistry } from '../api/routes.js';
2
3
  import {} from '../api/well-known.js';
3
4
  import {} from '../log/log.js';
4
5
  import { createSpan } from '../log/span.js';
5
- import { createToolRegistry } from '../mcp/tools.js';
6
+ import { createToolRegistry, } from '../mcp/tools.js';
6
7
  import { migrate } from '../store/migrations.js';
7
8
  import { createTestStore } from '../store/test-store.js';
8
9
  import {} from '../worker/job-options.js';
@@ -0,0 +1,13 @@
1
+ import { type Express } from 'express';
2
+ import { type Entries } from './entries.js';
3
+ import { type Entry } from './supervisor.js';
4
+ export interface AppRow {
5
+ title: string;
6
+ icon?: string;
7
+ order?: number;
8
+ entry: string;
9
+ css: string;
10
+ }
11
+ export declare const appRowOf: (entry: Entry) => Promise<AppRow | undefined>;
12
+ export declare const hasApp: (entries: Entries, id: string) => Promise<boolean>;
13
+ export declare const appRoutes: (app: Express, entries: Entries) => void;
@@ -0,0 +1,51 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import express, {} from 'express';
4
+ import { fail } from '../../envelope/envelope.js';
5
+ import { APP_DIR, APP_META_FILE, appOf } from '../../manifest/parts.js';
6
+ import { readManifest } from '../../manifest/read-manifest.js';
7
+ import {} from './entries.js';
8
+ import {} from './supervisor.js';
9
+ const HASHED = /^app-[0-9a-f]+\.(?:js|css)$/;
10
+ const builtFiles = async (dir) => {
11
+ const text = await readFile(join(dir, APP_DIR, APP_META_FILE), 'utf8');
12
+ const files = JSON.parse(text);
13
+ const ok = [files.entry, files.css].every((f) => typeof f === 'string' && HASHED.test(f));
14
+ return ok ? files : undefined;
15
+ };
16
+ // The nav row of an enabled entry whose package has the app part, built; else none.
17
+ export const appRowOf = async (entry) => {
18
+ if (!entry.dir || entry.install.enabled === false)
19
+ return undefined;
20
+ const meta = await readManifest(entry.dir).then(appOf, () => undefined);
21
+ const files = meta && (await builtFiles(entry.dir).catch(() => undefined));
22
+ if (!meta || !files)
23
+ return undefined;
24
+ const at = `/app/${entry.id}/`;
25
+ return { ...meta, entry: `${at}${files.entry}`, css: `${at}${files.css}` };
26
+ };
27
+ // The app id of a page path, when the id is installed and has an app row.
28
+ export const hasApp = async (entries, id) => {
29
+ const entry = entries.get(id);
30
+ return entry !== undefined && (await appRowOf(entry)) !== undefined;
31
+ };
32
+ // K5: hashed files never change; index.js and app.json name the newest build.
33
+ const cacheOf = (path) => HASHED.test(path.split('/').pop() ?? '') ? 'immutable' : 'no-cache';
34
+ const setHeaders = (res, path) => {
35
+ const cache = cacheOf(path);
36
+ res.set('Cache-Control', cache === 'immutable' ? 'public, max-age=31536000, immutable' : cache);
37
+ };
38
+ const appDirOf = async (entries, id) => {
39
+ const entry = entries.get(id);
40
+ if (!entry || !(await appRowOf(entry)))
41
+ throw fail('NOT_FOUND', `${id} has no app`);
42
+ return join(entry.dir ?? '', APP_DIR);
43
+ };
44
+ // GET /app/{id}/*: static from the package folder (not the child), so it answers while the child is down.
45
+ const serveApp = (entries) => async (req, res, next) => {
46
+ const root = await appDirOf(entries, String(req.params['id']));
47
+ express.static(root, { fallthrough: false, index: false, dotfiles: 'deny', setHeaders })(req, res, (err) => next(err && fail('NOT_FOUND', `${String(req.params['id'])} has no such app file`)));
48
+ };
49
+ export const appRoutes = (app, entries) => {
50
+ app.use('/app/:id', serveApp(entries));
51
+ };
@@ -0,0 +1,3 @@
1
+ import { type RequestHandler } from 'express';
2
+ export declare const APP_HEADER = "x-agentage-app";
3
+ export declare const ownAppOnly: RequestHandler;
@@ -0,0 +1,12 @@
1
+ import {} from 'express';
2
+ import { fail } from '../../envelope/envelope.js';
3
+ // What useAppHost().api sends: the app that made the call.
4
+ export const APP_HEADER = 'x-agentage-app';
5
+ // K10: an app calls only its own extension; a raw fetch with no header is not stopped (stated limit).
6
+ export const ownAppOnly = (req, _res, next) => {
7
+ const from = req.get(APP_HEADER);
8
+ const id = String(req.params['id']);
9
+ if (from !== undefined && from !== id)
10
+ throw fail('FORBIDDEN', `the app ${from} may not call the extension ${id}`);
11
+ next();
12
+ };
@@ -0,0 +1,10 @@
1
+ import { type Entries } from './entries.js';
2
+ import { type ShellEvents } from './shell-events.js';
3
+ export declare const isAppReload: (body: unknown) => boolean;
4
+ export declare const reloadApp: (entries: Entries, id: string, events: ShellEvents) => Promise<{
5
+ id: string;
6
+ version: string;
7
+ state: import("./supervisor.js").State;
8
+ reloaded: boolean;
9
+ part: string;
10
+ }>;
@@ -0,0 +1,18 @@
1
+ import { fail } from '../../envelope/envelope.js';
2
+ import { appRowOf } from './app-files.js';
3
+ import { entryOf } from './entries.js';
4
+ import {} from './shell-events.js';
5
+ // The body of a reload that names the app part: the child keeps running.
6
+ export const isAppReload = (body) => typeof body === 'object' &&
7
+ body !== null &&
8
+ Object.keys(body).length === 1 &&
9
+ body.part === 'app';
10
+ // K8: the new build is in dist/app already; the shell re-imports the entry the event names.
11
+ export const reloadApp = async (entries, id, events) => {
12
+ const entry = entryOf(entries, id);
13
+ const row = await appRowOf(entry);
14
+ if (!row)
15
+ throw fail('VALIDATION_ERROR', `${id} has no built app: run the app build first`);
16
+ events.send('app', { id, entry: row.entry, css: row.css });
17
+ return { id, version: entry.version, state: entry.state, reloaded: true, part: 'app' };
18
+ };
@@ -7,6 +7,7 @@ interface LaunchSpec {
7
7
  secrets: Record<string, string>;
8
8
  origin: string;
9
9
  storeOpenMs?: number;
10
+ userSub?: string;
10
11
  }
11
12
  export interface Exit {
12
13
  code: number | null;
@@ -6,7 +6,8 @@ import { configDirOf, fillRun, makeRun, undoRun } from './child-files.js';
6
6
  import { lastWords } from './last-words.js';
7
7
  import { LIMITS } from './limits.js';
8
8
  import { pipeRedacted } from './redact-stream.js';
9
- import { permissionFlag, sealFlags, sealOf } from './seal.js';
9
+ import { readManifest } from '../../manifest/read-manifest.js';
10
+ import { permissionFlag, sealFlags, sealOf, spawnsGit } from './seal.js';
10
11
  const HOST_MAIN = fileURLToPath(new URL('../main.js', import.meta.url));
11
12
  const STOP_MS = 5_000;
12
13
  const PASSED = ['PATH', 'HOME', 'TMPDIR', 'LANG', 'NODE_EXTRA_CA_CERTS'];
@@ -20,6 +21,7 @@ export const childEnv = (spec, secretsDir, runDir) => ({
20
21
  AGENTAGE_ORIGIN: spec.origin,
21
22
  ...(runDir && { AGENTAGE_RUN_DIR: runDir }),
22
23
  ...(spec.storeOpenMs && { AGENTAGE_STORE_OPEN_MS: String(spec.storeOpenMs) }),
24
+ ...(spec.userSub && { AGENTAGE_USER_SUB: spec.userSub }),
23
25
  });
24
26
  const passedEnv = () => Object.fromEntries(PASSED.flatMap((k) => (process.env[k] ? [[k, process.env[k]]] : [])));
25
27
  const captured = (child, secrets) => {
@@ -73,12 +75,13 @@ const stopOf = (child, exited) => async () => {
73
75
  clearTimeout(kill);
74
76
  };
75
77
  // The daemon's own node flags (a loader, --input-type) are never the child's; C2 where Node has --permission.
76
- const execArgvOf = (node, main, spec, run) => {
78
+ const execArgvOf = async (node, main, spec, run) => {
77
79
  if (!permissionFlag(node))
78
80
  return [];
79
81
  const configDir = configDirOf(spec.dataDir);
80
82
  const { id, dir, dataDir } = spec;
81
- return sealFlags({ id, main, dir, configDir, runDir: run.runDir, dataDir });
83
+ const childProcess = spawnsGit(await readManifest(dir));
84
+ return sealFlags({ id, main, dir, configDir, runDir: run.runDir, dataDir, childProcess });
82
85
  };
83
86
  // The listed env of the daemon, then the child's own: TMPDIR in run/{id}, the test clock when not 1.
84
87
  const envOf = (spec, run, clockRate) => ({
@@ -88,7 +91,7 @@ const envOf = (spec, run, clockRate) => ({
88
91
  ...(clockRate === 1 ? {} : { [CLOCK_RATE_ENV]: String(clockRate) }),
89
92
  });
90
93
  const started = async (at, spec, run) => {
91
- const execArgv = execArgvOf(at.node, at.main, spec, run);
94
+ const execArgv = await execArgvOf(at.node, at.main, spec, run);
92
95
  await fillRun(run, spec);
93
96
  const stdio = ['ignore', 'pipe', 'pipe', 'ipc'];
94
97
  const child = fork(at.main, [], {
@@ -0,0 +1,8 @@
1
+ import { type Entries } from './entries.js';
2
+ import { type SupervisorDeps } from './supervisor.js';
3
+ export interface CliUser {
4
+ text?: string;
5
+ sub?: string;
6
+ }
7
+ export declare const syncCliUser: (deps: SupervisorDeps, entries: Entries, polls?: number) => Promise<boolean>;
8
+ export declare const watchCliUser: (deps: SupervisorDeps, entries: Entries) => (() => void);
@@ -0,0 +1,43 @@
1
+ import {} from './entries.js';
2
+ import { cliUserOf, readCliAuth } from './cli-user.js';
3
+ import { halt, hold } from './gate.js';
4
+ import { startEntry } from './supervisor.js';
5
+ // A failed session check (offline) is tried again this many polls later, with the same file.
6
+ const RETRY_POLLS = 30;
7
+ const restart = async (deps, entry) => {
8
+ const release = hold(entry);
9
+ try {
10
+ await halt(entry, deps.drainMs);
11
+ await startEntry(deps, entry);
12
+ }
13
+ finally {
14
+ release();
15
+ }
16
+ };
17
+ // Read the file; a new user (sign-in, sign-out, another account) restarts every running child.
18
+ export const syncCliUser = async (deps, entries, polls = 0) => {
19
+ const text = await readCliAuth(deps.configDir);
20
+ const retry = text !== '' && deps.user.sub === undefined && polls % RETRY_POLLS === 0;
21
+ if (text === deps.user.text && !retry)
22
+ return false;
23
+ const sub = await cliUserOf(text);
24
+ const changed = sub !== deps.user.sub;
25
+ Object.assign(deps.user, { text, sub });
26
+ if (!changed)
27
+ return false;
28
+ deps.log.info('cli user changed: running extensions restart', { signedIn: sub !== undefined });
29
+ for (const entry of entries.values())
30
+ if (entry.lane)
31
+ await restart(deps, entry);
32
+ return true;
33
+ };
34
+ // Polled in the change queue, so a restart never runs inside an install, update or reload.
35
+ export const watchCliUser = (deps, entries) => {
36
+ let polls = 0;
37
+ const tick = () => void deps
38
+ .queue(() => syncCliUser(deps, entries, ++polls))
39
+ .catch((err) => deps.log.warn('cli user not read', { reason: err.message }));
40
+ const timer = setInterval(tick, deps.userPollMs);
41
+ timer.unref();
42
+ return () => clearInterval(timer);
43
+ };
@@ -0,0 +1,2 @@
1
+ export declare const cliUserOf: (text: string) => Promise<string | undefined>;
2
+ export declare const readCliAuth: (configDir: string) => Promise<string>;