capable-kit 0.0.1-alpha.8 → 0.1.0-alpha.11

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 (93) hide show
  1. package/CHANGELOG.md +385 -0
  2. package/LICENSE +21 -0
  3. package/README.md +12 -0
  4. package/dist/ai-sdk.d.mts +3 -3
  5. package/dist/ai-sdk.mjs +9 -7
  6. package/dist/ai-sdk.mjs.map +1 -1
  7. package/dist/app.d.mts +2 -2
  8. package/dist/app.mjs +2 -2
  9. package/dist/bin.mjs +19 -15
  10. package/dist/bin.mjs.map +1 -1
  11. package/dist/cli.d.mts +9 -1
  12. package/dist/cli.mjs +1 -1
  13. package/dist/core.d.mts +3 -3
  14. package/dist/core.mjs +2 -2
  15. package/dist/eve.d.mts +92 -9
  16. package/dist/eve.mjs +606 -26
  17. package/dist/eve.mjs.map +1 -1
  18. package/dist/http.d.mts +1 -1
  19. package/dist/http.mjs +1 -1
  20. package/dist/{index-_qKFfWV4.d.mts → index-BIO_hbXJ.d.mts} +69 -26
  21. package/dist/{index-hdH_K5Zc.d.mts → index-C0tU5Y2n.d.mts} +4 -4
  22. package/dist/{index-Dl4NK9G0.d.mts → index-CwvjDizW.d.mts} +5 -3
  23. package/dist/{index-F4ba_olD.d.mts → index-F_eaksy8.d.mts} +58 -17
  24. package/dist/index.d.mts +4 -4
  25. package/dist/index.mjs +3 -3
  26. package/dist/mcp.d.mts +19 -4
  27. package/dist/mcp.mjs +2 -2
  28. package/dist/{mount-CEFAplR5.mjs → mount-pvIaehZC.mjs} +159 -107
  29. package/dist/mount-pvIaehZC.mjs.map +1 -0
  30. package/dist/react-query.d.mts +2 -2
  31. package/dist/react-query.mjs +1 -1
  32. package/dist/react-query.mjs.map +1 -1
  33. package/dist/runtime-support.d.mts +1 -1
  34. package/dist/runtime-support.mjs +3 -3
  35. package/dist/server.d.mts +1 -1
  36. package/dist/server.mjs +1 -1
  37. package/dist/{src-rkr5j_NH.mjs → src-Bk3lEhI7.mjs} +63 -25
  38. package/dist/src-Bk3lEhI7.mjs.map +1 -0
  39. package/dist/src-C2OEkZ3c.mjs +760 -0
  40. package/dist/src-C2OEkZ3c.mjs.map +1 -0
  41. package/dist/{src-BWxDO2Ua.mjs → src-DFrxQ_S6.mjs} +9 -7
  42. package/dist/src-DFrxQ_S6.mjs.map +1 -0
  43. package/dist/{src-D_0PIhqq.mjs → src-DklM1g7V.mjs} +69 -40
  44. package/dist/src-DklM1g7V.mjs.map +1 -0
  45. package/dist/{src-D-cm2gQ6.mjs → src-TCQGaWar.mjs} +119 -45
  46. package/dist/src-TCQGaWar.mjs.map +1 -0
  47. package/dist/{subscription-B-auXJbm.d.mts → subscription-fVgS4T8P.d.mts} +2 -2
  48. package/dist/swr.d.mts +2 -2
  49. package/dist/swr.mjs +1 -1
  50. package/dist/swr.mjs.map +1 -1
  51. package/docs/CONTEXT.md +44 -22
  52. package/docs/README.md +3 -0
  53. package/docs/internal/README.md +3 -0
  54. package/docs/internal/adr/0001-capability-is-the-semantic-boundary.md +1 -1
  55. package/docs/internal/adr/0003-capability-reference-customization.md +68 -0
  56. package/docs/internal/architecture.md +31 -17
  57. package/docs/internal/capability-first-model.md +126 -17
  58. package/docs/internal/eve-recovery-validation.md +87 -0
  59. package/docs/internal/feedback/v-ray/README.md +258 -0
  60. package/docs/internal/feedback/v-ray/inference.mjs +43 -0
  61. package/docs/internal/feedback/v-ray/reproduce.mjs +36 -0
  62. package/docs/internal/implementation-friction.md +445 -1
  63. package/docs/internal/releases.md +79 -0
  64. package/docs/site/capable-orpc-and-trpc.mdx +2 -2
  65. package/docs/site/concepts/apps.mdx +7 -1
  66. package/docs/site/concepts/architecture.mdx +9 -1
  67. package/docs/site/concepts/capabilities.mdx +41 -4
  68. package/docs/site/concepts/errors.mdx +26 -4
  69. package/docs/site/concepts/presentations.mdx +20 -0
  70. package/docs/site/hosting/standalone-server.mdx +2 -0
  71. package/docs/site/patterns/composition.mdx +152 -8
  72. package/docs/site/patterns/remote-apps.mdx +29 -3
  73. package/docs/site/patterns/subscriptions.mdx +79 -32
  74. package/docs/site/quickstart.mdx +3 -2
  75. package/docs/site/reference/packages-and-entry-points.mdx +52 -4
  76. package/docs/site/reference/the-cap-cli.mdx +2 -2
  77. package/docs/site/surfaces/cli.mdx +44 -0
  78. package/docs/site/surfaces/eve.mdx +67 -18
  79. package/docs/site/surfaces/mcp.mdx +84 -2
  80. package/docs/site/surfaces/typescript.mdx +3 -3
  81. package/package-docs.mjs +3 -0
  82. package/package.json +17 -12
  83. package/src/bin.ts +0 -0
  84. package/src/index.test.ts +2 -1
  85. package/src/index.ts +8 -1
  86. package/src/package.test.ts +15 -0
  87. package/dist/mount-CEFAplR5.mjs.map +0 -1
  88. package/dist/src-BWxDO2Ua.mjs.map +0 -1
  89. package/dist/src-D-cm2gQ6.mjs.map +0 -1
  90. package/dist/src-D_0PIhqq.mjs.map +0 -1
  91. package/dist/src-betOfnDL.mjs +0 -481
  92. package/dist/src-betOfnDL.mjs.map +0 -1
  93. package/dist/src-rkr5j_NH.mjs.map +0 -1
@@ -11,6 +11,14 @@ export const metadata = docMetadata("/reference/packages", frontmatter);
11
11
 
12
12
  Entry points are explicit so that a server mount, a UI projection, or an agent integration never gets pulled into an application that does not use it.
13
13
 
