capable-kit 0.1.0-alpha.10 → 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 (67) hide show
  1. package/CHANGELOG.md +171 -0
  2. package/LICENSE +21 -0
  3. package/README.md +6 -0
  4. package/dist/ai-sdk.d.mts +2 -2
  5. package/dist/ai-sdk.mjs +1 -1
  6. package/dist/app.d.mts +2 -2
  7. package/dist/app.mjs +1 -1
  8. package/dist/bin.mjs +19 -15
  9. package/dist/bin.mjs.map +1 -1
  10. package/dist/cli.d.mts +1 -1
  11. package/dist/cli.mjs +1 -1
  12. package/dist/core.d.mts +3 -3
  13. package/dist/core.mjs +2 -2
  14. package/dist/eve.d.mts +20 -14
  15. package/dist/eve.mjs +450 -211
  16. package/dist/eve.mjs.map +1 -1
  17. package/dist/http.d.mts +1 -1
  18. package/dist/http.mjs +1 -1
  19. package/dist/{index-WiBWfyTn.d.mts → index-BIO_hbXJ.d.mts} +8 -2
  20. package/dist/{index-D-NV4PiU.d.mts → index-C0tU5Y2n.d.mts} +4 -4
  21. package/dist/{index-CHuCLJIs.d.mts → index-CwvjDizW.d.mts} +5 -3
  22. package/dist/{index-1A44jLuE.d.mts → index-F_eaksy8.d.mts} +7 -4
  23. package/dist/index.d.mts +4 -4
  24. package/dist/index.mjs +2 -2
  25. package/dist/mcp.d.mts +14 -4
  26. package/dist/mcp.mjs +2 -2
  27. package/dist/{mount-BmLHp349.mjs → mount-pvIaehZC.mjs} +148 -104
  28. package/dist/mount-pvIaehZC.mjs.map +1 -0
  29. package/dist/react-query.d.mts +1 -1
  30. package/dist/react-query.mjs +1 -1
  31. package/dist/runtime-support.d.mts +1 -1
  32. package/dist/runtime-support.mjs +3 -3
  33. package/dist/server.d.mts +1 -1
  34. package/dist/server.mjs +1 -1
  35. package/dist/{src-_6OmFRYa.mjs → src-Bk3lEhI7.mjs} +38 -18
  36. package/dist/src-Bk3lEhI7.mjs.map +1 -0
  37. package/dist/{src-DePlcG_t.mjs → src-C2OEkZ3c.mjs} +38 -65
  38. package/dist/src-C2OEkZ3c.mjs.map +1 -0
  39. package/dist/{src-C5jGDnuu.mjs → src-DFrxQ_S6.mjs} +9 -7
  40. package/dist/src-DFrxQ_S6.mjs.map +1 -0
  41. package/dist/{src-3LE9S4QE.mjs → src-DklM1g7V.mjs} +5 -5
  42. package/dist/src-DklM1g7V.mjs.map +1 -0
  43. package/dist/{src-B2WeUwUT.mjs → src-TCQGaWar.mjs} +60 -18
  44. package/dist/src-TCQGaWar.mjs.map +1 -0
  45. package/dist/{subscription-DPdwovhw.d.mts → subscription-fVgS4T8P.d.mts} +2 -2
  46. package/dist/swr.d.mts +1 -1
  47. package/dist/swr.mjs +1 -1
  48. package/docs/CONTEXT.md +5 -2
  49. package/docs/internal/eve-recovery-validation.md +12 -11
  50. package/docs/internal/implementation-friction.md +59 -0
  51. package/docs/site/concepts/errors.mdx +15 -3
  52. package/docs/site/hosting/standalone-server.mdx +2 -0
  53. package/docs/site/patterns/remote-apps.mdx +23 -1
  54. package/docs/site/quickstart.mdx +2 -1
  55. package/docs/site/reference/packages-and-entry-points.mdx +2 -1
  56. package/docs/site/reference/the-cap-cli.mdx +2 -2
  57. package/docs/site/surfaces/eve.mdx +6 -4
  58. package/docs/site/surfaces/mcp.mdx +84 -2
  59. package/package.json +13 -7
  60. package/src/index.ts +2 -0
  61. package/src/package.test.ts +6 -0
  62. package/dist/mount-BmLHp349.mjs.map +0 -1
  63. package/dist/src-3LE9S4QE.mjs.map +0 -1
  64. package/dist/src-B2WeUwUT.mjs.map +0 -1
  65. package/dist/src-C5jGDnuu.mjs.map +0 -1
  66. package/dist/src-DePlcG_t.mjs.map +0 -1
  67. package/dist/src-_6OmFRYa.mjs.map +0 -1
@@ -70,11 +70,23 @@ The same guard works against a remote app, because the error code and data cross
70
70
 
71
71
  ## Undeclared failures [#undeclared]
72
72
 
73
- Any failure that is not in the located capability's error sets becomes `INTERNAL_SERVER_ERROR`. The original value is kept as `cause` on the server and is never serialized to a caller.
73
+ Where an unexpected failure is handled depends on the boundary:
74
74
 
75
- > **Why the strictness**
75
+ - **In-process (`executeCapability()`, local `createApp()`, local CLI):** Unexpected runtime errors (such as database or third-party SDK errors) propagate unchanged with their original class, message, and stack trace. Declared `CapableError`s throw directly without extra wrapper layers. Throwing an undeclared `CapableError` still normalizes to `INTERNAL_SERVER_ERROR`.
76
+ - **External boundaries (`http()`, `protocol()`, `mcp()`):** Any unexpected or undeclared failure is masked to `INTERNAL_SERVER_ERROR` (HTTP 500) before crossing the wire so internal details never leak to external clients or agents. Pass `onError` to `createServer()` (or `createHttpHandler()` / `createProtocolHandler()`) to observe the original error in logs or error tracking.
77
+
78
+ ```ts title="server.ts"
79
+ const server = createServer(definition, {
80
+ mounts: [protocol(), http(), mcp()],
81
+ onError(error) {
82
+ logger.error(error); // receives the original unexpected error
83
+ },
84
+ });
85
+ ```
86
+
87
+ > **Why mask at the wire boundary**
76
88
  >
77
- > A surface can only present failures it can describe. Declared errors appear in OpenAPI, in CLI output, and in agent-visible schemas. Leaking arbitrary exception text would make those contracts unreliable and would risk exposing internals.
89
+ > A remote surface can only present failures it can describe. Declared errors appear in OpenAPI, in CLI output, and in agent-visible schemas. Masking unexpected exceptions at HTTP, protocol, and MCP boundaries keeps wire contracts safe without blinding in-process callers, tests, or local CLIs.
78
90
 
