@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,17 +1,21 @@
1
1
  import { McpServer } from '@modelcontextprotocol/server';
2
2
  import { agcidOf } from '../agcid/agcid.js';
3
+ import {} from '../auth/token-check.js';
3
4
  import { currentAgcid } from '../agcid/current.js';
4
5
  import { fail, isFailure } from '../envelope/envelope.js';
5
6
  import {} from '../log/log.js';
6
- import { prefixed } from './tools.js';
7
+ import { isToolResult, nameOf, } from './tools.js';
7
8
  const text = (value) => [{ type: 'text', text: value }];
8
- // A failed tool: isError, the REST error shape, an agcid (minted outside a request); else INTERNAL.
9
- const errorResult = (err, log, tool) => {
9
+ // A failed tool: isError, else INTERNAL; with an output schema also the REST error shape and an agcid.
10
+ const errorResult = (entry, err, log, tool) => {
10
11
  const failure = isFailure(err) ? err : fail('INTERNAL', 'Internal error');
11
12
  if (failure.status >= 500)
12
13
  log.error(err, tool);
14
+ const content = text(failure.message);
15
+ if (!entry.spec.output)
16
+ return { isError: true, content };
13
17
  const error = { code: failure.code, message: failure.message, agcid: agcidOf(currentAgcid()) };
14
- return { isError: true, content: text(error.message), structuredContent: { error } };
18
+ return { isError: true, content, structuredContent: { error } };
15
19
  };
16
20
  // The kit, not the SDK, refuses bad arguments (C7): the SDK lists the schema, passes all through.
17
21
  const listedOnly = (input) => ({
@@ -24,32 +28,80 @@ const argsOf = (entry, args) => {
24
28
  const fields = new Set(parsed.error.issues.map((issue) => issue.path.join('.') || '(root)'));
25
29
  throw fail('VALIDATION_ERROR', `Invalid arguments: ${[...fields].join(', ')}`);
26
30
  };
27
- const callback = (entry, log, tool) => async (args) => {
31
+ // The tool's own text; its structured part still meets the output schema.
32
+ const ownResultOf = (entry, { content, isError, structuredContent }) => {
33
+ if (isError)
34
+ return { isError, content };
35
+ if (!entry.spec.output)
36
+ return { content };
37
+ const output = entry.spec.output.parse(structuredContent);
38
+ return { content, structuredContent: output };
39
+ };
40
+ // No output schema: the answer is text only, as a client of a tool with no outputSchema expects.
41
+ const resultOf = (entry, value) => {
42
+ if (isToolResult(value))
43
+ return ownResultOf(entry, value);
44
+ if (!entry.spec.output)
45
+ return { content: text(JSON.stringify(value ?? null)) };
46
+ const output = entry.spec.output.parse(value);
47
+ return {
48
+ content: text(JSON.stringify(output)),
49
+ structuredContent: output,
50
+ };
51
+ };
52
+ const callback = (entry, log, tool, caller) => async (args) => {
28
53
  const start = performance.now();
29
54
  const ms = () => Math.round(performance.now() - start);
30
55
  try {
31
- const output = entry.spec.output.parse(await entry.handler(argsOf(entry, args)));
56
+ const result = resultOf(entry, await entry.handler(argsOf(entry, args), caller));
32
57
  log.mcp({ tool, ms: ms() });
33
- const content = text(JSON.stringify(output));
34
- return { content, structuredContent: output };
58
+ return result;
35
59
  }
36
60
  catch (err) {
37
61
  // A 4xx is a rejection, not a failure: the row stays info.
38
62
  log.mcp({ tool, ms: ms(), ...(isFailure(err) && err.status < 500 ? {} : { error: err }) });
39
- return errorResult(err, log, tool);
63
+ return errorResult(entry, err, log, tool);
64
+ }
65
+ };
66
+ // The caller the guard checked rides in authInfo, the SDK's own path to a per-request server.
67
+ export const authInfoOf = (caller, opening) => ({
68
+ token: '',
69
+ clientId: caller?.sub ?? '',
70
+ scopes: [...(caller?.scopes ?? [])],
71
+ extra: { caller, opening },
72
+ });
73
+ const callerOf = (ctx) => ctx?.authInfo?.extra?.['caller'] ?? null;
74
+ const isOpening = (ctx) => ctx?.authInfo?.extra?.['opening'] === true;
75
+ // Unset fields stay off the listing, so a tool that sets none lists as before.
76
+ const configOf = (spec) => ({
77
+ description: spec.description,
78
+ inputSchema: listedOnly(spec.input),
79
+ ...(spec.output && { outputSchema: spec.output }),
80
+ ...(spec.title !== undefined && { title: spec.title }),
81
+ ...(spec.annotations && { annotations: spec.annotations }),
82
+ });
83
+ // A function runs only for the opening message; its failure is logged and the opening has no text.
84
+ const textOf = async (instructions, ctx, log) => {
85
+ if (typeof instructions !== 'function')
86
+ return instructions;
87
+ if (!isOpening(ctx))
88
+ return undefined;
89
+ try {
90
+ return await instructions(callerOf(ctx));
91
+ }
92
+ catch (err) {
93
+ log.error(err, 'instructions');
94
+ return undefined;
40
95
  }
41
96
  };
42
97
  // One fresh server per request (stateless); serverInfo agentage-{id} at the package version.
43
- export const serverFactory = (identity, tools, log) => () => {
44
- const server = new McpServer({ name: `agentage-${identity.id}`, version: identity.version });
98
+ export const serverFactory = (identity, tools, log, instructions) => async (ctx) => {
99
+ const caller = callerOf(ctx);
100
+ const info = { name: `agentage-${identity.id}`, version: identity.version };
101
+ const server = new McpServer(info, { instructions: await textOf(instructions, ctx, log) });
45
102
  for (const entry of tools) {
46
- const config = {
47
- description: entry.spec.description,
48
- inputSchema: listedOnly(entry.spec.input),
49
- outputSchema: entry.spec.output,
50
- };
51
- const tool = prefixed(identity.id, entry.name);
52
- server.registerTool(tool, config, callback(entry, log, tool));
103
+ const tool = nameOf(identity.id, entry.name, identity.bare);
104
+ server.registerTool(tool, configOf(entry.spec), callback(entry, log, tool, caller));
53
105
  }
54
106
  return server;
55
107
  };
@@ -1,26 +1,62 @@
1
1
  import { type z } from 'zod';
2
- import { type Access } from '../auth/token-check.js';
2
+ import { type Access, type Caller } from '../auth/token-check.js';
3
3
  import { type PartContext } from '../context/context.js';
4
4
  type ObjectSchema = z.ZodObject;
5
+ export interface ToolAnnotations {
6
+ readOnlyHint?: boolean;
7
+ destructiveHint?: boolean;
8
+ idempotentHint?: boolean;
9
+ openWorldHint?: boolean;
10
+ }
5
11
  export interface ToolSpec<I extends ObjectSchema, O extends ObjectSchema> {
12
+ title?: string;
6
13
  description: string;
7
14
  input: I;
8
- output: O;
15
+ output?: O;
16
+ annotations?: ToolAnnotations;
9
17
  scope?: Exclude<Access, 'optional'>;
10
18
  }
11
- export type ToolHandler<I extends ObjectSchema, O extends ObjectSchema> = (args: z.output<I>) => z.input<O> | Promise<z.input<O>>;
19
+ export interface TextContent {
20
+ type: 'text';
21
+ text: string;
22
+ }
23
+ declare const TOOL_RESULT: unique symbol;
24
+ export interface ToolResult<T = unknown> {
25
+ readonly [TOOL_RESULT]: true;
26
+ content: TextContent[];
27
+ structuredContent?: T;
28
+ isError?: true;
29
+ }
30
+ export interface ToolResultOptions<T> {
31
+ structured?: T;
32
+ isError?: true;
33
+ }
34
+ export declare const toolResult: <T = never>(text: string | TextContent[], options?: ToolResultOptions<T>) => ToolResult<T>;
35
+ export declare const isToolResult: (value: unknown) => value is ToolResult;
36
+ type Answer<O extends ObjectSchema> = z.input<O> | ToolResult<z.input<O>>;
37
+ export type ToolHandler<I extends ObjectSchema, O extends ObjectSchema> = (args: z.output<I>, caller: Caller | null) => Answer<O> | Promise<Answer<O>>;
12
38
  export type ToolRegistrar = <I extends ObjectSchema, O extends ObjectSchema>(name: string, spec: ToolSpec<I, O>, handler: ToolHandler<I, O>) => void;
39
+ export type Instructions = string | ((caller: Caller | null) => string | Promise<string>);
13
40
  export interface McpContext extends PartContext {
14
41
  readonly tool: ToolRegistrar;
42
+ readonly instructions: (instructions: Instructions) => void;
43
+ readonly connector: ToolRegistrar;
15
44
  }
16
45
  export interface ToolEntry {
17
46
  name: string;
18
47
  spec: ToolSpec<ObjectSchema, ObjectSchema>;
19
- handler: (args: Record<string, unknown>) => unknown;
48
+ handler: (args: Record<string, unknown>, caller: Caller | null) => unknown;
20
49
  }
21
50
  export declare const createToolRegistry: () => {
22
51
  tool: ToolRegistrar;
23
52
  tools: ToolEntry[];
53
+ instructions: (value: Instructions) => void;
54
+ served: {
55
+ instructions?: Instructions;
56
+ };
57
+ connector: ToolRegistrar;
58
+ connectors: ToolEntry[];
24
59
  };
25
60
  export declare const prefixed: (id: string, name: string) => string;
61
+ export declare const nameOf: (id: string, name: string, bare?: boolean) => string;
26
62
  export {};
package/dist/mcp/tools.js CHANGED
@@ -1,22 +1,44 @@
1
1
  import {} from 'zod';
2
2
  import { ACCESS, badScope } from '../auth/token-check.js';
3
3
  import {} from '../context/context.js';
4
+ // A registry symbol, so a result made by a second copy of the kit is still recognised.
5
+ const TOOL_RESULT = Symbol.for('agentage.extension.tool-result');
6
+ // What a tool returns to send its own text (markdown) in place of the kit's JSON of the output.
7
+ export const toolResult = (text, options = {}) => ({
8
+ [TOOL_RESULT]: true,
9
+ content: typeof text === 'string' ? [{ type: 'text', text }] : text,
10
+ ...(options.structured !== undefined && { structuredContent: options.structured }),
11
+ ...(options.isError && { isError: true }),
12
+ });
13
+ export const isToolResult = (value) => typeof value === 'object' &&
14
+ value !== null &&
15
+ value[TOOL_RESULT] === true;
4
16
  const TOOL_NAME = /^[a-z][a-z0-9_-]*$/;
5
17
  const TOOL_ACCESS = ACCESS.filter((access) => access !== 'optional');
18
+ const registrarOn = (tools) => (name, spec, handler) => {
19
+ if (!TOOL_NAME.test(name))
20
+ throw new Error(`tool name ${name}: lowercase, digits, _ and -`);
21
+ if (tools.some((entry) => entry.name === name))
22
+ throw new Error(`tool ${name} is registered twice`);
23
+ if (!spec.description)
24
+ throw new Error(`tool ${name} needs a description: it routes the model`);
25
+ const bad = badScope(spec.scope, TOOL_ACCESS);
26
+ if (bad)
27
+ throw new Error(`tool ${name} ${bad}`);
28
+ tools.push({ name, spec, handler: handler });
29
+ };
6
30
  export const createToolRegistry = () => {
7
31
  const tools = [];
8
- const tool = (name, spec, handler) => {
9
- if (!TOOL_NAME.test(name))
10
- throw new Error(`tool name ${name}: lowercase, digits, _ and -`);
11
- if (tools.some((entry) => entry.name === name))
12
- throw new Error(`tool ${name} is registered twice`);
13
- if (!spec.description)
14
- throw new Error(`tool ${name} needs a description: it routes the model`);
15
- const bad = badScope(spec.scope, TOOL_ACCESS);
16
- if (bad)
17
- throw new Error(`tool ${name} ${bad}`);
18
- tools.push({ name, spec, handler: handler });
32
+ const connectors = [];
33
+ const served = {};
34
+ const instructions = (value) => {
35
+ if (served.instructions !== undefined)
36
+ throw new Error('instructions are set twice');
37
+ served.instructions = value;
19
38
  };
20
- return { tool, tools };
39
+ const [tool, connector] = [registrarOn(tools), registrarOn(connectors)];
40
+ return { tool, tools, instructions, served, connector, connectors };
21
41
  };
22
42
  export const prefixed = (id, name) => `${id}__${name}`;
43
+ // A connector tool keeps its own name (search, fetch); every other is {id}__{name}.
44
+ export const nameOf = (id, name, bare) => bare ? name : prefixed(id, name);
@@ -10,7 +10,8 @@ import {} from '../manifest/manifest.schema.js';
10
10
  import { hasStore } from '../manifest/parts.js';
11
11
  import {} from '../manifest/primitives.schema.js';
12
12
  import { createSpan } from '../log/span.js';
13
- import { mountMcp } from '../mcp/mcp-app.js';
13
+ import { mountWithConnector } from '../mcp/connector.js';
14
+ import {} from '../mcp/mcp-app.js';
14
15
  import { createToolRegistry } from '../mcp/tools.js';
15
16
  import { mountApiRoutes } from '../server/app.js';
16
17
  import { mountApi } from '../server/api-routes.js';
@@ -22,22 +23,27 @@ import {} from './build-info.js';
22
23
  export const callCreate = async (input, part, ctx) => (await loadCreate(input.dir, input.pkg, part, input.importModule))(ctx);
23
24
  const api = async (input) => {
24
25
  const ctx = input.ctx();
25
- const { router, routes, documents } = await mountApi(ctx, (api) => callCreate(input, 'api', api));
26
+ const mounted = await mountApi(ctx, (api) => callCreate(input, 'api', api));
27
+ const { router, routes, documents, files } = mounted;
26
28
  // Declared routes guard at their own scope, whatever the committed file says.
27
29
  const openapi = routes.length > 0 ? generatedOpenapi(input.pkg, routes) : input.openapi;
28
- const options = { ...input.base, router, routes, openapi, wellKnown: documents };
30
+ const options = { ...input.base, router, routes, openapi, wellKnown: documents, files };
29
31
  const record = openapi ? { openapi: openapiPath(input.pkg.agentage.id) } : {};
30
32
  return { mount: (app) => mountApiRoutes(app, { ...options, aliases: input.apiAliases }), record };
31
33
  };
32
34
  const mcp = async (input) => {
33
35
  const registry = createToolRegistry();
34
36
  const ctx = input.ctx();
35
- await callCreate(input, 'mcp', { ...ctx, tool: registry.tool });
37
+ const { tool, instructions, connector, tools: registered, served } = registry;
38
+ await callCreate(input, 'mcp', { ...ctx, tool, instructions, connector });
36
39
  const token = !input.openListing && ctx.settings['mcp.listing'] === 'token';
37
40
  const listing = token ? 'token' : 'open';
38
- const options = { ...input.base, tools: registry.tools, listing, paths: input.mcpPaths };
41
+ const paths = input.mcpPaths;
42
+ const options = { ...input.base, tools: registered, listing, paths, ...served };
43
+ const mount = (app) => mountWithConnector(app, options, registry.connectors);
44
+ // Connector tools stay out of the record: the record lists the {id}__{name} tools only.
39
45
  const tools = toolRecords(input.pkg.agentage.id, registry.tools);
40
- return { mount: (app) => mountMcp(app, options), record: tools.length ? { tools } : {} };
46
+ return { mount, record: tools.length ? { tools } : {} };
41
47
  };
42
48
  const worker = async (input) => {
43
49
  const ctx = input.ctx();
@@ -11,12 +11,16 @@ import { createLog } from '../log/log.js';
11
11
  import {} from '../health/health.js';
12
12
  import {} from '../manifest/entry.js';
13
13
  import {} from '../manifest/manifest.schema.js';
14
- import { hasStore, imageParts } from '../manifest/parts.js';
14
+ import { hasStore, imageParts, storeOf } from '../manifest/parts.js';
15
15
  import {} from '../manifest/primitives.schema.js';
16
16
  import { readManifest } from '../manifest/read-manifest.js';
17
17
  import {} from '../server/app.js';
18
18
  import { serve } from '../server/serve.js';
19
- import { createStore, storeCheck } from '../store/store.js';
19
+ import { MCP_PATH, mcpPathOf } from '../mcp/mcp-app.js';
20
+ import { hostEnvOf } from '../host/host-env.js';
21
+ import { hostStoreChecks } from '../host/host-url-store.js';
22
+ import { openStore } from '../host/open-store.js';
23
+ import { createStore } from '../store/store.js';
20
24
  import {} from '../store/store.types.js';
21
25
  import { buildInfoFromEnv, portFromEnv } from './build-info.js';
22
26
  import { RUNNERS } from './part-runners.js';
@@ -33,8 +37,18 @@ export const partOf = (pkg, part) => {
33
37
  throw new Error(`part ${part} is not an image part of this manifest`);
34
38
  return part;
35
39
  };
36
- // ui serves files and gets no ctx; every other part gets the store when the manifest has postgres.
37
- const storeFor = ({ pkg, part, env, log }) => part !== 'ui' && hasStore(pkg, 'postgres') ? createStore(env, log) : undefined;
40
+ const poolOf = (env, log) => {
41
+ const pool = createStore(env, log);
42
+ return { query: pool.query, close: () => pool.end() };
43
+ };
44
+ // ui gets no ctx; the others get the daemon's store (git, a URL file), else a postgres pool.
45
+ const storeFor = async ({ pkg, part, env, log }, dir) => {
46
+ if (part === 'ui' || !storeOf(pkg))
47
+ return undefined;
48
+ const { dataDir, runDir, storeOpenMs: openMs, storeUrlFile: file } = hostEnvOf(env);
49
+ const opened = await openStore(pkg, { dir, dataDir, runDir, openMs, file, partImage: true }, log);
50
+ return opened ?? (hasStore(pkg, 'postgres') ? poolOf(env, log) : undefined);
51
+ };
38
52
  const contextFor = (start, part, store, checks) => createContext({
39
53
  pkg: start.pkg,
40
54
  part,
@@ -71,14 +85,14 @@ const baseFor = async (start, store, openapi) => {
71
85
  log,
72
86
  record,
73
87
  ...guard,
74
- checks: { ...(store ? { store: storeCheck(store) } : {}), ...guard.checks },
88
+ checks: { ...hostStoreChecks(store), ...guard.checks },
75
89
  build: buildInfoFromEnv(env),
76
90
  origin: env['AGENTAGE_ORIGIN'] || undefined,
77
91
  ownImage: env['AGENTAGE_IMAGE'],
78
92
  };
79
93
  };
80
94
  const inputFor = async (options, start) => {
81
- const store = storeFor(start);
95
+ const store = await storeFor(start, options.dir);
82
96
  const openapi = await readOpenapi(options.dir);
83
97
  const base = await baseFor(start, store, openapi);
84
98
  return {
@@ -91,6 +105,8 @@ const inputFor = async (options, start) => {
91
105
  importModule: options.importModule,
92
106
  // The old prefix as a second mount, so next stays green; it goes in phase 4.
93
107
  apiAliases: ['/api/v1'],
108
+ // /mcp/{id} (and /connector/{id}) as the app host routes it; bare /mcp for the estate gateway.
109
+ mcpPaths: [MCP_PATH, mcpPathOf(start.pkg.agentage.id)],
94
110
  };
95
111
  };
96
112
  let running;
@@ -1,9 +1,12 @@
1
+ import { type FilesEntry } from '../api/files-registry.js';
1
2
  import { type ApiContext, type RouteEntry } from '../api/routes.js';
2
3
  import { type WellKnownEntry } from '../api/well-known.js';
3
4
  import { type PartContext } from '../context/context.js';
4
5
  import { type ApiHandler } from './part.types.js';
5
- export declare const mountApi: (ctx: PartContext, create: (ctx: ApiContext) => unknown) => Promise<{
6
+ export interface MountedApi {
6
7
  router: ApiHandler;
7
8
  routes: RouteEntry[];
8
9
  documents: WellKnownEntry[];
9
- }>;
10
+ files?: FilesEntry;
11
+ }
12
+ export declare const mountApi: (ctx: PartContext, create: (ctx: ApiContext) => unknown) => Promise<MountedApi>;
@@ -1,11 +1,14 @@
1
1
  import { Router } from 'express';
2
+ import { isDownload } from '../api/download.js';
2
3
  import { inQuery } from '../api/openapi-doc.js';
4
+ import {} from '../api/files-registry.js';
3
5
  import { createRouteRegistry } from '../api/routes.js';
4
6
  import {} from '../api/well-known.js';
5
7
  import {} from '../context/context.js';
6
8
  import { isReply, ok, reply } from '../envelope/envelope.js';
7
9
  import { parse } from '../envelope/parse.js';
8
10
  import {} from './part.types.js';
11
+ import { sendDownload } from './send-download.js';
9
12
  const inputOf = ({ method, spec }, query, body) => {
10
13
  if (!spec.input)
11
14
  return {};
@@ -13,7 +16,31 @@ const inputOf = ({ method, spec }, query, body) => {
13
16
  return parse(spec.input, query, 'Invalid query');
14
17
  return parse(spec.input, body ?? {}, 'Invalid body');
15
18
  };
16
- // Validated in, the handler's data (bare or a reply) parsed by its output schema and sent in the envelope.
19
+ const opaque = (tag) => tag.trim().replace(/^W\//, '');
20
+ // If-None-Match names the tag (weak or strong) or is *: the client's copy is current.
21
+ const notModified = (req, etag) => {
22
+ const given = req.get('if-none-match');
23
+ if (!given || !etag)
24
+ return false;
25
+ const tags = given.split(',').map(opaque);
26
+ return tags.includes('*') || tags.includes(opaque(etag));
27
+ };
28
+ // The envelope by default; a bare route sends the body as it is and answers a current GET 304.
29
+ const sendJson = (req, res, spec, answer) => {
30
+ const { data, meta, etag, status = 200 } = isReply(answer) ? answer : reply(answer);
31
+ if (etag)
32
+ res.setHeader('ETag', etag);
33
+ if (status === 204)
34
+ return void res.status(204).end();
35
+ const body = spec.output ? spec.output.parse(data) : data;
36
+ if (!spec.bare)
37
+ return void res.status(status).json(ok(body, meta));
38
+ if (req.method === 'GET' && notModified(req, etag))
39
+ return void res.status(304).end();
40
+ res.status(status).json(body);
41
+ };
42
+ // Validated in, the handler's data (bare or a reply) parsed by its output schema and sent in the envelope;
43
+ // a file as it is.
17
44
  const handlerOf = (ctx, entry) => async (req, res) => {
18
45
  const input = inputOf(entry, req.query, req.body);
19
46
  const { query: shape } = entry.spec;
@@ -31,13 +58,12 @@ const handlerOf = (ctx, entry) => async (req, res) => {
31
58
  ip: req.ip ?? '',
32
59
  header: (name) => req.get(name),
33
60
  });
34
- const { data, meta, etag, status = 200 } = isReply(answer) ? answer : reply(answer);
35
- if (etag)
36
- res.setHeader('ETag', etag);
37
- if (status === 204)
38
- return void res.status(204).end();
39
- res.status(status);
40
- res.json(ok(entry.spec.output ? entry.spec.output.parse(data) : data, meta));
61
+ const { produces } = entry.spec;
62
+ if (isDownload(answer) !== (produces !== undefined))
63
+ throw new Error(`${entry.path}: download() answers a route that declares produces, and only it`);
64
+ if (isDownload(answer))
65
+ return sendDownload(res, answer, produces);
66
+ sendJson(req, res, entry.spec, answer);
41
67
  };
42
68
  // /items/{id} as Express writes it.
43
69
  const expressPath = (path) => path.replace(/\{(\w+)\}/g, ':$1');
@@ -47,11 +73,11 @@ const routesRouter = (ctx, routes) => {
47
73
  router[entry.method](expressPath(entry.path), handlerOf(ctx, entry));
48
74
  return router;
49
75
  };
50
- // What create(ctx) gave: its ctx.route routes, or the router it returned; exactly one.
51
- const handlerFor = (ctx, routes, returned) => {
76
+ // What create(ctx) gave: its ctx.route routes, or the router it returned; exactly one (or ctx.files alone).
77
+ const handlerFor = (ctx, routes, returned, files) => {
52
78
  if (routes.length > 0 && returned)
53
79
  throw new Error('the api part registers ctx.route routes and returns a router: pick one');
54
- if (routes.length > 0)
80
+ if (routes.length > 0 || (files && !returned))
55
81
  return routesRouter(ctx, routes);
56
82
  if (!returned)
57
83
  throw new Error('the api part registers nothing and returns no router');
@@ -59,7 +85,8 @@ const handlerFor = (ctx, routes, returned) => {
59
85
  };
60
86
  // Runs the api part's create(ctx) with ctx.route; the runtime and the test server mount alike.
61
87
  export const mountApi = async (ctx, create) => {
62
- const { route, routes, wellKnown, documents } = createRouteRegistry();
63
- const returned = await create({ ...ctx, route, wellKnown });
64
- return { router: handlerFor(ctx, routes, returned), routes, documents };
88
+ const { route, routes, wellKnown, documents, files, filesServed } = createRouteRegistry();
89
+ const returned = await create({ ...ctx, route, wellKnown, files });
90
+ const router = handlerFor(ctx, routes, returned, filesServed.files !== undefined);
91
+ return { router, routes, documents, files: filesServed.files };
65
92
  };
@@ -2,6 +2,7 @@ import { type CorsOptions } from 'cors';
2
2
  import { type Express, type RequestHandler } from 'express';
3
3
  import { type HelmetOptions } from 'helmet';
4
4
  import { type WellKnownEntry } from '../api/well-known.js';
5
+ import { type FilesEntry } from '../api/files-registry.js';
5
6
  import { type TokenCheck } from '../auth/token-check.js';
6
7
  import { type BuildInfo, type ServedRecord } from '../discovery/discovery.js';
7
8
  import { type HealthCheck } from '../health/health.js';
@@ -40,9 +41,11 @@ export interface ApiAppOptions extends PartAppBase {
40
41
  path: string;
41
42
  }[];
42
43
  aliases?: string[];
44
+ files?: FilesEntry;
43
45
  }
44
46
  export declare const PUBLIC_CORS: CorsOptions;
45
47
  export declare const BODY_LIMIT = "1mb";
48
+ export declare const resourceDocAt: (app: Express, path: string, resource: Record<string, unknown>) => void;
46
49
  export declare const createPartApp: (options: PartAppOptions) => Express;
47
50
  export declare const mountApiRoutes: (app: Express, options: ApiAppOptions) => void;
48
51
  export declare const createApiApp: (options: ApiAppOptions) => Express;
@@ -3,6 +3,8 @@ import express, {} from 'express';
3
3
  import helmet, {} from 'helmet';
4
4
  import {} from '../api/well-known.js';
5
5
  import { agcidMiddleware } from '../agcid/scope.js';
6
+ import { mountFiles } from '../api/files.js';
7
+ import {} from '../api/files-registry.js';
6
8
  import { routeAccess, sameShape } from '../auth/route-access.js';
7
9
  import { setCaller } from '../auth/token-check.js';
8
10
  import { discoveryDocument, recordOf, } from '../discovery/discovery.js';
@@ -54,6 +56,11 @@ const healthHandler = (options) => createHealthHandler({
54
56
  parts: options.parts,
55
57
  clockRate: options.clockRate,
56
58
  });
59
+ // RFC 9728 path form: the document of the resource at {path}, the one a 401 there names.
60
+ export const resourceDocAt = (app, path, resource) => {
61
+ const doc = { ...resource, resource: `${String(resource['resource'])}${path}` };
62
+ app.get(`/.well-known/oauth-protected-resource${path}`, (_req, res) => void res.json(doc));
63
+ };
57
64
  // The kit app every part image runs: agcid, headers, /health, discovery, the part, the envelope.
58
65
  export const createPartApp = (options) => {
59
66
  const app = express();
@@ -107,7 +114,10 @@ const routeGuard = (options) => {
107
114
  };
108
115
  // The api routes on an app: the part's own (createApiApp) or the host's one app of all parts.
109
116
  export const mountApiRoutes = (app, options) => {
110
- const prefixes = [apiPrefix(options.pkg.agentage.id), ...(options.aliases ?? [])];
117
+ const { id } = options.pkg.agentage;
118
+ if (options.files)
119
+ mountFiles(app, id, options.files, options.tokenCheck);
120
+ const prefixes = [apiPrefix(id), ...(options.aliases ?? [])];
111
121
  app.use(prefixes, cors(PUBLIC_CORS));
112
122
  for (const { name, render } of options.wellKnown ?? [])
113
123
  app.get(`/.well-known/${name}`, wellKnownHandler(render));
@@ -0,0 +1,3 @@
1
+ import { type Response } from 'express';
2
+ import { type DownloadAnswer } from '../api/download.js';
3
+ export declare const sendDownload: (res: Response, answer: DownloadAnswer, produces: string) => Promise<undefined>;
@@ -0,0 +1,29 @@
1
+ import { Readable } from 'node:stream';
2
+ import {} from 'node:stream/web';
3
+ import { pipeline } from 'node:stream/promises';
4
+ import {} from 'express';
5
+ import {} from '../api/download.js';
6
+ const setHeaders = (res, answer, produces) => {
7
+ if (answer.filename)
8
+ res.attachment(answer.filename);
9
+ res.status(200).setHeader('Content-Type', answer.contentType ?? produces);
10
+ };
11
+ async function* from(first, rest) {
12
+ for (let next = first; !next.done; next = await rest.next())
13
+ yield next.value;
14
+ }
15
+ // No header goes out before the first chunk, so a failure up to it is still the error envelope.
16
+ export const sendDownload = async (res, answer, produces) => {
17
+ const { body } = answer;
18
+ if (typeof body === 'string' || body instanceof Uint8Array) {
19
+ setHeaders(res, answer, produces);
20
+ return void res.end(body);
21
+ }
22
+ const source = body instanceof Readable ? body : Readable.fromWeb(body);
23
+ // A client that leaves (or an answer ended) closes the source, also one waiting for its next chunk.
24
+ res.once('close', () => source.destroy());
25
+ const chunks = source[Symbol.asyncIterator]();
26
+ const first = await chunks.next();
27
+ setHeaders(res, answer, produces);
28
+ await pipeline(Readable.from(from(first, chunks)), res);
29
+ };
@@ -0,0 +1,46 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
6
+ <meta name="agentage-shell" content="0.1.0" />
7
+ <title>agentage</title>
8
+ <script>
9
+ try {
10
+ var d = document.documentElement,
11
+ L = localStorage,
12
+ g = function (k, a, b) {
13
+ var n = parseInt(L.getItem(k), 10);
14
+ return n >= a && n <= b ? n : 0;
15
+ };
16
+ var w = g('ag.nav', 232, 420),
17
+ a = g('ag.aside', 280, 640),
18
+ b = g('ag.bot', 100, 420);
19
+ if (w) d.style.setProperty('--nav-full', w + 'px');
20
+ if (a) d.style.setProperty('--aside-w', a + 'px');
21
+ if (b) d.style.setProperty('--bot-h', b + 'px');
22
+ if (L.getItem('ag.navh') === '1') d.classList.add('nh');
23
+ if (L.getItem('ag.bot.open') === '1') d.classList.add('bo');
24
+ } catch (e) {}
25
+ </script>
26
+ <script>
27
+ 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){}
28
+ </script>
29
+ <script type="importmap">
30
+ {
31
+ "imports": {
32
+ "react": "/shell/vendor/react.js",
33
+ "react/jsx-runtime": "/shell/vendor/jsx-runtime.js",
34
+ "react-dom": "/shell/vendor/react-dom.js",
35
+ "react-dom/client": "/shell/vendor/react-dom-client.js",
36
+ "@agentage/extension/app": "/shell/vendor/app.js"
37
+ }
38
+ }
39
+ </script>
40
+ <link rel="stylesheet" href="/shell/shell.css" />
41
+ <script type="module" src="/shell/shell.js"></script>
42
+ </head>
43
+ <body>
44
+ <div id="root"></div>
45
+ </body>
46
+ </html>