14
+ ## Changes and upgrades [#changes]
15
+
16
+ Read the [versioned changelog](https://github.com/vercel-labs/capable/blob/main/packages/capable/CHANGELOG.md)
17
+ for features, fixes, and breaking changes. It also ships at
18
+ `node_modules/capable-kit/CHANGELOG.md`. When upgrading, read the target version’s
19
+ changelog and apply entries after your installed version through your target
20
+ version, oldest first. Repository main may be ahead of your installed version.
21
+
14
22
  ## The root entry point [#root]
15
23
 
16
24
  `capable-kit` is deliberately limited to authoring and composing apps. Everything you need to define capabilities lives here.
@@ -26,7 +34,8 @@ import {
26
34
  watchQuery, // snapshot + invalidation subscriber
27
35
  createApp, // definition + context -> callable app
28
36
  createRemoteApp, // transport + definition type -> callable app
29
- mergeApps, // combine apps
37
+ composeApps, // place apps, subtrees, and individual references
38
+ customize, // customize a reference for presentation
30
39
  selectApp, // narrow an app
31
40
  subscribe, // iterate replacements
32
41
  executeCapability, // run one capability without an app
@@ -41,7 +50,7 @@ import {
41
50
  | `capable-kit/server` | `createServer()` plus the `protocol()` and `http()` mounts |
42
51
  | `capable-kit/http` | Capable transport and HTTP projection: `createHttpTransport()`, `createHttpHandler()`, `defineProtocolCodec()` |
43
52
  | `capable-kit/cli` | `createCli()` |
44
- | `capable-kit/mcp` | `createMcp()` and the `mcp()` server mount |
53
+ | `capable-kit/mcp` | `createMcp()`, `registerCapableTools()`, and the `mcp()` server mount |
45
54
  | `capable-kit/eve` | `createEveTools()` |
46
55
  | `capable-kit/ai-sdk` | `createAiSdkTools()` |
47
56
  | `capable-kit/app` | App runtime internals: manifests, transport types, selection |
@@ -60,14 +69,53 @@ import {
60
69
  | --- | --- | --- |
61
70
  | `capability()` | `capability(config)` | `capability<Context>()` or `capability.withContext<Context>()` binds a context type |
62
71
  | `present` | `present.table(), .image(), .file()` | Portable presentation parts for `toPresentation` |
63
- | `defineApp()` | `defineApp({ name, version, capabilities })` | Immutable definition, no context |
72
+ | `defineApp()` | `defineApp({ name, version, capabilities, middleware, errors })` | Immutable definition, no context |
64
73
  | `group()` | `group({ middleware, errors, meta, capabilities })` | Anonymous decorated subtree |
65
74
  | `createApp()` | `createApp(definition)` | Callable tree; context options exist only when declared |
66
75
  | `createRemoteApp()` | `createRemoteApp<AppDefinition>(transport)` | Lazy, transport-backed remote placement |
67
- | `mergeApps()` | `mergeApps(a, b, ...)` | Root-tree merge, dispatch by id |
76
+ | `composeApps()` | `composeApps(a, { tools: b.plugins })` | Place whole Apps, executable subtrees, or individual references; dispatch by ID |
77
+ | `customize()` | `customize(app.status, { description, meta: { cli: { positional: ["id"] } } })` | Immutable title, description, and CLI/MCP overrides for a composition entry |
68
78
  | `selectApp()` | `selectApp(app, { include, exclude })` | Exclude wins over include |
69
79
  | `subscribe()` | `subscribe(app.todos.list, input, { signal })` | Async iterator of replacements |
70
80
  | `executeCapability()` | `executeCapability(capability, { input, context, signal })` | No app tree, no group behaviour |
81
+ | `registerCapableTools()` | `registerCapableTools(server, await createMcp(app))` | Register generated tools on an SDK `McpServer`; returns native tool handles. See [native hosting](/surfaces/mcp#native-hosting) |
71
82
  | `createServer()` | `createServer(definition, { context, mounts, middleware })` | Returns `{ fetch }` |
72
83
 
84
+ ## Custom surface display [#custom-display]
85
+
86
+ Custom surfaces can read placement settings without replacing the source
87
+ contract used for execution or policy:
88
+
89
+ ```ts
90
+ import {
91
+ flattenManifestCapabilities, getAppRuntime, getCapabilityDisplay,
92
+ } from "capable-kit/app";
93
+
94
+ const manifest = await getAppRuntime(app).manifest();
95
+ const help = flattenManifestCapabilities(manifest.capabilities).map(capability => ({
96
+ id: capability.id,
97
+ path: capability.path,
98
+ ...getCapabilityDisplay(capability),
99
+ }));
100
+ ```
101
+
102
+ `getCapabilityDisplay()` returns the effective title, description, and metadata.
103
+ To opt a custom surface into `customize()` metadata, augment the global
104
+ `CapableCustomizationMeta` interface in the surface's types and explicitly read
105
+ that namespace when compiling its display. This registry is separate from the
106
+ open metadata on authored capabilities.
107
+
108
+ ```ts
109
+ // In a custom surface module:
110
+ declare global {
111
+ interface CapableCustomizationMeta {
112
+ readonly inspector?: { readonly label?: string };
113
+ }
114
+ }
115
+
116
+ const reference = customize(app.status, {
117
+ meta: { inspector: { label: "Instance status" } },
118
+ });
119
+ ```
120
+
73
121
  </DocsPage>
@@ -30,9 +30,9 @@ pnpm dev
30
30
 
31
31
  | Command | Description |
32
32
  | --- | --- |
33
- | `init` | Creates capable.app.ts and a runnable package.json in the current directory or a supplied directory. Existing fields and Capable App entries are never overwritten. |
33
+ | `init` | Creates capable.app.ts and a runnable package.json, including `rolldown` for `cap build`, in the current directory or a supplied directory. Existing fields and Capable App entries are never overwritten. |
34
34
  | `dev` | Starts a watching development server. Without a capable.server.ts it serves /~capable, /api, /openapi.json, and /mcp, plus a read-only capability index at /. With one, it wraps the authored server and adds only the index. |
35
- | `build` | Builds the project into `.output`. Presets are Nitro deployment presets, for example `node-server` or `vercel`. |
35
+ | `build` | Builds the project into `.output`. Requires `rolldown` in the project's dependencies. Presets are Nitro deployment presets, for example `node-server` or `vercel`. |
36
36
  | `preview` | Runs a previously built `node-server` output. Other presets do not produce a locally runnable command. |
37
37
  | `cli` | Runs the app's derived command tree without writing a CLI entry point. |
38
38
 
@@ -52,6 +52,39 @@ todo --help
52
52
 
53
53
  `run()` resolves to an exit code: `0` on success, `1` for a failed capability, and `2` for a usage error.
54
54
 
55
+ For a single-operation CLI, map the Capability to an empty command path:
56
+
57
+ ```ts
58
+ capability({
59
+ id: "analysis.url",
60
+ input: z.object({ url: z.string() }),
61
+ meta: { cli: { command: [], positional: ["url"] } },
62
+ handler: ({ input }) => analyzeURL(input.url),
63
+ });
64
+ // pnpm cli vercel.com
65
+ ```
66
+
67
+ Bare invocation and `--help` keep the app name and command listing, with the root
68
+ Capability's arguments and options underneath. `--json`
69
+ or `--watch` selects execution even without positional arguments, applying schema
70
+ defaults or reporting missing required input. Only one Capability may map to the
71
+ root; longer subcommands still take precedence.
72
+
73
+ Pass markdansi's `RenderOptions` directly through `markdown` to customize terminal
74
+ presentations:
75
+
76
+ ```ts
77
+ createCli(app, {
78
+ invocationName: "pnpm cli",
79
+ markdown: { codeBox: false, tableBorder: "none", tableDense: true },
80
+ });
81
+ ```
82
+
83
+ These options are forwarded unchanged for ordinary and watched presentations in
84
+ a TTY. `markdown.color` and `markdown.width`, when supplied, override the CLI's
85
+ color and columns defaults for presentation rendering. Redirected output remains
86
+ Markdown, and `--json` returns canonical output.
87
+
55
88
  ## How commands are derived [#mapping]
56
89
 
57
90
  | Authored | Becomes |
@@ -135,4 +168,15 @@ cap cli --app ./ todos list
135
168
  cap cli --app https://todos.example.com todos list
136
169
  ```
137
170
 
171
+ ## Stream events and live state [#subscriptions]
172
+
173
+ A capability with only `subscribe` streams individual events by default. Readable output appends each event's presentation, with canonical output as the fallback. `--json` emits one canonical event per line without generating presentations.
174
+
175
+ ```sh title="terminal"
176
+ radar runs logs --run-id run_123
177
+ radar runs logs --run-id run_123 --json
178
+ ```
179
+
180
+ Capabilities with both `handler` and `subscribe` keep their unary command and use `--watch` for replacement snapshots. See [Subscriptions](/patterns/subscriptions).
181
+
138
182
  </DocsPage>
@@ -13,18 +13,12 @@ export const metadata = docMetadata("/surfaces/eve", frontmatter);
13
13
 
14
14
  ## Start in-process [#local]
15
15
 
16
- Put an executable app directly in Eve's `agent/tools/` directory. There is no second server and no HTTP hop.
16
+ Import an executable app into Eve's `agent/tools/` module. There is no second server and no HTTP hop.
17
17
 
18
18
  ```ts title="agent/tools/todos.ts"
19
- import { createApp } from "capable-kit";
20
19
  import { createEveTools } from "capable-kit/eve";
21
20
  import { always } from "eve/tools/approval";
22
- import definition from "../../capable.app";
23
- import { todos } from "../../todos";
24
-
25
- const app = createApp(definition, {
26
- context: () => ({ todos }),
27
- });
21
+ import { app } from "../../capable.app";
28
22
 
29
23
  export default createEveTools(app, {
30
24
  approval: (capability) =>
@@ -63,18 +57,20 @@ The standalone server exposes the Capable transport at `/~capable/`. Its manifes
63
57
 
64
58
  Replace `createApp()` with `createRemoteApp()`. The tool projection and approval policy stay the same; only the placement of execution changes.
65
59
 
66
- ```ts title="agent/tools/todos.ts"
60
+ ```ts title="remote.app.ts"
67
61
  import { createRemoteApp } from "capable-kit";
68
- import { createEveTools } from "capable-kit/eve";
69
62
  import { createHttpTransport } from "capable-kit/http";
70
- import { always } from "eve/tools/approval";
71
- import type { AppDefinition } from "../../capable.app";
63
+ import type { AppDefinition } from "./capable.app";
72
64
 
73
- const app = createRemoteApp<AppDefinition>(
74
- createHttpTransport({
75
- url: "https://todos.example.com/~capable/",
76
- }),
77
- );
65
+ export const app = createRemoteApp<AppDefinition>(createHttpTransport({
66
+ url: "https://todos.example.com/~capable/",
67
+ }));
68
+ ```
69
+
70
+ ```ts title="agent/tools/todos.ts"
71
+ import { createEveTools } from "capable-kit/eve";
72
+ import { always } from "eve/tools/approval";
73
+ import { app } from "../../remote.app";
78
74
 
79
75
  export default createEveTools(app, {
80
76
  approval: (capability) =>
@@ -112,10 +108,63 @@ meta: {
112
108
 
113
109
  ## Durability [#durability]
114
110
 
115
- The tool definition resolves at Eve's `step.started` boundary. With a local app, Eve keeps the app and its context provider in memory. With a remote app, it keeps the transport-backed runtime live instead. In both cases Eve checkpoints the tool call and its result.
111
+ `createEveTools()` returns an Eve `defineDynamic()` resolver. Eve evaluates it before every model call, in any process, so a cold start needs no reconstruction step. Capable reads the App manifest once per session through `ctx.memo()`, and each tool call rebuilds provider Apps from the current execution session. Define your App or provider in deployed code and keep its data in persistent storage.
116
112
 
117
113
  > **Interrupted steps can re-run**
118
114
  >
119
115
  > As with any Eve tool, a side effect must be idempotent: an interrupted step may execute again. This is a property of durable agent execution, not of Capable.
120
116
 
117
+ ## Wrap an Eve agent as an app [#agent-app]
118
+
119
+ `createEveAgentAdapter()` wraps remote execution with `send`, `result`,
120
+ and `cancel` capabilities. Its `name` mounts the lifecycle under a namespace, so
121
+ multiple agents compose alongside direct capabilities.
122
+
123
+ ```ts
124
+ import { composeApps } from "capable-kit";
125
+ import { createEveAgentAdapter } from "capable-kit/eve";
126
+ import { createMcp } from "capable-kit/mcp";
127
+
128
+ // Clients and authorization are bound by the host to one authenticated caller.
129
+ const content = createEveAgentAdapter({
130
+ name: "content", client: contentClient, authorize,
131
+ });
132
+ const research = createEveAgentAdapter({
133
+ name: "research", client: researchClient, authorize,
134
+ });
135
+ const app = composeApps(content.app, research.app, notionApp);
136
+ const tools = await createMcp(app);
137
+ // content__send, content__result, content__cancel, ...
138
+
139
+ const { runId } = await app.content.send({ message: "Draft an outline" });
140
+ const result = await app.content.send({
141
+ runId, message: "Make it shorter", wait: true, timeoutMs: 60_000,
142
+ });
143
+ ```
144
+
145
+ The CLI uses a positional message:
146
+
147
+ ```sh
148
+ recipes chef send "What can I cook?" --wait
149
+ recipes chef send "Vegetarian please" --run-id '<runId>' --wait
150
+ ```
151
+
152
+ Without `wait`, `send` returns the accepted ID and `running` immediately. Waiting
153
+ follows the session stream until the message's turn completes, pauses for input,
154
+ fails, or is cancelled. Answering a question waits for the resumed turn.
155
+ The default deadline is 30 seconds (`timeoutMs`, at most five minutes); on timeout,
156
+ it returns the accepted ID with `running`. A single pending question is answered
157
+ automatically; multiple questions require `requestId`. Selection-only questions
158
+ require `optionId` instead of submitting the message as freeform text.
159
+
160
+ Run IDs are durable Eve session IDs, so subsequent CLI processes can attach
161
+ without a local mapping. The host authorizes every operation against the caller
162
+ and session. Only typed questions are answerable; approvals remain host-owned.
163
+
164
+ The adapter targets Eve 1.x (stream version 27). Each result or continuation folds
165
+ Eve's finite durable history into a session view, with configurable event and time
166
+ limits. `cursor` is the next stream line to read. An
167
+ incomplete read fails rather than returning partial state. Call `dispose()` to
168
+ abort local requests; Eve execution continues until explicitly cancelled.
169
+
121
170
  </DocsPage>
@@ -53,6 +53,7 @@ export default createServer(definition, {
53
53
  | `icons` | None | Server icons shown by supporting clients |
54
54
  | `instructions` | None | Guidance every MCP client receives during connection setup |
55
55
  | `selection` | Everything | Capability tree exposed as tools; exclude wins over include |
56
+ | `toolName` | `capability.path.join("__")` | App-level formatter for derived tool names; explicit `meta.mcp.name` or `customize()` overrides still win |
56
57
  | `cache.discovery` | `0 ms`, private | Modern-client cache hint for server discovery |
57
58
  | `cache.tools` | `0 ms`, private | Modern-client cache hint for the tool list |
58
59
 
@@ -96,8 +97,23 @@ const getTodo = todo({
96
97
  ```
97
98
 
98
99
  The tool name is a portable wire name derived from the Application path; it is
99
- not the Capability's canonical identity. Every derived tool also exposes that
100
- identity as `_meta["dev.capable/capabilityId"]`:
100
+ not the Capability's canonical identity. To change the naming convention for an
101
+ entire surface without repeating `meta.mcp.name` on every capability, pass
102
+ `toolName` to `mcp()` or `createMcp()`:
103
+
104
+ ```ts title="naming.ts"
105
+ import { createMcp, mcp } from "capable-kit/mcp";
106
+
107
+ mcp({ toolName: (capability) => capability.path.join("_") });
108
+
109
+ const tools = await createMcp(app, {
110
+ toolName: (capability) => capability.id.replaceAll(".", "_"),
111
+ });
112
+ ```
113
+
114
+ Explicit `meta.mcp.name` and `customize()` overrides still take precedence over
115
+ `toolName`, and duplicate names fail discovery. Every derived tool also exposes
116
+ its canonical identity as `_meta["dev.capable/capabilityId"]`:
101
117
 
102
118
  ```json
103
119
  {
@@ -157,6 +173,72 @@ const agentApp = selectApp(app, { exclude: { admin: true } });
157
173
  const tools = await createMcp(agentApp);
158
174
  ```
159
175
 
176
+ ## Host with the native SDK [#native-hosting]
177
+
178
+ Use `registerCapableTools()` to add generated tools to an SDK `McpServer` alongside
179
+ handwritten tools and resources. The host owns server lifecycle, transport, and
180
+ request context. Install `@modelcontextprotocol/server` in your host application.
181
+
182
+ This complete Fetch handler exposes a contextless App and a native tool/resource
183
+ on the same endpoint:
184
+
185
+ ```ts title="mcp.ts"
186
+ import { McpServer, createMcpHandler } from "@modelcontextprotocol/server";
187
+ import { capability, createApp, defineApp } from "capable-kit";
188
+ import { createMcp, registerCapableTools } from "capable-kit/mcp";
189
+ import { z } from "zod";
190
+
191
+ const app = createApp(defineApp({
192
+ capabilities: {
193
+ greet: capability({
194
+ id: "greet",
195
+ input: z.object({ name: z.string().default("world") }),
196
+ output: z.string(),
197
+ handler: ({ input }) => `Hello, ${input.name}!`,
198
+ }),
199
+ },
200
+ }));
201
+ const tools = await createMcp(app);
202
+
203
+ const handler = createMcpHandler(() => {
204
+ const server = new McpServer({ name: "greetings", version: "1.0.0" });
205
+ registerCapableTools(server, tools);
206
+
207
+ server.registerTool("health", {}, () => ({
208
+ content: [{ type: "text", text: "OK" }],
209
+ }));
210
+ server.registerResource("guide", "docs://guide", {}, uri => ({
211
+ contents: [{ uri: uri.href, text: "Call greet to say hello." }],
212
+ }));
213
+ return server;
214
+ }, { legacy: "stateless" });
215
+
216
+ // Route /mcp to this Fetch handler in your host.
217
+ export const fetch = (request: Request) => handler.fetch(request);
218
+ ```
219
+
220
+ For a contextual App, create the App inside the handler factory using its
221
+ `requestInfo`, bind the host's authenticated context, then call
222
+ `registerCapableTools(server, await createMcp(app))`. Selection remains available
223
+ through `selectApp()` before discovery.
224
+
225
+ The helper preserves schemas, metadata, annotations, icons, presentation, and
226
+ Capable transport errors. Parsing stays with the source App executor, so defaults
227
+ and transforms run once and invalid arguments retain `BAD_REQUEST`. Cancellation
228
+ forwards the current SDK request signal to the App. The SDK owns modern and
229
+ legacy output projection.
230
+
231
+ The return value is an array of SDK `RegisteredTool` handles in descriptor order;
232
+ use their native `disable()`, `enable()`, or `remove()` methods. The SDK rejects
233
+ name collisions with generated or handwritten tools. Registration is sequential;
234
+ a collision can leave earlier tools registered.
235
+
236
+ Native SDK rules also apply: unknown names produce protocol errors, and a tool
237
+ with an output schema must return defined `structuredContent`. A Capability with
238
+ `output: z.undefined()` cannot meet that native output-presence rule; the helper
239
+ returns the SDK's tool error rather than fabricating output. The existing `mcp()`
240
+ mount retains its own unknown-tool and undefined-output behavior.
241
+
160
242
  ## Tools without a server [#tools]
161
243
 
162
244
  `createMcp()` returns plain tool descriptors you can host yourself — over stdio, inside a test, or in another MCP server.
@@ -86,7 +86,7 @@ const todos = await app.todos.list({}, { signal: controller.signal });
86
86
 
87
87
  ## Streaming reads [#subscribe]
88
88
 
89
- When a capability defines [subscribe](/patterns/subscriptions), pass its call to `subscribe()` to get an async iterator instead of a single result. Calling it normally still returns one value.
89
+ When a capability defines [subscribe](/patterns/subscriptions), pass its reference to `subscribe()` to get an async iterator. A capability with a handler remains callable; a subscription-only event capability has no unary call signature.
90
90
 
91
91
  ```ts title="watch.ts"
92
92
  import { subscribe } from "capable-kit";
@@ -96,11 +96,11 @@ for await (const todos of subscribe(app.todos.list, { status: "open" })) {
96
96
  }
97
97
  ```
98
98
 
99
- > `subscribe()` takes the capability function itself, not its result, which is why it stays fully typed: `subscribe(app.todos.list, input)`.
99
+ > `subscribe()` takes the capability reference, not an invocation result, which is why it stays fully typed: `subscribe(app.todos.list, input)`.
100
100
 
101
101
  ## One capability without an app [#without-app]
102
102
 
103
- Tests and scripts sometimes want a single capability with no tree around it. `executeCapability()` runs it directly. Group middleware, group errors, and group metadata do not apply, because there is no group.
103
+ Tests and scripts sometimes want a single capability with no tree around it. `executeCapability()` runs it directly. App and group middleware and errors do not apply, because the call has no app or group. Group metadata also does not apply.
104
104
 
105
105
  ```ts title="list-todos.test.ts"
106
106
  import { executeCapability } from "capable-kit";
package/package-docs.mjs CHANGED
@@ -103,6 +103,9 @@ the npm package is packed. It matches the installed package version.
103
103
  Do not rely on remembered Capable APIs. Read the relevant bundled guide and
104
104
  inspect \`../src/\` when you need a detail the guides do not cover.
105
105
 
106
+ Before upgrading, read [the versioned changelog](../CHANGELOG.md). Apply all
107
+ entries after the installed version through the target version, oldest first.
108
+
106
109
  Start here:
107
110
 
108
111
  1. [Introduction](./site/introduction.mdx)
package/package.json CHANGED
@@ -1,6 +1,12 @@
1
1
  {
2
2
  "name": "capable-kit",
3
- "version": "0.0.1-alpha.8",
3
+ "version": "0.1.0-alpha.11",
4
+ "license": "MIT",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/vercel-labs/capable.git",
8
+ "directory": "packages/capable"
9
+ },
4
10
  "type": "module",
5
11
  "bin": {
6
12
  "cap": "dist/bin.mjs",
@@ -65,17 +71,15 @@
65
71
  "prepare-package.mjs",
66
72
  "src",
67
73
  "verify-package-exports.mjs",
68
- "README.md"
74
+ "README.md",
75
+ "CHANGELOG.md",
76
+ "LICENSE"
69
77
  ],
70
78
  "directories": {
71
79
  "doc": "./docs"
72
80
  },
73
- "scripts": {
74
- "prepack": "node prepare-package.mjs",
75
- "postpack": "node package-docs.mjs --clean"
76
- },
77
81
  "engines": {
78
- "node": ">=20"
82
+ "node": ">=22.22"
79
83
  },
80
84
  "publishConfig": {
81
85
  "access": "public",
@@ -85,13 +89,13 @@
85
89
  "@standard-schema/spec": "^1.1.0",
86
90
  "@modelcontextprotocol/server": "^2.0.0",
87
91
  "markdansi": "0.3.2",
88
- "nitro": "3.0.260610-beta",
92
+ "nitro": "3.0.261103-rc",
89
93
  "superjson": "2.2.6"
90
94
  },
91
95
  "peerDependencies": {
92
96
  "@tanstack/react-query": ">=5.80.2 <6",
93
- "ai": "^7.0.0",
94
- "eve": ">=0.27.1",
97
+ "ai": "^7.0.82",
98
+ "eve": "^1.0.0",
95
99
  "swr": ">=2.3.0 <3"
96
100
  },
97
101
  "peerDependenciesMeta": {
@@ -107,5 +111,6 @@
107
111
  "swr": {
108
112
  "optional": true
109
113
  }
110
- }
111
- }
114
+ },
115
+ "scripts": {}
116
+ }
package/src/bin.ts CHANGED
File without changes
package/src/index.test.ts CHANGED
@@ -29,14 +29,15 @@ describe("capable public entry points", () => {
29
29
  test("keeps the root focused on authoring and App composition", () => {
30
30
  expect(Object.keys(capable).sort()).toEqual([
31
31
  "capability",
32
+ "composeApps",
32
33
  "createApp",
33
34
  "createRemoteApp",
35
+ "customize",
34
36
  "defineApp",
35
37
  "defineErrors",
36
38
  "executeCapability",
37
39
  "group",
38
40
  "md",
39
- "mergeApps",
40
41
  "present",
41
42
  "selectApp",
42
43
  "subscribe",
package/src/index.ts CHANGED
@@ -18,6 +18,7 @@ export {
18
18
  type CapabilityDefinition,
19
19
  type CapabilityContext,
20
20
  type CapabilityEffect,
21
+ type CapabilityExecution,
21
22
  type CapabilityFactory,
22
23
  type CapabilityHandlerArgs,
23
24
  type CapabilityInput,
@@ -32,11 +33,17 @@ export {
32
33
  export {
33
34
  createApp,
34
35
  createRemoteApp,
35
- mergeApps,
36
+ composeApps,
37
+ customize,
38
+ type ApplicationManifest,
39
+ type CapabilityCustomization,
40
+ type CreateRemoteAppOptions,
41
+ type CustomizedCapability,
36
42
  selectApp,
37
43
  subscribe,
38
44
  type ApplicationSelection,
39
45
  type App,
40
46
  type AppContextProvider,
41
47
  type AppCapabilityCall,
48
+ type AppCapabilityReference,
42
49
  } from "@capable/app";
@@ -35,6 +35,15 @@ describe("published package", () => {
35
35
  encoding: "utf8",
36
36
  },
37
37
  );
38
+ // Compile against built declarations without monorepo path aliases. This
39
+ // catches metadata augmentations lost while bundling private packages.
40
+ for (const fixture of ["customization", "customization-no-surface"]) {
41
+ execFileSync(process.platform === "win32" ? "pnpm.cmd" : "pnpm", [
42
+ "exec", "tsc", "--ignoreConfig", "--noEmit", "--strict", "--skipLibCheck",
43
+ "--target", "es2022", "--module", "nodenext",
44
+ join(packageDirectory, `fixtures/${fixture}.mts`),
45
+ ], { cwd: packageDirectory, encoding: "utf8" });
46
+ }
38
47
  const result = findPackResult(JSON.parse(output));
39
48
  const paths = new Set(result.files.map((file) => file.path));
40
49
  const archive = join(destination, result.filename);
@@ -46,15 +55,18 @@ describe("published package", () => {
46
55
  ),
47
56
  ) as {
48
57
  readonly bin?: Readonly<Record<string, string>>;
58
+ readonly dependencies?: Readonly<Record<string, string>>;
49
59
  readonly directories?: { readonly doc?: string };
50
60
  readonly exports?: Readonly<Record<
51
61
  string,
52
62
  string | Readonly<Record<string, string>>
53
63
  >>;
64
+ readonly license?: string;
54
65
  readonly peerDependenciesMeta?: Readonly<Record<
55
66
  string,
56
67
  { readonly optional?: boolean }
57
68
  >>;
69
+ readonly repository?: unknown;
58
70
  readonly scripts?: Record<string, string>;
59
71
  };
60
72
  const quickstart = execFileSync(
@@ -102,6 +114,9 @@ describe("published package", () => {
102
114
  expect(paths).toContain("package-docs.mjs");
103
115
  expect(paths).toContain("prepare-package.mjs");
104
116
  expect(paths).toContain("verify-package-exports.mjs");
117
+ expect(paths).toContain("LICENSE");
118
+ expect(manifest.license).toBe("MIT");
119
+ expect(manifest.dependencies).not.toHaveProperty("zod");
105
120
  expect(manifest.directories?.doc).toBe("./docs");
106
121
  expect(manifest.scripts).toMatchObject({
107
122
  prepack: "node prepare-package.mjs",
@@ -1 +0,0 @@
1
- {"version":3,"file":"mount-CEFAplR5.mjs","names":[],"sources":["../../mcp/src/index.ts","../../mcp/src/presentation.ts","../../mcp/src/mount.ts"],"sourcesContent":["import type { CapabilityMetaRegistry } from \"@capable/core\";\nimport {\n getAppRuntime,\n type AnyApp,\n type JsonSchema,\n type ManifestNode,\n type ManifestCapability,\n type CapabilityResult,\n} from \"@capable/app\";\n\nexport type McpCapabilityMeta =\n | false\n | {\n readonly name?: string;\n readonly icons?: readonly McpIcon[];\n readonly idempotentHint?: boolean;\n readonly openWorldHint?: boolean;\n };\n\nexport type McpIcon = {\n readonly src: string;\n readonly mimeType?: string;\n readonly sizes?: readonly string[];\n readonly theme?: \"light\" | \"dark\";\n};\n\ndeclare module \"@capable/core\" {\n interface CapabilityMetaRegistry {\n readonly mcp?: McpCapabilityMeta;\n }\n}\n\nexport type McpTool = {\n readonly name: string;\n readonly title?: string;\n readonly description?: string;\n readonly icons?: readonly McpIcon[];\n readonly inputSchema: JsonSchema;\n readonly outputSchema?: JsonSchema;\n readonly _meta: {\n readonly \"dev.capable/capabilityId\": string;\n };\n readonly annotations: {\n readonly readOnlyHint: boolean;\n readonly destructiveHint: boolean;\n readonly idempotentHint?: boolean;\n readonly openWorldHint?: boolean;\n };\n call(\n input: unknown,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapabilityResult>;\n};\n\nexport async function createMcp(\n app: AnyApp,\n): Promise<readonly McpTool[]> {\n const runtime = getAppRuntime(app);\n const manifest = await runtime.manifest();\n const tools = flatten(manifest.capabilities)\n .filter((capability) => capability.meta.mcp !== false)\n .map((capability) => {\n const meta = readMcpMeta(capability);\n return Object.freeze({\n name: meta?.name ?? capability.path.join(\"__\"),\n ...(capability.title ? { title: capability.title } : {}),\n ...(capability.description ? { description: capability.description } : {}),\n ...(meta?.icons ? { icons: meta.icons } : {}),\n inputSchema: capability.input ?? {\n type: \"object\",\n properties: {},\n additionalProperties: false,\n },\n ...(capability.output\n ? { outputSchema: capability.output }\n : {}),\n _meta: {\n \"dev.capable/capabilityId\": capability.id,\n },\n annotations: {\n readOnlyHint: capability.effect === \"read\",\n destructiveHint: capability.effect === \"destructive\",\n ...(meta?.idempotentHint !== undefined\n ? { idempotentHint: meta.idempotentHint }\n : {}),\n ...(meta?.openWorldHint !== undefined\n ? { openWorldHint: meta.openWorldHint }\n : {}),\n },\n call(input: unknown, options?: { readonly signal?: AbortSignal }) {\n return runtime.call({\n id: capability.id,\n input,\n presentation: true,\n ...(options?.signal ? { signal: options.signal } : {}),\n });\n },\n });\n });\n const names = new Set<string>();\n for (const tool of tools) {\n if (names.has(tool.name)) {\n throw new Error(`Duplicate MCP tool name \"${tool.name}\"`);\n }\n names.add(tool.name);\n }\n return tools;\n}\n\nfunction readMcpMeta(\n capability: ManifestCapability,\n): Exclude<McpCapabilityMeta, false> | undefined {\n const value = capability.meta.mcp;\n if (value === undefined) return undefined;\n if (!isRecord(value)) return invalidMcpMeta(capability, \"must be an object\");\n if (value.name !== undefined && typeof value.name !== \"string\") {\n return invalidMcpMeta(capability, \"name must be a string\");\n }\n if (\n value.idempotentHint !== undefined &&\n typeof value.idempotentHint !== \"boolean\"\n ) {\n return invalidMcpMeta(capability, \"idempotentHint must be a boolean\");\n }\n if (\n value.openWorldHint !== undefined &&\n typeof value.openWorldHint !== \"boolean\"\n ) {\n return invalidMcpMeta(capability, \"openWorldHint must be a boolean\");\n }\n if (\n value.icons !== undefined &&\n (!Array.isArray(value.icons) || !value.icons.every(isMcpIcon))\n ) {\n return invalidMcpMeta(capability, \"icons must be MCP icon descriptors\");\n }\n return value as Exclude<McpCapabilityMeta, false>;\n}\n\nfunction isMcpIcon(value: unknown): value is McpIcon {\n if (!isRecord(value) || typeof value.src !== \"string\") return false;\n if (value.mimeType !== undefined && typeof value.mimeType !== \"string\") {\n return false;\n }\n if (\n value.sizes !== undefined &&\n (!Array.isArray(value.sizes) ||\n !value.sizes.every((size) => typeof size === \"string\"))\n ) {\n return false;\n }\n return value.theme === undefined || value.theme === \"light\" ||\n value.theme === \"dark\";\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction invalidMcpMeta(\n capability: ManifestCapability,\n reason: string,\n): never {\n throw new Error(\n `Capability \"${capability.id}\" has invalid MCP metadata: ${reason}`,\n );\n}\n\nfunction flatten(nodes: readonly ManifestNode[]): readonly ManifestCapability[] {\n return nodes.flatMap((node) =>\n node.type === \"capability\" ? [node] : flatten(node.children)\n );\n}\n","import {\n renderPresentationMarkdown,\n type PresentationPart,\n} from \"@capable/core\";\nimport type { CallToolResult } from \"@modelcontextprotocol/server\";\n\nexport function toMcpContent(\n presentation: readonly PresentationPart[] | undefined,\n output: unknown,\n): CallToolResult[\"content\"] {\n if (!presentation?.length) {\n return [{ type: \"text\", text: stringify(output) }];\n }\n const content: CallToolResult[\"content\"] = [];\n for (const part of presentation) {\n if (part.type === \"markdown\") {\n content.push({ type: \"text\", text: renderPresentationMarkdown(part) });\n continue;\n }\n if (part.type === \"table\") {\n content.push({\n type: \"text\",\n text: renderPresentationMarkdown(part),\n });\n continue;\n }\n if (part.type === \"image\") {\n content.push(\n { type: \"text\", text: `[Image: ${part.alt}]` },\n {\n type: \"image\",\n data: part.base64,\n mimeType: part.mimeType,\n },\n );\n continue;\n }\n content.push({\n type: \"resource_link\",\n uri: part.url,\n name: part.name,\n ...(part.description ? { description: part.description } : {}),\n ...(part.mimeType ? { mimeType: part.mimeType } : {}),\n ...(part.size === undefined ? {} : { size: part.size }),\n });\n }\n return content;\n}\n\nfunction stringify(value: unknown): string {\n return typeof value === \"string\"\n ? value\n : JSON.stringify(value) ?? String(value);\n}\n","import type { ServerMount } from \"@capable/server\";\nimport {\n createApp,\n selectApp,\n TransportError,\n type ApplicationSelection,\n} from \"@capable/app\";\nimport {\n createMcpHandler,\n Server,\n type CallToolResult,\n type Icon,\n type Implementation,\n type Tool,\n} from \"@modelcontextprotocol/server\";\nimport {\n createMcp,\n type McpIcon,\n type McpTool,\n} from \"./index.ts\";\nimport { toMcpContent } from \"./presentation.ts\";\n\nexport type McpCacheHint = {\n readonly ttlMs?: number;\n readonly cacheScope?: \"public\" | \"private\";\n};\n\nexport type McpMountOptions = {\n readonly path?: string;\n readonly name?: string;\n readonly version?: string;\n readonly title?: string;\n readonly description?: string;\n readonly websiteUrl?: string;\n readonly icons?: readonly McpIcon[];\n readonly instructions?: string;\n readonly selection?: ApplicationSelection;\n readonly cache?: {\n readonly discovery?: McpCacheHint;\n readonly tools?: McpCacheHint;\n };\n};\n\nexport function mcp<TContext = any>(\n options: McpMountOptions = {},\n): ServerMount<TContext> {\n validateCacheHint(options.cache?.discovery, \"discovery\");\n validateCacheHint(options.cache?.tools, \"tools\");\n const path = normalizePath(options.path ?? \"/mcp\");\n return {\n kind: \"capable.server.mount\",\n compile(app, context, onError) {\n const description = options.description ?? app.description;\n const handler = createMcpHandler(async ({ requestInfo }) => {\n try {\n if (!requestInfo) {\n throw new Error(\n \"The MCP HTTP handler requires request information\",\n );\n }\n const executable = createApp(\n app,\n context\n ? { context: () => context({ request: requestInfo }) }\n : undefined as never,\n );\n const exposed = options.selection\n ? selectApp(executable, options.selection)\n : executable;\n const tools = await createMcp(exposed);\n return createMcpServer(tools, {\n name: options.name ?? app.name ?? \"capable\",\n version: options.version ?? app.version ?? \"0.0.0\",\n ...(options.title !== undefined ? { title: options.title } : {}),\n ...(description !== undefined\n ? { description }\n : {}),\n ...(options.websiteUrl !== undefined\n ? { websiteUrl: options.websiteUrl }\n : {}),\n ...(options.icons !== undefined\n ? { icons: toProtocolIcons(options.icons) }\n : {}),\n }, options);\n } catch (error) {\n onError?.(error);\n throw error;\n }\n }, {\n legacy: \"stateless\",\n });\n return {\n name: \"mcp\",\n async fetch(request) {\n if (new URL(request.url).pathname !== path) return undefined;\n return handler.fetch(request);\n },\n };\n },\n };\n}\n\nfunction createMcpServer(\n tools: readonly McpTool[],\n info: Implementation,\n options: Pick<McpMountOptions, \"instructions\" | \"cache\">,\n): Server {\n const server = new Server(info, {\n capabilities: { tools: {} },\n ...(options.instructions !== undefined\n ? { instructions: options.instructions }\n : {}),\n ...(options.cache !== undefined\n ? {\n cacheHints: {\n ...(options.cache.discovery !== undefined\n ? { \"server/discover\": options.cache.discovery }\n : {}),\n ...(options.cache.tools !== undefined\n ? { \"tools/list\": options.cache.tools }\n : {}),\n },\n }\n : {}),\n });\n server.setRequestHandler(\"tools/list\", () => ({\n tools: tools.map(toProtocolTool),\n }));\n server.setRequestHandler(\"tools/call\", async (request, context) => {\n const tool = tools.find(({ name }) => name === request.params.name);\n if (!tool) {\n return toolError(`Unknown tool \"${request.params.name}\"`);\n }\n try {\n const result = await tool.call(request.params.arguments ?? {}, {\n signal: context.mcpReq.signal,\n });\n return server.projectCallToolResult({\n content: toMcpContent(result.presentation, result.output),\n structuredContent: result.output,\n } satisfies CallToolResult, tool.outputSchema);\n } catch (error) {\n if (!(error instanceof TransportError)) throw error;\n return toolError(error.message, {\n code: error.code,\n status: error.status,\n data: error.data,\n });\n }\n });\n return server;\n}\n\nfunction toProtocolTool(tool: McpTool): Tool {\n return {\n name: tool.name,\n ...(tool.title ? { title: tool.title } : {}),\n ...(tool.description ? { description: tool.description } : {}),\n ...(tool.icons ? { icons: toProtocolIcons(tool.icons) } : {}),\n inputSchema: tool.inputSchema as Tool[\"inputSchema\"],\n ...(tool.outputSchema\n ? { outputSchema: tool.outputSchema as Tool[\"outputSchema\"] }\n : {}),\n _meta: tool._meta,\n annotations: tool.annotations,\n };\n}\n\nfunction toProtocolIcons(icons: readonly McpIcon[]): Icon[] {\n return icons.map((icon) => ({\n src: icon.src,\n ...(icon.mimeType !== undefined ? { mimeType: icon.mimeType } : {}),\n ...(icon.sizes !== undefined ? { sizes: [...icon.sizes] } : {}),\n ...(icon.theme !== undefined ? { theme: icon.theme } : {}),\n }));\n}\n\nfunction toolError(\n message: string,\n details?: Record<string, unknown>,\n): CallToolResult {\n return {\n isError: true,\n content: [{\n type: \"text\",\n text: details ? JSON.stringify({ message, ...details }) : message,\n }],\n };\n}\n\nfunction normalizePath(value: string): string {\n return `/${value.split(\"/\").filter(Boolean).join(\"/\")}`;\n}\n\nfunction validateCacheHint(\n hint: McpCacheHint | undefined,\n field: \"discovery\" | \"tools\",\n): void {\n if (!hint) return;\n if (\n hint.ttlMs !== undefined &&\n (!Number.isSafeInteger(hint.ttlMs) || hint.ttlMs < 0)\n ) {\n throw new RangeError(\n `MCP ${field} cache ttlMs must be a non-negative safe integer`,\n );\n }\n if (\n hint.cacheScope !== undefined &&\n hint.cacheScope !== \"public\" &&\n hint.cacheScope !== \"private\"\n ) {\n throw new RangeError(\n `MCP ${field} cache cacheScope must be \"public\" or \"private\"`,\n );\n }\n}\n"],"mappings":";;;;AAsDA,eAAsB,UACpB,KAC6B;CAC7B,MAAM,UAAU,cAAc,GAAG;CAEjC,MAAM,QAAQ,SAAQ,MADC,QAAQ,SAAS,EAAA,CACT,YAAY,CAAC,CACzC,QAAQ,eAAe,WAAW,KAAK,QAAQ,KAAK,CAAC,CACrD,KAAK,eAAe;EACnB,MAAM,OAAO,YAAY,UAAU;EACnC,OAAO,OAAO,OAAO;GACnB,MAAM,MAAM,QAAQ,WAAW,KAAK,KAAK,IAAI;GAC7C,GAAI,WAAW,QAAQ,EAAE,OAAO,WAAW,MAAM,IAAI,CAAC;GACtD,GAAI,WAAW,cAAc,EAAE,aAAa,WAAW,YAAY,IAAI,CAAC;GACxE,GAAI,MAAM,QAAQ,EAAE,OAAO,KAAK,MAAM,IAAI,CAAC;GAC3C,aAAa,WAAW,SAAS;IAC/B,MAAM;IACN,YAAY,CAAC;IACb,sBAAsB;GACxB;GACA,GAAI,WAAW,SACX,EAAE,cAAc,WAAW,OAAO,IAClC,CAAC;GACL,OAAO,EACL,4BAA4B,WAAW,GACzC;GACA,aAAa;IACX,cAAc,WAAW,WAAW;IACpC,iBAAiB,WAAW,WAAW;IACvC,GAAI,MAAM,mBAAmB,KAAA,IACzB,EAAE,gBAAgB,KAAK,eAAe,IACtC,CAAC;IACL,GAAI,MAAM,kBAAkB,KAAA,IACxB,EAAE,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AAA,KACpB,KAAK,eAAe,YACpB,KAAK,eAAe,WAEpB,MAAM,IAAI,WACR,OAAO,MAAM,gDACf;AAEJ"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"src-BWxDO2Ua.mjs","names":[],"sources":["../../server/src/index.ts"],"sourcesContent":["import type {\n AppDefinition,\n MaybePromise,\n} from \"@capable/core\";\nimport {\n createHttpHandler,\n createProtocolHandler,\n type ContextProvider,\n type CapabilitySelection,\n type ProtocolCodec,\n} from \"@capable/fetch\";\nimport {\n createApp,\n selectApp,\n type ApplicationSelection,\n} from \"@capable/app\";\n\nexport type ServerMount<TContext> = {\n readonly kind: \"capable.server.mount\";\n compile(\n app: AppDefinition<any, TContext>,\n context: ContextProvider<TContext> | undefined,\n onError?: (error: unknown) => void,\n ): CompiledServerMount;\n};\n\nexport type CompiledServerMount = {\n readonly name: string;\n readonly fetch: (request: Request) => MaybePromise<Response | undefined>;\n};\n\nexport function protocol<TContext = any>(\n options: {\n readonly path?: string;\n readonly selection?: ApplicationSelection;\n readonly codec?: ProtocolCodec;\n } = {},\n): ServerMount<TContext> {\n return {\n kind: \"capable.server.mount\",\n compile(app, context) {\n const protocol = createProtocolHandler(\n (request) => {\n const executable = createApp(\n app,\n context\n ? { context: () => context({ request }) }\n : undefined as never,\n );\n return options.selection\n ? selectApp(executable, options.selection)\n : executable;\n },\n {\n ...(options.path ? { basePath: options.path } : {}),\n ...(options.codec ? { codec: options.codec } : {}),\n },\n );\n const base = normalizePath(options.path ?? \"/~capable\");\n return {\n name: \"protocol\",\n async fetch(request) {\n if (!new URL(request.url).pathname.startsWith(`${base}/`)) {\n return undefined;\n }\n return protocol.fetch(request);\n },\n };\n },\n };\n}\n\nexport function http<TContext = any>(\n options: {\n readonly path?: string;\n readonly openapiPath?: string | false;\n readonly requireExplicitRoutes?: boolean;\n readonly selection?: CapabilitySelection;\n } = {},\n): ServerMount<TContext> {\n return {\n kind: \"capable.server.mount\",\n compile(app, context) {\n const handler = createHttpHandler(app, {\n ...(context ? { context } : {}),\n ...(options.path ? { basePath: options.path } : {}),\n ...(options.openapiPath !== undefined\n ? { openapiPath: options.openapiPath }\n : {}),\n ...(options.requireExplicitRoutes !== undefined\n ? { requireExplicitRoutes: options.requireExplicitRoutes }\n : {}),\n ...(options.selection ? { selection: options.selection } : {}),\n });\n const base = normalizePath(options.path ?? \"/api\");\n const openapiPath = options.openapiPath === false\n ? undefined\n : normalizePath(options.openapiPath ?? \"/openapi.json\");\n return {\n name: \"http\",\n async fetch(request) {\n const pathname = new URL(request.url).pathname;\n if (\n !pathname.startsWith(`${base}/`) &&\n pathname !== base &&\n pathname !== openapiPath\n ) {\n return undefined;\n }\n return handler.fetch(request);\n },\n };\n },\n };\n}\n\nexport type CapableServer = {\n readonly fetch: (request: Request) => Promise<Response>;\n};\n\nexport type ServerMiddleware = (args: {\n readonly request: Request;\n readonly next: (request?: Request) => Promise<Response>;\n}) => MaybePromise<Response>;\n\ntype CreateServerOptions<TContext> = {\n readonly context?: ContextProvider<TContext>;\n readonly mounts?: readonly ServerMount<TContext>[];\n readonly middleware?: ServerMiddleware;\n readonly onError?: (error: unknown) => void;\n};\n\ntype CreateServerArgs<TContext> = [TContext] extends [undefined]\n ? [options?: CreateServerOptions<TContext>]\n : [options: CreateServerOptions<TContext> & {\n readonly context: ContextProvider<TContext>;\n }];\n\nexport function createServer<TContext>(\n app: AppDefinition<any, TContext>,\n ...[providedOptions]: CreateServerArgs<TContext>\n): CapableServer {\n const options = (providedOptions ?? {}) as CreateServerOptions<TContext>;\n const mounts = (options.mounts ?? [protocol(), http()])\n .map((mount) => mount.compile(app, options.context, options.onError));\n\n async function dispatch(request: Request): Promise<Response> {\n for (const mount of mounts) {\n const response = await mount.fetch(request);\n if (response) return response;\n }\n return new Response(\"Not Found\", { status: 404 });\n }\n\n return Object.freeze({\n async fetch(request: Request) {\n try {\n return options.middleware\n ? await options.middleware({\n request,\n next: (nextRequest = request) => dispatch(nextRequest),\n })\n : await dispatch(request);\n } catch (error) {\n options.onError?.(error);\n return Response.json({\n ok: false,\n error: {\n code: \"INTERNAL_SERVER_ERROR\",\n message: \"Internal Server Error\",\n status: 500,\n },\n }, { status: 500 });\n }\n },\n });\n}\n\nfunction normalizePath(value: string): string {\n return `/${value.split(\"/\").filter(Boolean).join(\"/\")}`;\n}\n"],"mappings":";;;AA+BA,SAAgB,SACd,UAII,CAAC,GACkB;CACvB,OAAO;EACL,MAAM;EACN,QAAQ,KAAK,SAAS;GACpB,MAAM,WAAW,uBACd,YAAY;IACX,MAAM,aAAa,UACjB,KACA,UACI,EAAE,eAAe,QAAQ,EAAE,QAAQ,CAAC,EAAE,IACtC,KAAA,CACN;IACA,OAAO,QAAQ,YACX,UAAU,YAAY,QAAQ,SAAS,IACvC;GACN,GACA;IACE,GAAI,QAAQ,OAAO,EAAE,UAAU,QAAQ,KAAK,IAAI,CAAC;IACjD,GAAI,QAAQ,QAAQ,EAAE,OAAO,QAAQ,MAAM,IAAI,CAAC;GAClD,CACF;GACA,MAAM,OAAO,cAAc,QAAQ,QAAQ,WAAW;GACtD,OAAO;IACL,MAAM;IACN,MAAM,MAAM,SAAS;KACnB,IAAI,CAAC,IAAI,IAAI,QAAQ,GAAG,CAAC,CAAC,SAAS,WAAW,GAAG,KAAK,EAAE,GACtD;KAEF,OAAO,SAAS,MAAM,OAAO;IAC/B;GACF;EACF;CACF;AACF;AAEA,SAAgB,KACd,UAKI,CAAC,GACkB;CACvB,OAAO;EACL,MAAM;EACN,QAAQ,KAAK,SAAS;GACpB,MAAM,UAAU,kBAAkB,KAAK;IACrC,GAAI,UAAU,EAAE,QAAQ,IAAI,CAAC;IAC7B,GAAI,QAAQ,OAAO,EAAE,UAAU,QAAQ,KAAK,IAAI,CAAC;IACjD,GAAI,QAAQ,gBAAgB,KAAA,IACxB,EAAE,aAAa,QAAQ,YAAY,IACnC,CAAC;IACL,GAAI,QAAQ,0BAA0B,KAAA,IAClC,EAAE,uBAAuB,QAAQ,sBAAsB,IACvD,CAAC;I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