79
91
  ## Inherited errors [#groups]
80
92
 
@@ -56,6 +56,8 @@ cap build --preset vercel # build for another target
56
56
  | `cap preview` | Runs a `node-server` build locally |
57
57
  | `cap cli` | Invokes capabilities in the local project or against a URL |
58
58
 
59
+ `cap build` bundles with [Rolldown](https://rolldown.rs), which you install yourself so apps that never build with `cap` stay light. `cap init` adds it for you; otherwise run `pnpm add -D rolldown`. `cap dev` does not need it.
60
+
59
61
  Full options and project discovery rules are in the [CLI reference](/reference/cli).
60
62
 
61
63
  ## Growing the boundary [#boundary]
@@ -38,9 +38,31 @@ export async function openTodos(app: typeof local | typeof remote) {
38
38
  | --- | --- | --- |
39
39
  | Needs | The implementation, and context only if one is declared | A transport, and the definition as a type |
40
40
  | Executes | In this process | Wherever the server placed it |
41
- | Manifest | Derived from the definition | Fetched once, then cached, on first call |
41
+ | Manifest | Derived from the definition | Fetched once on first call, or supplied statically via `{ manifest }` |
42
42
  | Failure mode | Throws from the handler | Also transport errors |
43
43
 
44
+ ## Static manifests for CLIs [#static-manifest]
45
+
46
+ By default, `createRemoteApp()` fetches the manifest from `transport.manifest()` on first use and caches it in memory. For short-lived processes such as a CLI, that adds a network round trip to every run. Pass a prebuilt manifest to `createRemoteApp()` to validate it up front and skip discovery completely:
47
+
48
+ ```ts title="cli.ts"
49
+ import { createRemoteApp, type ApplicationManifest } from "capable-kit";
50
+ import { createHttpTransport } from "capable-kit/http";
51
+ import { createCli } from "capable-kit/cli";
52
+ import type { AppDefinition } from "./capable.app";
53
+ import manifest from "./generated/capable-manifest.json" with { type: "json" };
54
+
55
+ const remote = createRemoteApp<AppDefinition>(
56
+ createHttpTransport({ url: "https://todos.example.com/~capable/" }),
57
+ { manifest: manifest as ApplicationManifest },
58
+ );
59
+
60
+ // Runs help offline and sends only POST /~capable/call/<id> on invocation.
61
+ await createCli(remote).run(process.argv.slice(2));
62
+ ```
63
+
64
+ Generate the static JSON artifact at build time with `createAppManifest(definition)` from `capable-kit/app`.
65
+
44
66
  > **No code generation**
45
67
  >
46
68
  > Export a named type derived from the definition, then import that type in remote consumers. The type is erased at build time, so no server code or generated client ends up in the caller. Ship the definition's types in a package and any consumer can be typed against it.
@@ -17,10 +17,11 @@ Capable works two ways: as its own service, or embedded in an app you already ha
17
17
 
18
18
  1. ### Install Capable
19
19
 
20
- The `capable` package includes the runtime and the `capable` command for development, builds, and derived CLI access. Zod is the schema authoring library in this example; Capable consumes its Standard Schema and Standard JSON Schema interfaces.
20
+ The `capable` package includes the runtime and the `capable` command for development, builds, and derived CLI access. Zod is the schema authoring library in this example; Capable consumes its Standard Schema and Standard JSON Schema interfaces. `cap build` bundles the server with Rolldown, so add it as a development dependency.
21
21
 
22
22
  ```sh title="terminal"
23
23
  pnpm add capable-kit zod
24
+ pnpm add -D rolldown
24
25
  ```
25
26
 
26
27
  2. ### Create capable.app.ts
@@ -50,7 +50,7 @@ import {
50
50
  | `capable-kit/server` | `createServer()` plus the `protocol()` and `http()` mounts |
51
51
  | `capable-kit/http` | Capable transport and HTTP projection: `createHttpTransport()`, `createHttpHandler()`, `defineProtocolCodec()` |
52
52
  | `capable-kit/cli` | `createCli()` |
53
- | `capable-kit/mcp` | `createMcp()` and the `mcp()` server mount |
53
+ | `capable-kit/mcp` | `createMcp()`, `registerCapableTools()`, and the `mcp()` server mount |
54
54
  | `capable-kit/eve` | `createEveTools()` |
55
55
  | `capable-kit/ai-sdk` | `createAiSdkTools()` |
56
56
  | `capable-kit/app` | App runtime internals: manifests, transport types, selection |
@@ -78,6 +78,7 @@ import {
78
78
  | `selectApp()` | `selectApp(app, { include, exclude })` | Exclude wins over include |
79
79
  | `subscribe()` | `subscribe(app.todos.list, input, { signal })` | Async iterator of replacements |
80
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) |
81
82
  | `createServer()` | `createServer(definition, { context, mounts, middleware })` | Returns `{ fetch }` |
82
83
 
83
84
  ## Custom surface display [#custom-display]
@@ -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
 
@@ -108,7 +108,7 @@ meta: {
108
108
 
109
109
  ## Durability [#durability]
110
110
 
111
- The tool catalog resolves at Eve's `session.started` boundary. Eve reruns that resolver to reconstruct callbacks after a cold start. Capable persists the capability ID and rebuilds provider Apps using the current execution session. Define your App or provider in deployed code and keep its data in persistent storage. The repository currently backports `defineDurableCallback` from Eve PR #2981 at commit `8e6964036657082ce1405864cf3313ad11fc8d60`; external consumers need the same patch until Eve releases the helper.
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.
112
112
 
113
113
  > **Interrupted steps can re-run**
114
114
  >
@@ -150,7 +150,8 @@ recipes chef send "Vegetarian please" --run-id '<runId>' --wait
150
150
  ```
151
151
 
152
152
  Without `wait`, `send` returns the accepted ID and `running` immediately. Waiting
153
- uses Eve's response stream and stops at completion, input, failure, or cancellation.
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.
154
155
  The default deadline is 30 seconds (`timeoutMs`, at most five minutes); on timeout,
155
156
  it returns the accepted ID with `running`. A single pending question is answered
156
157
  automatically; multiple questions require `requestId`. Selection-only questions
@@ -160,8 +161,9 @@ Run IDs are durable Eve session IDs, so subsequent CLI processes can attach
160
161
  without a local mapping. The host authorizes every operation against the caller
161
162
  and session. Only typed questions are answerable; approvals remain host-owned.
162
163
 
163
- The adapter targets Eve 0.52.3. Each result or continuation reconstructs state from
164
- Eve's finite durable history, with configurable event and time limits. An
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
165
167
  incomplete read fails rather than returning partial state. Call `dispose()` to
166
168
  abort local requests; Eve execution continues until explicitly cancelled.
167
169
 
@@ -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.
package/package.json CHANGED
@@ -1,6 +1,12 @@
1
1
  {
2
2
  "name": "capable-kit",
3
- "version": "0.1.0-alpha.10",
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",
@@ -66,13 +72,14 @@
66
72
  "src",
67
73
  "verify-package-exports.mjs",
68
74
  "README.md",
69
- "CHANGELOG.md"
75
+ "CHANGELOG.md",
76
+ "LICENSE"
70
77
  ],
71
78
  "directories": {
72
79
  "doc": "./docs"
73
80
  },
74
81
  "engines": {
75
- "node": ">=20"
82
+ "node": ">=22.22"
76
83
  },
77
84
  "publishConfig": {
78
85
  "access": "public",
@@ -82,14 +89,13 @@
82
89
  "@standard-schema/spec": "^1.1.0",
83
90
  "@modelcontextprotocol/server": "^2.0.0",
84
91
  "markdansi": "0.3.2",
85
- "nitro": "3.0.260610-beta",
86
- "superjson": "2.2.6",
87
- "zod": "^4.4.3"
92
+ "nitro": "3.0.261103-rc",
93
+ "superjson": "2.2.6"
88
94
  },
89
95
  "peerDependencies": {
90
96
  "@tanstack/react-query": ">=5.80.2 <6",
91
97
  "ai": "^7.0.82",
92
- "eve": "0.52.3",
98
+ "eve": "^1.0.0",
93
99
  "swr": ">=2.3.0 <3"
94
100
  },
95
101
  "peerDependenciesMeta": {
package/src/index.ts CHANGED
@@ -35,7 +35,9 @@ export {
35
35
  createRemoteApp,
36
36
  composeApps,
37
37
  customize,
38
+ type ApplicationManifest,
38
39
  type CapabilityCustomization,
40
+ type CreateRemoteAppOptions,
39
41
  type CustomizedCapability,
40
42
  selectApp,
41
43
  subscribe,
@@ -55,15 +55,18 @@ describe("published package", () => {
55
55
  ),
56
56
  ) as {
57
57
  readonly bin?: Readonly<Record<string, string>>;
58
+ readonly dependencies?: Readonly<Record<string, string>>;
58
59
  readonly directories?: { readonly doc?: string };
59
60
  readonly exports?: Readonly<Record<
60
61
  string,
61
62
  string | Readonly<Record<string, string>>
62
63
  >>;
64
+ readonly license?: string;
63
65
  readonly peerDependenciesMeta?: Readonly<Record<
64
66
  string,
65
67
  { readonly optional?: boolean }
66
68
  >>;
69
+ readonly repository?: unknown;
67
70
  readonly scripts?: Record<string, string>;
68
71
  };
69
72
  const quickstart = execFileSync(
@@ -111,6 +114,9 @@ describe("published package", () => {
111
114
  expect(paths).toContain("package-docs.mjs");
112
115
  expect(paths).toContain("prepare-package.mjs");
113
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");
114
120
  expect(manifest.directories?.doc).toBe("./docs");
115
121
  expect(manifest.scripts).toMatchObject({
116
122
  prepack: "node prepare-package.mjs",
@@ -1 +0,0 @@
1
- {"version":3,"file":"mount-BmLHp349.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 getCapabilityDisplay,\n getCapabilityNavigationMeta,\n flattenManifestCapabilities,\n type AnyApp,\n type JsonSchema,\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\ndeclare global {\n interface CapableCustomizationMeta {\n readonly mcp?: McpCapabilityMeta;\n }\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 = flattenManifestCapabilities(manifest.capabilities)\n .map((capability) => ({ ...capability, ...getCapabilityDisplay(capability) }))\n .filter((capability) => {\n const meta = capability.meta.mcp;\n if (meta === false) return false;\n if (capability.execution !== \"events\") return true;\n if (meta !== undefined) {\n throw new Error(\n `Event Capability \"${capability.id}\" cannot be exposed as an MCP tool`,\n );\n }\n return false;\n })\n .map((capability) => {\n const meta = readMcpMeta(capability);\n const navigation = getCapabilityNavigationMeta(capability, \"mcp\");\n const name = navigation === false ? undefined : navigation?.name;\n return Object.freeze({\n name: 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","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":";;;;AA8DA,eAAsB,UACpB,KAC6B;CAC7B,MAAM,UAAU,cAAc,GAAG;CAEjC,MAAM,QAAQ,6BAA4B,MADnB,QAAQ,SAAS,EAAA,CACW,YAAY,CAAC,CAC7D,KAAK,gBAAgB;EAAE,GAAG;EAAY,GAAG,qBAAqB,UAAU;CAAE,EAAE,CAAC,CAC7E,QAAQ,eAAe;EACtB,MAAM,OAAO,WAAW,KAAK;EAC7B,IAAI,SAAS,OAAO,OAAO;EAC3B,IAAI,WAAW,cAAc,UAAU,OAAO;EAC9C,IAAI,SAAS,KAAA,GACX,MAAM,IAAI,MACR,qBAAqB,WAAW,GAAG,mCACrC;EAEF,OAAO;CACT,CAAC,CAAC,CACD,KAAK,eAAe;EACnB,MAAM,OAAO,YAAY,UAAU;EACnC,MAAM,aAAa,4BAA4B,YAAY,KAAK;EAChE,MAAM,OAAO,eAAe,QAAQ,KAAA,IAAY,YAAY;EAC5D,OAAO,OAAO,OAAO;GACnB,MAAM,QAAQ,WAAW,KAAK,KAAK,IAAI;GACvC,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,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AAG;AACtD;AAEA,SAAS,kBACP,MACA,OACM;CACN,IAAI,CAAC,MAAM;CACX,IACE,KAAK,UAAU,KAAA,MACd,CAAC,OAAO,cAAc,KAAK,KAAK,KAAK,KAAK,QAAQ,IAEnD,MAAM,IAAI,WACR,OAAO,MAAM,iDACf;CAEF,IACE,KAAK,eAAe,KAAA,KACpB,KAAK,eAAe,YACpB,KAAK,eAAe,WAEpB,MAAM,IAAI,WACR,OAAO,MAAM,gDACf;AAEJ"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"src-3LE9S4QE.mjs","names":["kebabCase","renderMarkdown"],"sources":["../../cli/src/commands.ts","../../cli/src/style.ts","../../cli/src/help.ts","../../cli/src/presentation.ts","../../cli/src/index.ts"],"sourcesContent":["import {\n getCapabilityDisplay,\n getCapabilityNavigationMeta,\n} from \"@capable/app\";\nimport type {\n ManifestGroup,\n ManifestNode,\n ManifestCapability,\n} from \"@capable/app\";\nimport type {\n CliGroupMeta,\n CliCapabilityMeta,\n} from \"./index.ts\";\n\nexport type CliCommand = {\n readonly command: readonly string[];\n readonly capability: ManifestCapability;\n readonly meta: Exclude<CliCapabilityMeta, false>;\n};\n\nexport type CliCommandGroup = {\n readonly command: readonly string[];\n readonly title?: string;\n readonly description?: string;\n};\n\nexport type CliCommandCatalog = {\n readonly commands: readonly CliCommand[];\n readonly groups: readonly CliCommandGroup[];\n};\n\nexport function collectCommands(\n nodes: readonly ManifestNode[],\n parent: readonly string[] = [],\n): CliCommandCatalog {\n const commands: CliCommand[] = [];\n const groups: CliCommandGroup[] = [];\n\n for (const node of nodes) {\n if (node.type === \"group\") {\n const meta = (node.meta.cli ?? {}) as CliGroupMeta;\n const command = [...parent, meta.name ?? node.key];\n groups.push(groupFrom(node, command));\n const children = collectCommands(node.children, command);\n commands.push(...children.commands);\n groups.push(...children.groups);\n continue;\n }\n\n const capability = { ...node, ...getCapabilityDisplay(node) };\n const rawMeta = capability.meta.cli as CliCapabilityMeta | undefined;\n if (rawMeta === false) continue;\n const meta = rawMeta ?? {};\n // Curated leaves get navigation from the destination tree, unless explicitly\n // overridden there. Keep source non-navigational metadata (e.g. positionals).\n const navigationMeta = getCapabilityNavigationMeta(node, \"cli\");\n const navigation = navigationMeta === false ? {} : navigationMeta ?? {};\n commands.push({\n command: navigation.command ?? [...parent, navigation.name ?? node.path.at(-1)!],\n capability,\n meta,\n });\n }\n\n return {\n commands: Object.freeze(commands),\n groups: Object.freeze(groups),\n };\n}\n\nfunction groupFrom(\n node: ManifestGroup,\n command: readonly string[],\n): CliCommandGroup {\n return Object.freeze({\n command: Object.freeze(command),\n ...(node.title ? { title: node.title } : {}),\n ...(node.description ? { description: node.description } : {}),\n });\n}\n","export type CliStyle = {\n readonly bold: (text: string) => string;\n readonly accent: (text: string) => string;\n readonly dim: (text: string) => string;\n};\n\nexport type CliRow = {\n readonly label: string;\n readonly description?: string;\n};\n\n/** Every help line hangs off this margin. */\nexport const MARGIN = \" \";\n\n/** Rows sit one step inside their section heading. */\nexport const ROW_INDENT = \" \";\n\n/** Widest label that still keeps descriptions in a single column. */\nconst MAX_LABEL_WIDTH = 30;\n\nconst LABEL_GAP = 2;\n\nexport function createCliStyle(color?: boolean): CliStyle {\n const enabled = color ?? supportsColor();\n return {\n bold: enabled\n ? (text: string) => `\\u001B[1m${text}\\u001B[22m`\n : identity,\n accent: enabled\n ? (text: string) => `\\u001B[36m${text}\\u001B[39m`\n : identity,\n dim: enabled\n ? (text: string) => `\\u001B[2m${text}\\u001B[22m`\n : identity,\n };\n}\n\nexport function supportsColor(\n env: Record<string, string | undefined> = process.env,\n isTTY: boolean = Boolean(process.stdout.isTTY),\n): boolean {\n if (\"NO_COLOR\" in env) return false;\n if (env.FORCE_COLOR !== undefined) return env.FORCE_COLOR !== \"0\";\n return isTTY && env.TERM !== \"dumb\";\n}\n\nexport function renderRows(\n rows: readonly CliRow[],\n style: CliStyle,\n options: {\n readonly indent?: string;\n /** Absolute column for descriptions, so sibling sections stay aligned. */\n readonly column?: number;\n } = {},\n): string {\n const indent = options.indent ?? ROW_INDENT;\n const width = Math.max(\n 0,\n (options.column ?? descriptionColumn(rows, indent)) - indent.length -\n LABEL_GAP,\n );\n return rows.map(({ label, description }) => {\n const line = `${indent}${style.accent(label)}`;\n if (!description) return line;\n return label.length > width\n ? `${line}\\n${indent}${\" \".repeat(width + LABEL_GAP)}${style.dim(description)}`\n : `${line}${\" \".repeat(width - label.length + LABEL_GAP)}${\n style.dim(description)\n }`;\n }).join(\"\\n\");\n}\n\n/** Shared description column so sibling sections stay visually aligned. */\nexport function descriptionColumn(\n rows: readonly CliRow[],\n indent: string = ROW_INDENT,\n): number {\n const labels = rows\n .filter(({ description }) => description !== undefined)\n .map(({ label }) => label.length)\n .filter((length) => length <= MAX_LABEL_WIDTH);\n return indent.length + LABEL_GAP + Math.max(0, ...labels);\n}\n\nexport function renderSection(\n title: string,\n body: string,\n style: CliStyle,\n): string {\n return `${MARGIN}${style.bold(title)}\\n\\n${body}`;\n}\n\nfunction identity(text: string): string {\n return text;\n}\n","import type {\n ApplicationManifest,\n JsonSchema,\n} from \"@capable/app\";\nimport type {\n CliCommand,\n CliCommandGroup,\n} from \"./commands.ts\";\nimport {\n descriptionColumn,\n MARGIN,\n renderRows,\n renderSection,\n ROW_INDENT,\n type CliRow,\n type CliStyle,\n} from \"./style.ts\";\n\nconst GLOBAL_OPTIONS: readonly CliRow[] = [\n { label: \"--json\", description: \"Print canonical JSON\" },\n { label: \"-h, --help\", description: \"Show help\" },\n];\n\nexport function renderRootHelp(\n manifest: Pick<ApplicationManifest, \"name\" | \"description\">,\n commands: readonly CliCommand[],\n groups: readonly CliCommandGroup[],\n invocationName: string,\n style: CliStyle,\n): string {\n const root = commands.find((command) => command.command.length === 0);\n const sections = commandSections(commands, groups);\n const nested = sections.some((section) => section.title !== undefined);\n const column = Math.max(\n descriptionColumn(\n sections.flatMap((section) => section.rows),\n nested ? `${ROW_INDENT}${MARGIN}` : ROW_INDENT,\n ),\n descriptionColumn(GLOBAL_OPTIONS),\n );\n return renderHelp([\n banner({\n title: manifest.name,\n ...(manifest.description ? { description: manifest.description } : {}),\n usage: [invocationName, root && commands.length === 1 ? signature(root) : \"<command>\", \"[options]\"].filter(Boolean).join(\" \"),\n style,\n }),\n renderSection(\n \"Commands\",\n sections\n .map((section) =>\n [\n section.title ? `${ROW_INDENT}${style.dim(section.title)}` : undefined,\n renderRows(section.rows, style, {\n column,\n ...(section.title ? { indent: `${ROW_INDENT}${MARGIN}` } : {}),\n }),\n ].filter(Boolean).join(\"\\n\")\n )\n .join(\"\\n\\n\"),\n style,\n ),\n root\n ? renderCommandInputs(root, style, column)\n : renderSection(\"Options\", renderRows(GLOBAL_OPTIONS, style, { column }), style),\n commands.some((command) => command.command.length > 0)\n ? hint(`Run \\`${invocationName} <command> --help\\` for details on a command.`, style)\n : undefined,\n ]);\n}\n\nexport function renderGroupHelp(\n group: CliCommandGroup,\n commands: readonly CliCommand[],\n invocationName: string,\n style: CliStyle,\n): string {\n const prefix = group.command.join(\" \");\n const rows = commands\n .filter((candidate) => startsWith(candidate.command, group.command))\n .map((candidate) => ({\n label: signature(candidate, candidate.command.slice(group.command.length)),\n ...describe(candidate),\n }));\n const column = descriptionColumn([...rows, ...GLOBAL_OPTIONS]);\n return renderHelp([\n banner({\n ...(group.title ? { title: group.title } : {}),\n ...(group.description ? { description: group.description } : {}),\n usage: `${invocationName} ${prefix} <command> [options]`,\n style,\n }),\n renderSection(\"Commands\", renderRows(rows, style, { column }), style),\n renderSection(\"Options\", renderRows(GLOBAL_OPTIONS, style, { column }), style),\n hint(\n `Run \\`${invocationName} ${prefix} <command> --help\\` for details on a command.`,\n style,\n ),\n ]);\n}\n\nexport function renderCommandHelp(\n command: CliCommand,\n invocationName: string,\n style: CliStyle,\n): string {\n return renderHelp([\n banner({\n ...(command.capability.title ? { title: command.capability.title } : {}),\n ...(command.capability.description\n ? { description: command.capability.description }\n : {}),\n usage: [invocationName, signature(command), \"[options]\"].join(\" \"),\n style,\n }),\n renderCommandInputs(command, style),\n ]);\n}\n\nfunction renderCommandInputs(command: CliCommand, style: CliStyle, minColumn = 0): string {\n const properties = fields(command);\n const required = requiredFields(command);\n const positionals = command.meta.positional ?? [];\n const argumentRows = positionals.map((name) => ({\n label: placeholder(name, required.has(name)),\n ...description(properties[name], { choices: true }),\n }));\n const optionRows = [\n ...Object.entries(properties)\n .filter(([name]) => !positionals.includes(name))\n .map(([name, schema]) => ({\n label: optionLabel(name, schema),\n ...description(schema, { required: required.has(name) }),\n })),\n ...(command.capability.execution === \"live\"\n ? [{ label: \"--watch\", description: \"Stream updates until interrupted\" }]\n : []),\n ];\n const column = Math.max(minColumn, descriptionColumn([\n ...argumentRows,\n ...optionRows,\n ...GLOBAL_OPTIONS,\n ]));\n\n return [\n argumentRows.length\n ? renderSection(\n \"Arguments\",\n renderRows(argumentRows, style, { column }),\n style,\n )\n : undefined,\n optionRows.length\n ? renderSection(\"Options\", renderRows(optionRows, style, { column }), style)\n : undefined,\n renderSection(\n optionRows.length ? \"Global Options\" : \"Options\",\n renderRows(GLOBAL_OPTIONS, style, { column }),\n style,\n ),\n ].filter(Boolean).join(\"\\n\\n\");\n}\n\n/** Root commands are grouped under their top-level group, Vercel style. */\nfunction commandSections(\n commands: readonly CliCommand[],\n groups: readonly CliCommandGroup[],\n): readonly { readonly title?: string; readonly rows: readonly CliRow[] }[] {\n const roots = groups.filter((group) => group.command.length === 1);\n const loose = commands.filter((command) =>\n !roots.some((group) => startsWith(command.command, group.command))\n );\n const sections = roots.map((group) => ({\n ...(roots.length > 1 || loose.length\n ? { title: group.title ?? group.command.join(\" \") }\n : {}),\n rows: commands\n .filter((command) => startsWith(command.command, group.command))\n .map(row),\n })).filter((section) => section.rows.length > 0);\n return [\n ...sections,\n ...(loose.length\n ? [{\n ...(sections.length ? { title: \"General\" } : {}),\n rows: loose.map(row),\n }]\n : []),\n ];\n}\n\nfunction row(command: CliCommand): CliRow {\n return { label: signature(command), ...describe(command) };\n}\n\nfunction describe(command: CliCommand): { description?: string } {\n const text = command.capability.title ?? command.capability.description;\n return text ? { description: text } : {};\n}\n\n/** `todo delete <todoId>` — command path plus its positional slots. */\nfunction signature(\n command: CliCommand,\n path: readonly string[] = command.command,\n): string {\n const required = requiredFields(command);\n return [\n ...path,\n ...(command.meta.positional ?? []).map((name) =>\n placeholder(name, required.has(name))\n ),\n ].join(\" \");\n}\n\nfunction placeholder(name: string, required: boolean): string {\n return required ? `<${name}>` : `[${name}]`;\n}\n\n/** Title, prose, then the invocation line. No heading needed above it. */\nfunction banner(options: {\n readonly title?: string;\n readonly description?: string;\n readonly usage: string;\n readonly style: CliStyle;\n}): string {\n const { style } = options;\n return [\n [\n options.title ? `${MARGIN}${style.bold(options.title)}` : undefined,\n options.description\n ? `${MARGIN}${style.dim(options.description)}`\n : undefined,\n ].filter(Boolean).join(\"\\n\"),\n `${MARGIN}${style.accent(options.usage)}`,\n ].filter(Boolean).join(\"\\n\\n\");\n}\n\nfunction hint(text: string, style: CliStyle): string {\n return `${MARGIN}${style.dim(text)}`;\n}\n\nfunction fields(command: CliCommand): Record<string, JsonSchema> {\n return (command.capability.input?.properties as\n | Record<string, JsonSchema>\n | undefined) ?? {};\n}\n\nfunction requiredFields(command: CliCommand): ReadonlySet<string> {\n return new Set(\n command.capability.input?.required as readonly string[] | undefined,\n );\n}\n\nfunction optionLabel(name: string, schema: JsonSchema): string {\n const flag = `--${kebabCase(name)}`;\n if (schema.type === \"boolean\") return flag;\n if (Array.isArray(schema.enum)) {\n return `${flag} <${schema.enum.map(String).join(\"|\")}>`;\n }\n if (schema.type === \"array\" || schema.type === \"object\") {\n return `${flag} <json>`;\n }\n return `${flag} <${String(schema.type ?? \"value\")}>`;\n}\n\n/**\n * Descriptions stay one short line: prose first, then only the facts a reader\n * cannot guess from the label (requiredness, defaults, choices).\n */\nfunction description(\n schema: JsonSchema | undefined,\n options: { readonly required?: boolean; readonly choices?: boolean } = {},\n): { description?: string } {\n const prose = typeof schema?.description === \"string\"\n ? schema.description\n : undefined;\n const notes = [\n options.choices && Array.isArray(schema?.enum)\n ? `one of ${schema.enum.map(String).join(\", \")}`\n : undefined,\n schema?.default !== undefined\n ? `default: ${String(schema.default)}`\n : undefined,\n options.required ? \"required\" : undefined,\n ].filter(Boolean);\n const text = [prose, notes.length ? `(${notes.join(\", \")})` : undefined]\n .filter(Boolean)\n .join(\" \");\n return text ? { description: text } : {};\n}\n\nfunction startsWith(\n value: readonly string[],\n prefix: readonly string[],\n): boolean {\n return prefix.every((part, index) => value[index] === part);\n}\n\nfunction kebabCase(value: string): string {\n return value.replace(/[A-Z]/g, (character) => `-${character.toLowerCase()}`);\n}\n\nfunction renderHelp(sections: readonly (string | undefined)[]): string {\n return `\\n${sections.filter(Boolean).join(\"\\n\\n\")}\\n`;\n}\n","import type { CapabilityResult } from \"@capable/app\";\nimport { renderPresentationMarkdown } from \"@capable/core\";\nimport { render as renderMarkdown, type RenderOptions } from \"markdansi\";\n\nexport type CliPresentationOptions = {\n readonly color: boolean;\n readonly isTTY: boolean;\n readonly columns: number;\n readonly markdown?: RenderOptions;\n};\n\nexport function renderCliCapabilityResult(\n result: CapabilityResult,\n options: CliPresentationOptions,\n): string {\n if (result.presentation !== undefined) {\n return renderCliMarkdown(\n renderPresentationMarkdown(result.presentation),\n options,\n );\n }\n return typeof result.output === \"string\"\n ? result.output\n : JSON.stringify(result.output, null, 2);\n}\n\nfunction renderCliMarkdown(\n markdown: string,\n options: CliPresentationOptions,\n): string {\n return options.isTTY\n ? renderMarkdown(markdown, {\n color: options.color,\n width: options.columns,\n ...options.markdown,\n })\n : markdown;\n}\n","import type { RenderOptions } from \"markdansi\";\nimport type {\n GroupMetaRegistry,\n CapabilityMetaRegistry,\n} from \"@capable/core\";\nimport {\n getAppRuntime,\n TransportError,\n type AnyApp,\n type JsonSchema,\n} from \"@capable/app\";\nimport {\n collectCommands,\n type CliCommand,\n type CliCommandGroup,\n} from \"./commands.ts\";\nimport {\n renderCommandHelp,\n renderGroupHelp,\n renderRootHelp,\n} from \"./help.ts\";\nimport {\n createCliStyle,\n supportsColor,\n} from \"./style.ts\";\nimport { renderCliCapabilityResult } from \"./presentation.ts\";\n\n/** Shared help layout, so every Capable surface prints the same shape. */\nexport {\n createCliStyle,\n descriptionColumn,\n MARGIN,\n renderRows,\n renderSection,\n ROW_INDENT,\n supportsColor,\n type CliRow,\n type CliStyle,\n} from \"./style.ts\";\n\nexport type CliCapabilityMeta =\n | false\n | {\n readonly name?: string;\n readonly command?: readonly string[];\n readonly positional?: readonly string[];\n };\n\ndeclare global {\n interface CapableCustomizationMeta {\n readonly cli?: CliCapabilityMeta;\n }\n}\n\nexport type CliGroupMeta = {\n readonly name?: string;\n};\n\ndeclare module \"@capable/core\" {\n interface CapabilityMetaRegistry {\n readonly cli?: CliCapabilityMeta;\n }\n\n interface GroupMetaRegistry {\n readonly cli?: CliGroupMeta;\n }\n}\n\nexport type CliIo = {\n readonly stdout: (text: string) => void;\n readonly stderr: (text: string) => void;\n};\n\nexport type CreateCliOptions = {\n readonly invocationName?: string;\n readonly color?: boolean;\n readonly isTTY?: boolean;\n readonly columns?: number;\n readonly markdown?: RenderOptions;\n};\n\nexport function createCli(\n app: AnyApp,\n cliOptions: CreateCliOptions = {},\n): {\n run(\n argv: readonly string[],\n options?: { readonly io?: Partial<CliIo> },\n ): Promise<number>;\n} {\n return Object.freeze({\n run(argv, options = {}) {\n return runCli({\n app,\n argv,\n ...(cliOptions.invocationName\n ? { invocationName: cliOptions.invocationName }\n : {}),\n ...(cliOptions.color !== undefined ? { color: cliOptions.color } : {}),\n ...(cliOptions.isTTY !== undefined ? { isTTY: cliOptions.isTTY } : {}),\n ...(cliOptions.columns !== undefined\n ? { columns: cliOptions.columns }\n : {}),\n ...(cliOptions.markdown ? { markdown: cliOptions.markdown } : {}),\n ...(options.io ? { io: options.io } : {}),\n });\n },\n });\n}\n\nexport async function runCli(options: {\n readonly app: AnyApp;\n readonly argv: readonly string[];\n readonly invocationName?: string;\n readonly color?: boolean;\n readonly isTTY?: boolean;\n readonly columns?: number;\n readonly markdown?: RenderOptions;\n readonly io?: Partial<CliIo>;\n}): Promise<number> {\n const io: CliIo = {\n stdout: options.io?.stdout ??\n ((text) => process.stdout.write(withTrailingNewline(text))),\n stderr: options.io?.stderr ??\n ((text) => process.stderr.write(withTrailingNewline(text))),\n };\n const invocationName = options.invocationName ?? \"cap\";\n const isTTY = options.isTTY ?? Boolean(process.stdout.isTTY);\n const color = options.color ?? supportsColor(process.env, isTTY);\n const columns = options.columns ?? process.stdout.columns ?? 80;\n const style = createCliStyle(color);\n const runtime = getAppRuntime(options.app);\n let manifest;\n try {\n manifest = await runtime.manifest();\n } catch (error) {\n io.stderr(renderRuntimeError(error));\n return 1;\n }\n const catalog = collectCommands(manifest.capabilities);\n const json = options.argv.includes(\"--json\");\n const watch = options.argv.includes(\"--watch\");\n const wantsHelp = options.argv.includes(\"--help\") ||\n options.argv.includes(\"-h\");\n const argv = options.argv.filter((argument) =>\n ![\"--json\", \"--watch\", \"--help\", \"-h\"].includes(argument)\n );\n\n const roots = catalog.commands.filter((command) => command.command.length === 0);\n if (roots.length > 1) {\n io.stderr(\"Multiple Capabilities map to the root CLI command\");\n return 2;\n }\n const root = roots[0];\n const runsRoot = root && !wantsHelp &&\n (json || watch || root.capability.execution === \"events\");\n if (argv.length === 0 && !runsRoot) {\n io.stdout(renderRootHelp(\n manifest,\n catalog.commands,\n catalog.groups,\n invocationName,\n style,\n ));\n return 0;\n }\n\n const command = matchCommand(argv, catalog.commands);\n const group = exactGroup(argv, catalog.groups);\n if (wantsHelp) {\n if (command) {\n io.stdout(renderCommandHelp(command, invocationName, style));\n return 0;\n }\n if (group) {\n io.stdout(renderGroupHelp(\n group,\n catalog.commands,\n invocationName,\n style,\n ));\n return 0;\n }\n io.stderr(unknownCommand(argv, catalog.commands, invocationName));\n return 2;\n }\n\n if (!command) {\n if (group) {\n io.stderr(\n `Missing command after ${group.command.join(\" \")}\\n` +\n `Run \\`${invocationName} ${group.command.join(\" \")} --help\\` to list available commands.`,\n );\n return 2;\n }\n io.stderr(unknownCommand(argv, catalog.commands, invocationName));\n return 2;\n }\n\n try {\n if (watch && command.capability.execution === \"unary\") {\n throw new CliUsageError(\n `Option --watch is only available for subscribable Capabilities`,\n );\n }\n const input = parseArguments(\n argv.slice(command.command.length),\n command,\n invocationName,\n );\n if (watch || command.capability.execution === \"events\") {\n return await runWatchedCommand({\n runtime,\n command,\n input,\n json,\n io,\n color,\n isTTY,\n columns,\n ...(options.markdown ? { markdown: options.markdown } : {}),\n });\n }\n const result = await runtime.call({\n id: command.capability.id,\n input,\n ...(!json ? { presentation: true } : {}),\n });\n io.stdout(\n json\n ? JSON.stringify(result.output, null, 2)\n : renderCliCapabilityResult(result, {\n color,\n isTTY,\n columns,\n ...(options.markdown ? { markdown: options.markdown } : {}),\n }),\n );\n return 0;\n } catch (error) {\n if (error instanceof CliUsageError) {\n io.stderr(error.message);\n return 2;\n }\n if (error instanceof TransportError) {\n io.stderr(renderRuntimeError(error));\n return 1;\n }\n io.stderr(error instanceof Error ? error.message : String(error));\n return 1;\n }\n}\n\nfunction withTrailingNewline(value: string): string {\n return value.endsWith(\"\\n\") ? value : `${value}\\n`;\n}\n\nasync function runWatchedCommand(options: {\n readonly runtime: ReturnType<typeof getAppRuntime>;\n readonly command: CliCommand;\n readonly input: Record<string, unknown>;\n readonly json: boolean;\n readonly io: CliIo;\n readonly color: boolean;\n readonly isTTY: boolean;\n readonly columns: number;\n readonly markdown?: RenderOptions;\n}): Promise<number> {\n const controller = new AbortController();\n const abort = () => controller.abort();\n process.once(\"SIGINT\", abort);\n let stream: Awaited<ReturnType<typeof options.runtime.subscribe>> | undefined;\n\n try {\n stream = await options.runtime.subscribe({\n id: options.command.capability.id,\n input: options.input,\n ...(!options.json ? { presentation: true } : {}),\n signal: controller.signal,\n });\n let frame = 0;\n let previousFrameLines = 0;\n for await (const result of stream) {\n if (options.json) {\n options.io.stdout(`${JSON.stringify(result.output)}\\n`);\n continue;\n }\n const presentation = renderCliCapabilityResult(result, options);\n if (options.command.capability.execution === \"events\") {\n options.io.stdout(withTrailingNewline(presentation));\n continue;\n }\n options.io.stdout(formatWatchFrame(\n presentation,\n frame++,\n options.isTTY,\n previousFrameLines,\n ));\n previousFrameLines = countFrameLines(presentation);\n }\n return 0;\n } catch (error) {\n if (controller.signal.aborted || isAbortError(error)) return 0;\n throw error;\n } finally {\n process.off(\"SIGINT\", abort);\n await stream?.return?.();\n }\n}\n\nfunction formatWatchFrame(\n value: string,\n index: number,\n isTTY: boolean,\n previousFrameLines: number,\n): string {\n const frame = value.endsWith(\"\\n\") ? value : `${value}\\n`;\n if (isTTY) {\n return index === 0\n ? frame\n : `\\u001B[${previousFrameLines}A\\r\\u001B[0J${frame}`;\n }\n return index === 0 ? frame : `\\n---\\n\\n${frame}`;\n}\n\nfunction countFrameLines(value: string): number {\n const frame = value.endsWith(\"\\n\") ? value : `${value}\\n`;\n return frame.split(\"\\n\").length - 1;\n}\n\nfunction isAbortError(error: unknown): boolean {\n return error instanceof DOMException && error.name === \"AbortError\";\n}\n\nfunction parseArguments(\n argv: readonly string[],\n command: CliCommand,\n invocationName: string,\n): Record<string, unknown> {\n const capability = command.capability;\n const positional = command.meta.positional ?? [];\n const commandName = [invocationName, ...command.command].join(\" \");\n const schema = capability.input;\n const properties = schema?.properties as\n | Record<string, JsonSchema>\n | undefined;\n const input: Record<string, unknown> = {};\n let position = 0;\n\n for (let index = 0; index < argv.length; index++) {\n const token = argv[index]!;\n if (token.startsWith(\"--\")) {\n const [rawName, inline] = token.slice(2).split(\"=\", 2);\n const name = camelCase(rawName!);\n const field = properties?.[name];\n if (!field || positional.includes(name)) {\n const suggestion = nearest(\n rawName!,\n Object.keys(properties ?? {})\n .filter((candidate) => !positional.includes(candidate))\n .map(kebabCase),\n );\n throw new CliUsageError([\n `Unknown option --${rawName}`,\n ...(suggestion ? [`Did you mean \\`--${suggestion}\\`?`] : []),\n `Run \\`${commandName} --help\\` to inspect accepted input.`,\n ].join(\"\\n\"));\n }\n const boolean = field.type === \"boolean\";\n const raw = inline ?? (boolean ? \"true\" : argv[++index]);\n if (raw === undefined) {\n throw new CliUsageError(\n `Option --${rawName} requires a value\\n` +\n `Run \\`${commandName} --help\\` to inspect accepted input.`,\n );\n }\n input[name] = coerce(raw, field, `--${rawName}`, commandName);\n continue;\n }\n const name = positional[position++];\n if (!name) {\n throw new CliUsageError(\n `Unexpected argument \"${token}\"\\n` +\n `Run \\`${commandName} --help\\` to inspect accepted input.`,\n );\n }\n const field = properties?.[name];\n if (!field) {\n throw new CliUsageError(\n `CLI positional field \"${name}\" is not present in the input schema`,\n );\n }\n input[name] = coerce(token, field, `<${name}>`, commandName);\n }\n\n const required = schema?.required as readonly string[] | undefined;\n for (const name of required ?? []) {\n if (!(name in input)) {\n const label = positional.includes(name)\n ? `positional argument <${name}>`\n : `required option --${kebabCase(name)}`;\n throw new CliUsageError(\n `Missing ${label}\\n` +\n `Run \\`${commandName} --help\\` to inspect accepted input.`,\n );\n }\n }\n return input;\n}\n\nfunction coerce(\n value: string,\n schema: JsonSchema,\n label: string,\n commandName: string,\n): unknown {\n if (schema.type === \"boolean\") return value !== \"false\";\n if (schema.type === \"integer\" || schema.type === \"number\") {\n const number = Number(value);\n if (!Number.isFinite(number)) {\n throw new CliUsageError(\n `Expected a number for ${label}, received \"${value}\"\\n` +\n `Run \\`${commandName} --help\\` to inspect accepted input.`,\n );\n }\n return number;\n }\n return value;\n}\n\nclass CliUsageError extends Error {}\n\nfunction renderRuntimeError(error: unknown): string {\n return error instanceof TransportError\n ? `${error.code}: ${error.message}`\n : error instanceof Error\n ? error.message\n : String(error);\n}\n\nfunction matchCommand(\n argv: readonly string[],\n commands: readonly CliCommand[],\n): CliCommand | undefined {\n return commands\n .filter((candidate) =>\n candidate.command.every((token, index) => argv[index] === token)\n )\n .sort((left, right) => right.command.length - left.command.length)[0];\n}\n\nfunction exactGroup(\n argv: readonly string[],\n groups: readonly CliCommandGroup[],\n): CliCommandGroup | undefined {\n return groups.find((group) =>\n group.command.length === argv.length &&\n group.command.every((token, index) => argv[index] === token)\n );\n}\n\nfunction unknownCommand(\n argv: readonly string[],\n commands: readonly CliCommand[],\n invocationName: string,\n): string {\n const entered = argv.join(\" \");\n const suggestion = nearest(\n entered,\n commands.map((command) => command.command.join(\" \")),\n );\n return [\n `Unknown command: ${entered}`,\n ...(suggestion ? [`Did you mean \\`${suggestion}\\`?`] : []),\n `Run \\`${invocationName} --help\\` to list available commands.`,\n ].join(\"\\n\");\n}\n\nfunction nearest(\n value: string,\n candidates: readonly string[],\n): string | undefined {\n let match: { readonly candidate: string; readonly distance: number } | undefined;\n for (const candidate of new Set(candidates)) {\n const distance = editDistance(value, candidate);\n if (!match || distance < match.distance) {\n match = { candidate, distance };\n }\n }\n if (!match) return undefined;\n return match.distance <= Math.max(2, Math.floor(match.candidate.length / 3))\n ? match.candidate\n : undefined;\n}\n\nfunction editDistance(left: string, right: string): number {\n const previous = Array.from(\n { length: right.length + 1 },\n (_, index) => index,\n );\n for (let leftIndex = 1; leftIndex <= left.length; leftIndex++) {\n const current = [leftIndex];\n for (let rightIndex = 1; rightIndex <= right.length; rightIndex++) {\n current[rightIndex] = Math.min(\n current[rightIndex - 1]! + 1,\n previous[rightIndex]! + 1,\n previous[rightIndex - 1]! +\n (left[leftIndex - 1] === right[rightIndex - 1] ? 0 : 1),\n );\n }\n previous.splice(0, previous.length, ...current);\n }\n return previous[right.length]!;\n}\n\nfunction camelCase(value: string): string {\n return value.replace(/-([a-z])/g, (_, character: string) =>\n character.toUpperCase()\n );\n}\n\nfunction kebabCase(value: string): string {\n return value.replace(/[A-Z]/g, (character) => `-${character.toLowerCase()}`);\n}\n"],"mappings":";;;;AA+BA,SAAgB,gBACd,OACA,SAA4B,CAAC,GACV;CACnB,MAAM,WAAyB,CAAC;CAChC,MAAM,SAA4B,CAAC;CAEnC,KAAK,MAAM,QAAQ,OAAO;EACxB,IAAI,KAAK,SAAS,SAAS;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