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

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 (87) hide show
  1. package/CHANGELOG.md +214 -0
  2. package/README.md +6 -0
  3. package/dist/ai-sdk.d.mts +3 -3
  4. package/dist/ai-sdk.mjs +9 -7
  5. package/dist/ai-sdk.mjs.map +1 -1
  6. package/dist/app.d.mts +2 -2
  7. package/dist/app.mjs +2 -2
  8. package/dist/bin.mjs +4 -4
  9. package/dist/cli.d.mts +9 -1
  10. package/dist/cli.mjs +1 -1
  11. package/dist/core.d.mts +3 -3
  12. package/dist/core.mjs +1 -1
  13. package/dist/eve.d.mts +82 -5
  14. package/dist/eve.mjs +364 -23
  15. package/dist/eve.mjs.map +1 -1
  16. package/dist/http.d.mts +1 -1
  17. package/dist/http.mjs +1 -1
  18. package/dist/{index-F4ba_olD.d.mts → index-1A44jLuE.d.mts} +54 -16
  19. package/dist/{index-Dl4NK9G0.d.mts → index-CHuCLJIs.d.mts} +3 -3
  20. package/dist/{index-hdH_K5Zc.d.mts → index-D-NV4PiU.d.mts} +4 -4
  21. package/dist/{index-_qKFfWV4.d.mts → index-WiBWfyTn.d.mts} +63 -26
  22. package/dist/index.d.mts +4 -4
  23. package/dist/index.mjs +3 -3
  24. package/dist/mcp.d.mts +7 -2
  25. package/dist/mcp.mjs +1 -1
  26. package/dist/{mount-CEFAplR5.mjs → mount-BmLHp349.mjs} +16 -8
  27. package/dist/mount-BmLHp349.mjs.map +1 -0
  28. package/dist/react-query.d.mts +2 -2
  29. package/dist/react-query.mjs +1 -1
  30. package/dist/react-query.mjs.map +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-D_0PIhqq.mjs → src-3LE9S4QE.mjs} +67 -38
  36. package/dist/src-3LE9S4QE.mjs.map +1 -0
  37. package/dist/{src-D-cm2gQ6.mjs → src-B2WeUwUT.mjs} +64 -32
  38. package/dist/src-B2WeUwUT.mjs.map +1 -0
  39. package/dist/{src-BWxDO2Ua.mjs → src-C5jGDnuu.mjs} +3 -3
  40. package/dist/{src-BWxDO2Ua.mjs.map → src-C5jGDnuu.mjs.map} +1 -1
  41. package/dist/src-DePlcG_t.mjs +787 -0
  42. package/dist/src-DePlcG_t.mjs.map +1 -0
  43. package/dist/{src-rkr5j_NH.mjs → src-_6OmFRYa.mjs} +28 -10
  44. package/dist/src-_6OmFRYa.mjs.map +1 -0
  45. package/dist/{subscription-B-auXJbm.d.mts → subscription-DPdwovhw.d.mts} +2 -2
  46. package/dist/swr.d.mts +2 -2
  47. package/dist/swr.mjs +1 -1
  48. package/dist/swr.mjs.map +1 -1
  49. package/docs/CONTEXT.md +39 -20
  50. package/docs/README.md +3 -0
  51. package/docs/internal/README.md +3 -0
  52. package/docs/internal/adr/0001-capability-is-the-semantic-boundary.md +1 -1
  53. package/docs/internal/adr/0003-capability-reference-customization.md +68 -0
  54. package/docs/internal/architecture.md +31 -17
  55. package/docs/internal/capability-first-model.md +126 -17
  56. package/docs/internal/eve-recovery-validation.md +86 -0
  57. package/docs/internal/feedback/v-ray/README.md +258 -0
  58. package/docs/internal/feedback/v-ray/inference.mjs +43 -0
  59. package/docs/internal/feedback/v-ray/reproduce.mjs +36 -0
  60. package/docs/internal/implementation-friction.md +386 -1
  61. package/docs/internal/releases.md +79 -0
  62. package/docs/site/capable-orpc-and-trpc.mdx +2 -2
  63. package/docs/site/concepts/apps.mdx +7 -1
  64. package/docs/site/concepts/architecture.mdx +9 -1
  65. package/docs/site/concepts/capabilities.mdx +41 -4
  66. package/docs/site/concepts/errors.mdx +11 -1
  67. package/docs/site/concepts/presentations.mdx +20 -0
  68. package/docs/site/patterns/composition.mdx +152 -8
  69. package/docs/site/patterns/remote-apps.mdx +6 -2
  70. package/docs/site/patterns/subscriptions.mdx +79 -32
  71. package/docs/site/quickstart.mdx +1 -1
  72. package/docs/site/reference/packages-and-entry-points.mdx +50 -3
  73. package/docs/site/surfaces/cli.mdx +44 -0
  74. package/docs/site/surfaces/eve.mdx +65 -18
  75. package/docs/site/surfaces/typescript.mdx +3 -3
  76. package/package-docs.mjs +3 -0
  77. package/package.json +10 -11
  78. package/src/bin.ts +0 -0
  79. package/src/index.test.ts +2 -1
  80. package/src/index.ts +6 -1
  81. package/src/package.test.ts +9 -0
  82. package/dist/mount-CEFAplR5.mjs.map +0 -1
  83. package/dist/src-D-cm2gQ6.mjs.map +0 -1
  84. package/dist/src-D_0PIhqq.mjs.map +0 -1
  85. package/dist/src-betOfnDL.mjs +0 -481
  86. package/dist/src-betOfnDL.mjs.map +0 -1
  87. package/dist/src-rkr5j_NH.mjs.map +0 -1
@@ -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,61 @@ 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
+ 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.
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
+ uses Eve's response stream and stops at completion, input, failure, or cancellation.
154
+ The default deadline is 30 seconds (`timeoutMs`, at most five minutes); on timeout,
155
+ it returns the accepted ID with `running`. A single pending question is answered
156
+ automatically; multiple questions require `requestId`. Selection-only questions
157
+ require `optionId` instead of submitting the message as freeform text.
158
+
159
+ Run IDs are durable Eve session IDs, so subsequent CLI processes can attach
160
+ without a local mapping. The host authorizes every operation against the caller
161
+ and session. Only typed questions are answerable; approvals remain host-owned.
162
+
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
165
+ incomplete read fails rather than returning partial state. Call `dispose()` to
166
+ abort local requests; Eve execution continues until explicitly cancelled.
167
+
121
168
  </DocsPage>
@@ -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,6 @@
1
1
  {
2
2
  "name": "capable-kit",
3
- "version": "0.0.1-alpha.8",
3
+ "version": "0.1.0-alpha.10",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "cap": "dist/bin.mjs",
@@ -65,15 +65,12 @@
65
65
  "prepare-package.mjs",
66
66
  "src",
67
67
  "verify-package-exports.mjs",
68
- "README.md"
68
+ "README.md",
69
+ "CHANGELOG.md"
69
70
  ],
70
71
  "directories": {
71
72
  "doc": "./docs"
72
73
  },
73
- "scripts": {
74
- "prepack": "node prepare-package.mjs",
75
- "postpack": "node package-docs.mjs --clean"
76
- },
77
74
  "engines": {
78
75
  "node": ">=20"
79
76
  },
@@ -86,12 +83,13 @@
86
83
  "@modelcontextprotocol/server": "^2.0.0",
87
84
  "markdansi": "0.3.2",
88
85
  "nitro": "3.0.260610-beta",
89
- "superjson": "2.2.6"
86
+ "superjson": "2.2.6",
87
+ "zod": "^4.4.3"
90
88
  },
91
89
  "peerDependencies": {
92
90
  "@tanstack/react-query": ">=5.80.2 <6",
93
- "ai": "^7.0.0",
94
- "eve": ">=0.27.1",
91
+ "ai": "^7.0.82",
92
+ "eve": "0.52.3",
95
93
  "swr": ">=2.3.0 <3"
96
94
  },
97
95
  "peerDependenciesMeta": {
@@ -107,5 +105,6 @@
107
105
  "swr": {
108
106
  "optional": true
109
107
  }
110
- }
111
- }
108
+ },
109
+ "scripts": {}
110
+ }
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,15 @@ export {
32
33
  export {
33
34
  createApp,
34
35
  createRemoteApp,
35
- mergeApps,
36
+ composeApps,
37
+ customize,
38
+ type CapabilityCustomization,
39
+ type CustomizedCapability,
36
40
  selectApp,
37
41
  subscribe,
38
42
  type ApplicationSelection,
39
43
  type App,
40
44
  type AppContextProvider,
41
45
  type AppCapabilityCall,
46
+ type AppCapabilityReference,
42
47
  } 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);
@@ -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,WA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;CAChB,OAAO;EACL,SAAS;EACT,SAAS,CAAC;GACR,MAAM;GACN,MAAM,UAAU,KAAK,UAAU;IAAE;IAAS,GAAG;GAAQ,CAAC,IAAI;EAC5D,CAAC;CACH;AACF;AAEA,SAAS,cAAc,OAAuB;CAC5C,OAAO,IAAI,MAAM,MAAM,GAAG,CAAC,CAAC,OAAO,OAAO,CAAC,CAAC,KAAK,GAAG;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-D-cm2gQ6.mjs","names":["NO_ERRORS","isRecord"],"sources":["../../core/src/errors.ts","../../core/src/presentation.ts","../../core/src/subscription.ts","../../core/src/schema.ts","../../core/src/capability.ts","../../core/src/application.ts"],"sourcesContent":["import type {\n AnySchema,\n InferSchemaInput,\n InferSchemaOutput,\n} from \"./schema.ts\";\n\nexport const CAPABILITY_ERRORS_SYMBOL: unique symbol = Symbol.for(\n \"capable.capability-errors\",\n) as never;\nexport const CAPABILITY_ERROR_DEFINITIONS_SYMBOL: unique symbol = Symbol.for(\n \"capable.capability-error-definitions\",\n) as never;\n\nexport interface ErrorMetaRegistry {}\n\ntype OpenErrorMeta =\n & Partial<ErrorMetaRegistry>\n & Readonly<Record<string, unknown>>;\n\nexport type CapabilityErrorDefinition<\n TData extends AnySchema | undefined = AnySchema | undefined,\n> = {\n readonly message?: string;\n readonly status?: number;\n readonly data?: TData;\n readonly meta?: OpenErrorMeta;\n readonly [key: string]: unknown;\n};\n\nexport type CapabilityErrorContract = Readonly<\n Record<string, CapabilityErrorDefinition>\n>;\n\nexport class CapableError<\n TCode extends string = string,\n TData = unknown,\n> extends Error {\n readonly code: TCode;\n readonly status: number | undefined;\n readonly data: TData;\n\n constructor(\n code: TCode,\n options: {\n message?: string;\n status?: number;\n data?: TData;\n cause?: unknown;\n } = {},\n ) {\n super(options.message ?? code, { cause: options.cause });\n this.name = \"CapableError\";\n this.code = code;\n this.status = options.status;\n this.data = options.data as TData;\n }\n}\n\ntype ErrorDataSchema<TDefinition extends CapabilityErrorDefinition> =\n TDefinition extends { readonly data: infer TData extends AnySchema }\n ? TData\n : undefined;\n\ntype ErrorDataInput<TDefinition extends CapabilityErrorDefinition> =\n ErrorDataSchema<TDefinition> extends infer TData extends AnySchema\n ? InferSchemaInput<TData>\n : undefined;\n\ntype ErrorDataOutput<TDefinition extends CapabilityErrorDefinition> =\n ErrorDataSchema<TDefinition> extends infer TData extends AnySchema\n ? InferSchemaOutput<TData>\n : undefined;\n\ntype ErrorFactoryArgs<TDefinition extends CapabilityErrorDefinition> =\n ErrorDataSchema<TDefinition> extends AnySchema\n ? [\n data: ErrorDataInput<TDefinition>,\n options?: { readonly cause?: unknown },\n ]\n : [options?: { readonly cause?: unknown }];\n\nexport type CapabilityErrorFactory<\n TCode extends string,\n TDefinition extends CapabilityErrorDefinition,\n> = {\n (...args: ErrorFactoryArgs<TDefinition>): CapableError<\n TCode,\n ErrorDataOutput<TDefinition>\n >;\n readonly code: TCode;\n readonly definition: TDefinition;\n is(error: unknown): error is CapableError<\n TCode,\n ErrorDataOutput<TDefinition>\n >;\n};\n\nexport type DefinedErrors<\n TDefinitions extends CapabilityErrorContract,\n> = {\n readonly [TCode in keyof TDefinitions & string]: CapabilityErrorFactory<\n TCode,\n TDefinitions[TCode]\n >;\n} & {\n readonly [CAPABILITY_ERRORS_SYMBOL]: true;\n readonly [CAPABILITY_ERROR_DEFINITIONS_SYMBOL]: TDefinitions;\n};\n\nexport type AnyDefinedErrors = {\n readonly [CAPABILITY_ERRORS_SYMBOL]: true;\n readonly [CAPABILITY_ERROR_DEFINITIONS_SYMBOL]: CapabilityErrorContract;\n};\n\nexport function defineErrors<\n const TDefinitions extends CapabilityErrorContract,\n>(definitions: TDefinitions): DefinedErrors<TDefinitions> {\n const frozenDefinitions = Object.freeze({ ...definitions }) as TDefinitions;\n const result: Record<PropertyKey, unknown> = {};\n\n for (const [code, definition] of Object.entries(frozenDefinitions)) {\n const create = ((\n first?: unknown,\n second?: { readonly cause?: unknown },\n ) => {\n const hasData = definition.data !== undefined;\n const data = hasData ? first : undefined;\n const options = (hasData ? second : first) as\n | { readonly cause?: unknown }\n | undefined;\n return new CapableError(code, {\n ...(definition.message ? { message: definition.message } : {}),\n ...(typeof definition.status === \"number\"\n ? { status: definition.status }\n : {}),\n ...(hasData ? { data } : {}),\n ...(options &&\n typeof options === \"object\" &&\n \"cause\" in options\n ? { cause: options.cause }\n : {}),\n });\n }) as CapabilityErrorFactory<string, CapabilityErrorDefinition>;\n\n Object.defineProperties(create, {\n code: { value: code, enumerable: true },\n definition: { value: definition, enumerable: true },\n is: {\n value: (error: unknown) =>\n error instanceof Error &&\n \"code\" in error &&\n error.code === code,\n },\n });\n result[code] = Object.freeze(create);\n }\n\n Object.defineProperties(result, {\n [CAPABILITY_ERRORS_SYMBOL]: { value: true },\n [CAPABILITY_ERROR_DEFINITIONS_SYMBOL]: { value: frozenDefinitions },\n });\n return Object.freeze(result) as DefinedErrors<TDefinitions>;\n}\n\nexport function errorDefinitions(\n errors: AnyDefinedErrors,\n): CapabilityErrorContract {\n return errors[CAPABILITY_ERROR_DEFINITIONS_SYMBOL];\n}\n","import type { MaybePromise } from \"./projection.ts\";\n\nexport type PresentationTableCell = string | number | boolean | null;\n\nexport type MarkdownPresentationPart = {\n readonly type: \"markdown\";\n readonly markdown: string;\n};\n\nexport type TablePresentationPart = {\n readonly type: \"table\";\n readonly caption?: string;\n readonly columns: readonly string[];\n readonly rows: readonly (readonly PresentationTableCell[])[];\n};\n\nexport type ImagePresentationPart = {\n readonly type: \"image\";\n readonly base64: string;\n readonly mimeType: `image/${string}`;\n readonly alt: string;\n};\n\nexport type FilePresentationPart = {\n readonly type: \"file\";\n readonly url: string;\n readonly name: string;\n readonly mimeType?: string;\n readonly size?: number;\n readonly description?: string;\n};\n\nexport type PresentationPart =\n | MarkdownPresentationPart\n | TablePresentationPart\n | ImagePresentationPart\n | FilePresentationPart;\n\ntype PresentationNode = string | PresentationPart;\nexport type PresentationValue =\n | PresentationNode\n | readonly PresentationNode[];\n\nexport type PresentationRenderer<TOutput, TContext> = (\n output: TOutput,\n options: { readonly context: TContext },\n) => MaybePromise<PresentationValue>;\n\ntype TablePresentationOptions = Omit<TablePresentationPart, \"type\">;\ntype ImagePresentationOptions = Omit<ImagePresentationPart, \"type\">;\ntype FilePresentationOptions = Omit<FilePresentationPart, \"type\">;\n\ntype PresentationBuilders = Readonly<{\n table(options: TablePresentationOptions): TablePresentationPart;\n image(options: ImagePresentationOptions): ImagePresentationPart;\n file(options: FilePresentationOptions): FilePresentationPart;\n}>;\n\nexport const present: PresentationBuilders = Object.freeze({\n table(options) {\n return {\n type: \"table\",\n ...(options.caption !== undefined ? { caption: options.caption } : {}),\n columns: options.columns,\n rows: options.rows,\n };\n },\n image(options) {\n return {\n type: \"image\",\n base64: options.base64,\n mimeType: options.mimeType,\n alt: options.alt,\n };\n },\n file(options) {\n return {\n type: \"file\",\n url: options.url,\n name: options.name,\n ...(options.mimeType !== undefined ? { mimeType: options.mimeType } : {}),\n ...(options.size !== undefined ? { size: options.size } : {}),\n ...(options.description !== undefined\n ? { description: options.description }\n : {}),\n };\n },\n});\n\nexport function normalizePresentation(\n value: PresentationValue,\n): readonly PresentationPart[] {\n const nodes = Array.isArray(value) ? value : [value];\n return Object.freeze(nodes.map((node, index) => {\n if (typeof node === \"string\") {\n return Object.freeze({\n type: \"markdown\" as const,\n markdown: node,\n });\n }\n return normalizePresentationPart(node, index);\n }));\n}\n\nexport function renderPresentationMarkdown(\n presentation: PresentationPart | readonly PresentationPart[],\n): string {\n const parts = Array.isArray(presentation) ? presentation : [presentation];\n return parts.map(renderPresentationPartMarkdown).join(\"\\n\\n\");\n}\n\nfunction renderPresentationPartMarkdown(part: PresentationPart): string {\n if (part.type === \"markdown\") return part.markdown;\n if (part.type === \"table\") return renderTableMarkdown(part);\n if (part.type === \"image\") return `[Image: ${part.alt}]`;\n\n const metadata = [\n part.mimeType,\n part.size === undefined ? undefined : formatBytes(part.size),\n ].filter(Boolean).join(\", \");\n return [\n `[${escapeMarkdown(part.name)}](${part.url})`,\n part.description,\n metadata ? `(${metadata})` : undefined,\n ].filter(Boolean).join(\" — \");\n}\n\nfunction renderTableMarkdown(table: TablePresentationPart): string {\n const lines = [\n `| ${table.columns.map(escapeTableCell).join(\" | \")} |`,\n `| ${table.columns.map(() => \"---\").join(\" | \")} |`,\n ...table.rows.map((row) =>\n `| ${row.map((cell) => escapeTableCell(cell === null ? \"\" : String(cell))).join(\" | \")} |`\n ),\n ];\n return table.caption === undefined\n ? lines.join(\"\\n\")\n : `**${escapeMarkdown(table.caption)}**\\n\\n${lines.join(\"\\n\")}`;\n}\n\nfunction normalizePresentationPart(\n part: PresentationPart,\n index: number,\n): PresentationPart {\n if (!part || typeof part !== \"object\") {\n throw new Error(`Presentation part ${index} must be a string or object`);\n }\n if (part.type === \"markdown\") {\n assertString(part.markdown, `Presentation part ${index} markdown`);\n return Object.freeze({\n type: \"markdown\",\n markdown: part.markdown,\n });\n }\n if (part.type === \"table\") {\n if (part.caption !== undefined) {\n assertString(part.caption, `Presentation part ${index} caption`);\n }\n if (!Array.isArray(part.columns) || part.columns.length === 0) {\n throw new Error(`Presentation part ${index} table requires columns`);\n }\n part.columns.forEach((column, columnIndex) =>\n assertString(\n column,\n `Presentation part ${index} column ${columnIndex}`,\n )\n );\n if (!Array.isArray(part.rows)) {\n throw new Error(`Presentation part ${index} table rows must be an array`);\n }\n const rows = part.rows.map((row, rowIndex) => {\n if (!Array.isArray(row) || row.length !== part.columns.length) {\n throw new Error(\n `Presentation part ${index} row ${rowIndex} must have ${part.columns.length} cells`,\n );\n }\n for (const cell of row) {\n if (\n cell !== null &&\n typeof cell !== \"string\" &&\n typeof cell !== \"number\" &&\n typeof cell !== \"boolean\"\n ) {\n throw new Error(\n `Presentation part ${index} row ${rowIndex} has a non-scalar cell`,\n );\n }\n if (typeof cell === \"number\" && !Number.isFinite(cell)) {\n throw new Error(\n `Presentation part ${index} row ${rowIndex} has a non-finite number`,\n );\n }\n }\n return Object.freeze([...row]);\n });\n return Object.freeze({\n type: \"table\",\n ...(part.caption !== undefined ? { caption: part.caption } : {}),\n columns: Object.freeze([...part.columns]),\n rows: Object.freeze(rows),\n });\n }\n if (part.type === \"image\") {\n assertString(part.base64, `Presentation part ${index} image base64`);\n assertString(part.mimeType, `Presentation part ${index} image MIME type`);\n if (!part.mimeType.startsWith(\"image/\")) {\n throw new Error(\n `Presentation part ${index} image MIME type must start with \"image/\"`,\n );\n }\n assertString(part.alt, `Presentation part ${index} image alt text`);\n return Object.freeze({\n type: \"image\",\n base64: part.base64,\n mimeType: part.mimeType,\n alt: part.alt,\n });\n }\n if (part.type === \"file\") {\n assertString(part.url, `Presentation part ${index} file URL`);\n assertString(part.name, `Presentation part ${index} file name`);\n if (part.mimeType !== undefined) {\n assertString(part.mimeType, `Presentation part ${index} file MIME type`);\n }\n if (\n part.size !== undefined &&\n (!Number.isInteger(part.size) || part.size < 0)\n ) {\n throw new Error(\n `Presentation part ${index} file size must be a non-negative integer`,\n );\n }\n if (part.description !== undefined) {\n assertString(\n part.description,\n `Presentation part ${index} file description`,\n );\n }\n return Object.freeze({\n type: \"file\",\n url: part.url,\n name: part.name,\n ...(part.mimeType !== undefined ? { mimeType: part.mimeType } : {}),\n ...(part.size !== undefined ? { size: part.size } : {}),\n ...(part.description !== undefined\n ? { description: part.description }\n : {}),\n });\n }\n throw new Error(\n `Presentation part ${index} has unknown type \"${String((part as { type?: unknown }).type)}\"`,\n );\n}\n\nfunction escapeTableCell(value: string): string {\n return value.replace(/\\|/g, \"\\\\|\").replace(/\\r?\\n/g, \" \");\n}\n\nfunction escapeMarkdown(value: string): string {\n return value.replace(/([\\\\`*_[\\]<>])/g, \"\\\\$1\");\n}\n\nfunction formatBytes(value: number): string {\n if (value < 1_000) return `${value} B`;\n if (value < 1_000_000) return `${(value / 1_000).toFixed(1)} kB`;\n if (value < 1_000_000_000) {\n return `${(value / 1_000_000).toFixed(1)} MB`;\n }\n return `${(value / 1_000_000_000).toFixed(1)} GB`;\n}\n\nfunction assertString(value: unknown, label: string): asserts value is string {\n if (typeof value !== \"string\") throw new Error(`${label} must be a string`);\n}\n","import type { MaybePromise } from \"./projection.ts\";\n\nexport type WatchQueryOptions<TOutput> = {\n readonly snapshot: () => MaybePromise<TOutput>;\n readonly invalidations: () => AsyncIterable<unknown>;\n readonly signal?: AbortSignal;\n};\n\n/**\n * Turn an invalidation source into a stream of complete replacement snapshots.\n *\n * The invalidation iterator is pulled before the first snapshot is read. A\n * change racing with that read therefore causes another snapshot rather than\n * being missed.\n */\nexport async function* watchQuery<TOutput>(\n options: WatchQueryOptions<TOutput>,\n): AsyncIterableIterator<TOutput> {\n if (options.signal?.aborted) return;\n\n const iterator = options.invalidations()[Symbol.asyncIterator]();\n let pending = nextHandled(iterator);\n\n try {\n yield await options.snapshot();\n\n while (!options.signal?.aborted) {\n const result = await pending;\n if (result.done) return;\n pending = nextHandled(iterator);\n yield await options.snapshot();\n }\n } finally {\n await iterator.return?.();\n }\n}\n\nfunction nextHandled(iterator: AsyncIterator<unknown>) {\n const pending = iterator.next();\n void pending.catch(() => undefined);\n return pending;\n}\n\ntype Deferred<T> = {\n readonly promise: Promise<T>;\n resolve(value: T): void;\n reject(error: unknown): void;\n};\n\nfunction deferred<T>(): Deferred<T> {\n let resolve!: (value: T) => void;\n let reject!: (error: unknown) => void;\n const promise = new Promise<T>((onResolve, onReject) => {\n resolve = onResolve;\n reject = onReject;\n });\n return { promise, resolve, reject };\n}\n\nexport type DemandStream<T> = {\n waitForDemand(): Promise<boolean>;\n emit(value: T): void;\n complete(): void;\n fail(error: unknown): void;\n onCancel(cleanup: () => void | Promise<void>): void;\n};\n\nexport function createDemandIterator<T>(\n produce: (stream: DemandStream<T>) => Promise<void>,\n): AsyncIterableIterator<T> {\n const demands: Deferred<IteratorResult<T>>[] = [];\n const demandWaiters: Array<() => void> = [];\n const cleanups: Array<() => void | Promise<void>> = [];\n let activeDemand: Deferred<IteratorResult<T>> | undefined;\n let started = false;\n let closed = false;\n let failure: unknown;\n let hasFailure = false;\n let failureDelivered = false;\n let task: Promise<void> | undefined;\n\n const wakeProducer = () => demandWaiters.shift()?.();\n const finishPending = () => {\n for (const demand of demands.splice(0)) {\n if (hasFailure && !failureDelivered) {\n failureDelivered = true;\n demand.reject(failure);\n } else {\n demand.resolve({ done: true, value: undefined });\n }\n }\n };\n\n const stream: DemandStream<T> = {\n async waitForDemand() {\n while (!closed && demands.length === 0) {\n await new Promise<void>((resolve) => demandWaiters.push(resolve));\n }\n if (closed) return false;\n activeDemand = demands.shift();\n return Boolean(activeDemand);\n },\n emit(value) {\n const demand = activeDemand;\n activeDemand = undefined;\n demand?.resolve({ done: false, value });\n },\n complete() {\n closed = true;\n activeDemand?.resolve({ done: true, value: undefined });\n activeDemand = undefined;\n finishPending();\n wakeProducer();\n },\n fail(error) {\n failure = error;\n hasFailure = true;\n closed = true;\n const demand = activeDemand;\n activeDemand = undefined;\n if (demand) {\n failureDelivered = true;\n demand.reject(error);\n }\n finishPending();\n wakeProducer();\n },\n onCancel(cleanup) {\n cleanups.push(cleanup);\n },\n };\n\n const start = () => {\n if (started) return;\n started = true;\n task = produce(stream).then(\n () => {\n if (!closed) stream.complete();\n },\n (error) => stream.fail(error),\n );\n };\n\n return {\n [Symbol.asyncIterator]() {\n return this;\n },\n next() {\n if (hasFailure && !failureDelivered) {\n failureDelivered = true;\n return Promise.reject(failure);\n }\n if (closed) return Promise.resolve({ done: true, value: undefined });\n const demand = deferred<IteratorResult<T>>();\n demands.push(demand);\n start();\n wakeProducer();\n return demand.promise;\n },\n async return() {\n if (!closed) {\n closed = true;\n wakeProducer();\n activeDemand?.resolve({ done: true, value: undefined });\n activeDemand = undefined;\n finishPending();\n for (const cleanup of cleanups) await cleanup();\n }\n await task;\n return { done: true, value: undefined };\n },\n };\n}\n","import type {\n StandardJSONSchemaV1,\n StandardSchemaV1,\n} from \"@standard-schema/spec\";\n\nexport type Schema<TInput = unknown, TOutput = TInput> = {\n readonly \"~standard\":\n & StandardSchemaV1.Props<TInput, TOutput>\n & StandardJSONSchemaV1.Props<TInput, TOutput>;\n};\n\nexport type AnySchema = Schema<any, any>;\nexport type AnyObjectSchema = Schema<any, Record<string, unknown>>;\n\nexport type InferSchemaInput<TSchema extends AnySchema> =\n StandardSchemaV1.InferInput<TSchema>;\n\nexport type InferSchemaOutput<TSchema extends AnySchema> =\n StandardSchemaV1.InferOutput<TSchema>;\n\nexport async function parseSchema<TSchema extends AnySchema>(\n schema: TSchema,\n value: unknown,\n): Promise<InferSchemaOutput<TSchema>> {\n const result = await schema[\"~standard\"].validate(value);\n if (result.issues) {\n throw new SchemaValidationError(result.issues);\n }\n return result.value as InferSchemaOutput<TSchema>;\n}\n\nexport function schemaToJsonSchema(\n schema: AnySchema,\n direction: \"input\" | \"output\",\n options: {\n readonly allowUnrepresentable?: boolean;\n } = {},\n): Readonly<Record<string, unknown>> {\n const projected = schema[\"~standard\"].jsonSchema[direction]({\n target: \"draft-2020-12\",\n ...(options.allowUnrepresentable\n ? { libraryOptions: { unrepresentable: \"any\" } }\n : {}),\n });\n return JSON.parse(JSON.stringify(projected)) as Readonly<\n Record<string, unknown>\n >;\n}\n\nexport class SchemaValidationError extends Error {\n readonly issues: readonly StandardSchemaV1.Issue[];\n\n constructor(issues: readonly StandardSchemaV1.Issue[]) {\n super(\"Schema validation failed\");\n this.name = \"SchemaValidationError\";\n this.issues = issues;\n }\n}\n","import {\n defineErrors,\n errorDefinitions,\n CapableError,\n type AnyDefinedErrors,\n type DefinedErrors,\n type CapabilityErrorContract,\n} from \"./errors.ts\";\nimport {\n parseSchema,\n SchemaValidationError,\n type AnySchema,\n type AnyObjectSchema,\n type InferSchemaInput,\n type InferSchemaOutput,\n} from \"./schema.ts\";\nimport type { MaybePromise } from \"./projection.ts\";\nimport type { PresentationRenderer } from \"./presentation.ts\";\nimport { createDemandIterator } from \"./subscription.ts\";\nimport type { LocatedCapability } from \"./application.ts\";\n\nexport const CAPABILITY_SYMBOL: unique symbol = Symbol.for(\n \"capable.capability\",\n) as never;\n\nexport interface CapabilityMetaRegistry {}\ntype OpenMeta<TRegistry> = Partial<TRegistry> & Readonly<Record<string, unknown>>;\n\nexport type CapabilityEffect = \"read\" | \"write\" | \"destructive\";\n\ntype EmptyInput = Record<never, never>;\ntype DefinedNoErrors = DefinedErrors<{}>;\nconst NO_ERRORS = defineErrors({});\n\ntype ParsedInput<TInput extends AnyObjectSchema | undefined> =\n TInput extends AnySchema ? InferSchemaOutput<TInput> : EmptyInput;\n\ntype HandlerInput<TInput extends AnyObjectSchema | undefined> =\n TInput extends AnySchema ? InferSchemaInput<TInput> : EmptyInput;\n\nexport type CapabilityHandlerArgs<TContext, TInput> = {\n readonly input: TInput;\n readonly context: TContext;\n readonly signal?: AbortSignal;\n};\n\nexport type CapabilitySubscriberArgs<TContext, TInput> = {\n readonly input: TInput;\n readonly context: TContext;\n readonly signal: AbortSignal;\n};\n\nexport type CapabilitySubscriber<TContext, TInput, TOutput> = (\n args: CapabilitySubscriberArgs<TContext, TInput>,\n) => AsyncIterable<TOutput>;\n\nexport type CapabilityMiddlewareArgs<TContext, TInput = unknown> = {\n readonly input: TInput;\n readonly context: TContext;\n readonly signal?: AbortSignal;\n next(): Promise<unknown>;\n};\n\nexport type CapabilityMiddleware<TContext, TInput = unknown> = (\n args: CapabilityMiddlewareArgs<TContext, TInput>,\n) => MaybePromise<unknown>;\n\ntype AnyHandler = (...args: any[]) => any;\n\nexport type CapabilityDefinition<\n TContext = unknown,\n TInput extends AnyObjectSchema | undefined = AnyObjectSchema | undefined,\n TOutput = unknown,\n TErrors extends AnyDefinedErrors = AnyDefinedErrors,\n TMeta extends OpenMeta<CapabilityMetaRegistry> = OpenMeta<CapabilityMetaRegistry>,\n TSubscribable extends boolean = boolean,\n> = {\n readonly [CAPABILITY_SYMBOL]: true;\n readonly id: string;\n readonly title?: string;\n readonly description?: string;\n readonly deprecated: boolean;\n readonly effect?: CapabilityEffect;\n readonly input?: TInput;\n readonly output?: AnySchema;\n readonly errors: TErrors;\n readonly middleware: readonly CapabilityMiddleware<TContext, ParsedInput<TInput>>[];\n readonly meta: TMeta;\n readonly handler: (\n args: CapabilityHandlerArgs<TContext, ParsedInput<TInput>>,\n ) => MaybePromise<TOutput>;\n readonly subscribe?: CapabilitySubscriber<\n TContext,\n ParsedInput<TInput>,\n any\n >;\n readonly toPresentation?: PresentationRenderer<TOutput, TContext>;\n readonly \"~capable/context\"?: (context: TContext) => TContext;\n readonly \"~capable/input\"?: TInput;\n readonly \"~capable/output\"?: TOutput;\n readonly \"~capable/subscribable\"?: TSubscribable;\n};\n\nexport type AnyCapability = CapabilityDefinition<\n any,\n any,\n any,\n any,\n any,\n any\n>;\n\nexport type CapabilityInput<TCapability extends AnyCapability> =\n TCapability extends CapabilityDefinition<any, infer TInput, any, any, any>\n ? TInput extends AnyObjectSchema\n ? InferSchemaInput<TInput>\n : EmptyInput\n : never;\n\nexport type CapabilityOutput<TCapability extends AnyCapability> =\n TCapability extends CapabilityDefinition<any, any, infer TOutput, any, any>\n ? TOutput\n : never;\n\nexport type CapabilityContext<TCapability extends AnyCapability> =\n TCapability extends CapabilityDefinition<infer TContext, any, any, any, any>\n ? TContext\n : never;\n\nexport type SubscribableCapability = CapabilityDefinition<\n any,\n any,\n any,\n any,\n any,\n true\n>;\n\nexport type ExecuteCapabilityOptions<TCapability extends AnyCapability> =\n TCapability extends CapabilityDefinition<\n infer TContext,\n infer TInput,\n any,\n any,\n any\n >\n ? (TInput extends AnyObjectSchema\n ? { readonly input: InferSchemaInput<TInput> }\n : { readonly input?: EmptyInput }) &\n ([TContext] extends [undefined]\n ? { readonly context?: undefined }\n : { readonly context: TContext }) & {\n readonly signal?: AbortSignal;\n }\n : never;\n\ntype CapabilityBaseConfig<\n TContext,\n TInput extends AnyObjectSchema | undefined,\n TErrors extends AnyDefinedErrors,\n TMeta extends OpenMeta<CapabilityMetaRegistry>,\n> = {\n readonly id: string;\n readonly title?: string;\n readonly description?: string;\n readonly deprecated?: boolean;\n readonly effect?: CapabilityEffect;\n readonly input?: TInput;\n readonly errors?: TErrors;\n readonly middleware?: readonly CapabilityMiddleware<\n TContext,\n ParsedInput<TInput>\n >[];\n readonly meta?: TMeta;\n};\n\ntype ExplicitOutputCapabilityConfig<\n TContext,\n TInput extends AnyObjectSchema | undefined,\n TOutput extends AnySchema,\n TErrors extends AnyDefinedErrors,\n TMeta extends OpenMeta<CapabilityMetaRegistry>,\n> = CapabilityBaseConfig<TContext, TInput, TErrors, TMeta> & {\n readonly output: TOutput;\n readonly handler: (\n args: CapabilityHandlerArgs<TContext, ParsedInput<TInput>>,\n ) => MaybePromise<InferSchemaInput<TOutput>>;\n readonly toPresentation?: PresentationRenderer<InferSchemaOutput<TOutput>, TContext>;\n readonly subscribe?: CapabilitySubscriber<\n TContext,\n ParsedInput<TInput>,\n InferSchemaInput<TOutput>\n >;\n};\n\ntype InferredOutputCapabilityConfig<\n TContext,\n TInput extends AnyObjectSchema | undefined,\n THandler extends (\n args: CapabilityHandlerArgs<TContext, ParsedInput<TInput>>,\n ) => unknown,\n TErrors extends AnyDefinedErrors,\n TMeta extends OpenMeta<CapabilityMetaRegistry>,\n> = CapabilityBaseConfig<TContext, TInput, TErrors, TMeta> & {\n readonly output?: never;\n readonly handler: THandler;\n readonly toPresentation?: PresentationRenderer<Awaited<ReturnType<THandler>>, TContext>;\n readonly subscribe?: CapabilitySubscriber<\n TContext,\n ParsedInput<TInput>,\n Awaited<ReturnType<THandler>>\n >;\n};\n\nexport type CapabilityFactory<TContext> = {\n <\n TInput extends AnyObjectSchema | undefined = undefined,\n TOutput extends AnySchema = AnySchema,\n const TErrors extends AnyDefinedErrors = DefinedNoErrors,\n const TMeta extends OpenMeta<CapabilityMetaRegistry> = {},\n >(\n config: ExplicitOutputCapabilityConfig<\n TContext,\n TInput,\n TOutput,\n TErrors,\n TMeta\n > & {\n readonly subscribe: CapabilitySubscriber<\n TContext,\n ParsedInput<TInput>,\n InferSchemaInput<TOutput>\n >;\n },\n ): CapabilityDefinition<\n TContext,\n TInput,\n InferSchemaOutput<TOutput>,\n TErrors,\n TMeta,\n true\n >;\n <\n TInput extends AnyObjectSchema | undefined = undefined,\n TOutput extends AnySchema = AnySchema,\n const TErrors extends AnyDefinedErrors = DefinedNoErrors,\n const TMeta extends OpenMeta<CapabilityMetaRegistry> = {},\n >(\n config: ExplicitOutputCapabilityConfig<\n TContext,\n TInput,\n TOutput,\n TErrors,\n TMeta\n > & { readonly subscribe?: never },\n ): CapabilityDefinition<\n TContext,\n TInput,\n InferSchemaOutput<TOutput>,\n TErrors,\n TMeta,\n false\n >;\n <\n TInput extends AnyObjectSchema | undefined = undefined,\n const THandler extends (\n args: CapabilityHandlerArgs<TContext, ParsedInput<TInput>>,\n ) => unknown = (\n args: CapabilityHandlerArgs<TContext, ParsedInput<TInput>>,\n ) => unknown,\n const TErrors extends AnyDefinedErrors = DefinedNoErrors,\n const TMeta extends OpenMeta<CapabilityMetaRegistry> = {},\n >(\n config: InferredOutputCapabilityConfig<\n TContext,\n TInput,\n THandler,\n TErrors,\n TMeta\n > & {\n readonly subscribe: CapabilitySubscriber<\n TContext,\n ParsedInput<TInput>,\n Awaited<ReturnType<THandler>>\n >;\n },\n ): CapabilityDefinition<\n TContext,\n TInput,\n Awaited<ReturnType<THandler>>,\n TErrors,\n TMeta,\n true\n >;\n <\n TInput extends AnyObjectSchema | undefined = undefined,\n const THandler extends (\n args: CapabilityHandlerArgs<TContext, ParsedInput<TInput>>,\n ) => unknown = (\n args: CapabilityHandlerArgs<TContext, ParsedInput<TInput>>,\n ) => unknown,\n const TErrors extends AnyDefinedErrors = DefinedNoErrors,\n const TMeta extends OpenMeta<CapabilityMetaRegistry> = {},\n >(\n config: InferredOutputCapabilityConfig<\n TContext,\n TInput,\n THandler,\n TErrors,\n TMeta\n > & { readonly subscribe?: never },\n ): CapabilityDefinition<\n TContext,\n TInput,\n Awaited<ReturnType<THandler>>,\n TErrors,\n TMeta,\n false\n >;\n};\n\ntype CapabilityFunction = CapabilityFactory<undefined> & {\n <TContext>(): CapabilityFactory<TContext>;\n withContext<TContext>(): CapabilityFactory<TContext>;\n};\n\nfunction capabilityWithContext<TContext>(): CapabilityFactory<TContext> {\n return createCapability as CapabilityFactory<TContext>;\n}\n\nexport const capability = Object.assign(\n function capability(\n config?:\n | ExplicitOutputCapabilityConfig<any, any, any, any, any>\n | InferredOutputCapabilityConfig<any, any, AnyHandler, any, any>,\n ): AnyCapability | CapabilityFactory<any> {\n return config === undefined\n ? createCapability as CapabilityFactory<any>\n : createCapability(config);\n },\n { withContext: capabilityWithContext },\n) as CapabilityFunction;\n\nfunction createCapability(\n config:\n | ExplicitOutputCapabilityConfig<any, any, any, any, any>\n | InferredOutputCapabilityConfig<any, any, AnyHandler, any, any>,\n): AnyCapability {\n if (!config.id) throw new Error(\"Capability id must not be empty\");\n if (config.subscribe && config.effect !== \"read\") {\n throw new Error(\n `Capability \"${config.id}\" must declare effect \"read\" to subscribe`,\n );\n }\n if (typeof config.handler !== \"function\") {\n throw new Error(`Capability \"${config.id}\" requires a handler`);\n }\n\n return Object.freeze({\n [CAPABILITY_SYMBOL]: true as const,\n id: config.id,\n ...(config.title ? { title: config.title } : {}),\n ...(config.description ? { description: config.description } : {}),\n deprecated: config.deprecated === true,\n ...(config.effect ? { effect: config.effect } : {}),\n ...(config.input ? { input: config.input } : {}),\n ...(config.output ? { output: config.output } : {}),\n errors: config.errors ?? NO_ERRORS,\n middleware: Object.freeze([...(config.middleware ?? [])]),\n meta: Object.freeze({ ...(config.meta ?? {}) }),\n handler: config.handler,\n ...(config.subscribe ? { subscribe: config.subscribe } : {}),\n ...(config.toPresentation\n ? { toPresentation: config.toPresentation }\n : {}),\n });\n}\n\nexport async function executeCapability<\n const TCapability extends AnyCapability,\n>(\n capability: TCapability,\n options: ExecuteCapabilityOptions<TCapability>,\n): Promise<CapabilityOutput<TCapability>> {\n const located: LocatedCapability = Object.freeze({\n path: Object.freeze([]),\n groups: Object.freeze([]),\n groupPaths: Object.freeze([]),\n capability,\n errors: Object.freeze({ ...errorDefinitions(capability.errors) }),\n middleware: capability.middleware,\n });\n return executeLocatedCapability(\n located,\n options.input ?? {},\n {\n context: options.context,\n ...(options.signal ? { signal: options.signal } : {}),\n },\n ) as Promise<CapabilityOutput<TCapability>>;\n}\n\nexport async function executeLocatedCapability(\n located: LocatedCapability,\n input: unknown,\n options: { readonly context: unknown; readonly signal?: AbortSignal },\n): Promise<unknown> {\n const parsedInput = await parseCapabilityInput(located.capability, input);\n let rawOutput: unknown;\n try {\n rawOutput = await runCapabilityMiddleware(\n located.middleware,\n {\n input: parsedInput,\n context: options.context,\n ...(options.signal ? { signal: options.signal } : {}),\n },\n () => located.capability.handler({\n input: parsedInput,\n context: options.context,\n ...(options.signal ? { signal: options.signal } : {}),\n }),\n );\n } catch (error) {\n throw await normalizeCapabilityError(located, error);\n }\n\n return validateCapabilityOutput(located.capability, rawOutput);\n}\n\nexport type SubscribeCapabilityOptions<\n TCapability extends SubscribableCapability,\n> = ExecuteCapabilityOptions<TCapability>;\n\nexport function subscribeCapability<\n const TCapability extends SubscribableCapability,\n>(\n capability: TCapability,\n options: SubscribeCapabilityOptions<TCapability>,\n): AsyncIterableIterator<CapabilityOutput<TCapability>> {\n const located: LocatedCapability = Object.freeze({\n path: Object.freeze([]),\n groups: Object.freeze([]),\n groupPaths: Object.freeze([]),\n capability,\n errors: Object.freeze({ ...errorDefinitions(capability.errors) }),\n middleware: capability.middleware,\n });\n return subscribeLocatedCapability(\n located,\n options.input ?? {},\n {\n context: options.context,\n ...(options.signal ? { signal: options.signal } : {}),\n },\n ) as AsyncIterableIterator<CapabilityOutput<TCapability>>;\n}\n\nexport function subscribeLocatedCapability(\n located: LocatedCapability,\n input: unknown,\n options: { readonly context: unknown; readonly signal?: AbortSignal },\n): AsyncIterableIterator<unknown> {\n const subscriber = located.capability.subscribe;\n if (!subscriber) {\n throw new Error(`Capability \"${located.capability.id}\" is not subscribable`);\n }\n\n return createDemandIterator(async (stream) => {\n let cleanupSource = async (_abort: boolean) => {};\n let parsedInput: Record<string, unknown>;\n try {\n parsedInput = await parseCapabilityInput(located.capability, input);\n } catch (error) {\n stream.fail(error);\n return;\n }\n\n try {\n const controller = new AbortController();\n const signal = options.signal\n ? AbortSignal.any([controller.signal, options.signal])\n : controller.signal;\n let iterator: AsyncIterator<unknown> | undefined;\n let cleaned = false;\n cleanupSource = async (abort: boolean) => {\n if (cleaned) return;\n cleaned = true;\n if (abort) controller.abort();\n await iterator?.return?.();\n };\n stream.onCancel(() => cleanupSource(true));\n\n let emitted = false;\n await runCapabilityMiddleware(\n located.middleware,\n {\n input: parsedInput,\n context: options.context,\n signal,\n },\n async () => {\n const iterable = subscriber({\n input: parsedInput,\n context: options.context,\n signal,\n });\n if (\n !iterable ||\n typeof iterable !== \"object\" ||\n !(Symbol.asyncIterator in iterable)\n ) {\n throw new CapableError(\"INTERNAL_SERVER_ERROR\", {\n message: `Capability \"${located.capability.id}\" subscribe must return an AsyncIterable`,\n });\n }\n const sourceIterator = iterable[Symbol.asyncIterator]();\n iterator = sourceIterator;\n\n while (await stream.waitForDemand()) {\n const result = await sourceIterator.next();\n if (result.done) {\n if (!emitted) throw emptySubscriptionError(located.capability);\n return;\n }\n emitted = true;\n stream.emit(\n await validateCapabilityOutput(\n located.capability,\n result.value,\n ),\n );\n }\n },\n );\n if (!emitted) throw emptySubscriptionError(located.capability);\n await cleanupSource(false);\n stream.complete();\n } catch (error) {\n await cleanupSource(false);\n stream.fail(await normalizeCapabilityError(located, error));\n }\n });\n}\n\nfunction emptySubscriptionError(capability: AnyCapability): CapableError {\n return new CapableError(\"INTERNAL_SERVER_ERROR\", {\n message: `Capability \"${capability.id}\" subscription completed before yielding a value`,\n });\n}\n\nasync function validateCapabilityOutput(\n capability: AnyCapability,\n rawOutput: unknown,\n): Promise<unknown> {\n if (!capability.output) return rawOutput;\n try {\n return await parseSchema(capability.output, rawOutput);\n } catch (error) {\n if (!(error instanceof SchemaValidationError)) throw error;\n throw new CapableError(\"INTERNAL_SERVER_ERROR\", {\n message: `Capability \"${capability.id}\" output validation failed`,\n data: { issues: error.issues },\n cause: error,\n });\n }\n}\n\nasync function parseCapabilityInput(\n capability: AnyCapability,\n input: unknown,\n): Promise<Record<string, unknown>> {\n if (!capability.input) {\n if (input === undefined) return {};\n if (isRecord(input) && Object.keys(input).length === 0) return {};\n throw new CapableError(\"BAD_REQUEST\", {\n status: 400,\n message: `Capability \"${capability.id}\" does not accept input`,\n });\n }\n try {\n const parsed = await parseSchema(capability.input, input);\n if (!isRecord(parsed)) {\n throw new CapableError(\"INTERNAL_SERVER_ERROR\", {\n message: `Capability \"${capability.id}\" input schema must produce an object`,\n });\n }\n return parsed;\n } catch (error) {\n if (error instanceof CapableError) throw error;\n if (!(error instanceof SchemaValidationError)) throw error;\n throw new CapableError(\"BAD_REQUEST\", {\n status: 400,\n message: `Invalid input for Capability \"${capability.id}\"`,\n data: { issues: error.issues },\n cause: error,\n });\n }\n}\n\nasync function runCapabilityMiddleware(\n middleware: readonly CapabilityMiddleware<any>[],\n args: {\n readonly input: unknown;\n readonly context: unknown;\n readonly signal?: AbortSignal;\n },\n handler: () => MaybePromise<unknown>,\n): Promise<unknown> {\n async function dispatch(index: number): Promise<unknown> {\n const current = middleware[index];\n if (!current) return handler();\n let called = false;\n return current({\n ...args,\n next: async () => {\n if (called) {\n throw new CapableError(\"INTERNAL_SERVER_ERROR\", {\n message: \"Capability middleware called next() more than once\",\n });\n }\n called = true;\n return dispatch(index + 1);\n },\n });\n }\n return dispatch(0);\n}\n\nasync function normalizeCapabilityError(\n located: LocatedCapability,\n error: unknown,\n): Promise<unknown> {\n if (!(error instanceof CapableError)) {\n return new CapableError(\"INTERNAL_SERVER_ERROR\", { cause: error });\n }\n const contract = located.errors[error.code];\n if (!contract) {\n return new CapableError(\"INTERNAL_SERVER_ERROR\", { cause: error });\n }\n\n let data = error.data;\n if (contract.data) {\n try {\n data = await parseSchema(contract.data, error.data);\n } catch (cause) {\n throw new CapableError(\"INTERNAL_SERVER_ERROR\", {\n message: `Invalid error data for ${error.code}`,\n cause,\n });\n }\n }\n return new CapableError(error.code, {\n ...(typeof contract.status === \"number\" ? { status: contract.status } : {}),\n message: contract.message ?? error.code,\n data,\n cause: error,\n });\n}\n\nexport function isCapability(value: unknown): value is AnyCapability {\n return Boolean(\n value &&\n typeof value === \"object\" &&\n (value as Partial<AnyCapability>)[CAPABILITY_SYMBOL] === true,\n );\n}\n\nfunction isRecord(value: unknown): value is Record<string, any> {\n return Boolean(value && typeof value === \"object\" && !Array.isArray(value));\n}\n","import {\n defineErrors,\n errorDefinitions,\n type AnyDefinedErrors,\n type DefinedErrors,\n type CapabilityErrorContract,\n} from \"./errors.ts\";\nimport {\n isCapability,\n type AnyCapability,\n type CapabilityDefinition,\n type CapabilityMiddleware,\n} from \"./capability.ts\";\n\nexport const CAPABILITY_GROUP_SYMBOL: unique symbol = Symbol.for(\n \"capable.capability-group\",\n) as never;\nexport const APPLICATION_SYMBOL: unique symbol = Symbol.for(\n \"capable.application\",\n) as never;\n\nexport interface GroupMetaRegistry {}\ntype OpenMeta<TRegistry> = Partial<TRegistry> & Readonly<Record<string, unknown>>;\ntype DefinedNoErrors = DefinedErrors<{}>;\nconst NO_ERRORS = defineErrors({});\n\nexport interface CapabilityTree {\n readonly [key: string]:\n | AnyCapability\n | CapabilityTree\n | AnyCapabilityGroup;\n}\n\nexport type CapabilityGroupDefinition<\n TCapabilities extends CapabilityTree = CapabilityTree,\n TErrors extends AnyDefinedErrors = AnyDefinedErrors,\n TMeta extends OpenMeta<GroupMetaRegistry> = OpenMeta<GroupMetaRegistry>,\n> = {\n readonly [CAPABILITY_GROUP_SYMBOL]: true;\n readonly title?: string;\n readonly description?: string;\n readonly errors: TErrors;\n readonly middleware: readonly CapabilityMiddleware<any>[];\n readonly meta: TMeta;\n readonly capabilities: TCapabilities;\n};\n\nexport type AnyCapabilityGroup = {\n readonly [CAPABILITY_GROUP_SYMBOL]: true;\n readonly title?: string;\n readonly description?: string;\n readonly errors: AnyDefinedErrors;\n readonly middleware: readonly CapabilityMiddleware<any>[];\n readonly meta: OpenMeta<GroupMetaRegistry>;\n readonly capabilities: CapabilityTree;\n};\n\nexport function group<\n const TCapabilities extends CapabilityTree,\n const TErrors extends AnyDefinedErrors = DefinedNoErrors,\n const TMeta extends OpenMeta<GroupMetaRegistry> = {},\n>(config: {\n readonly title?: string;\n readonly description?: string;\n readonly errors?: TErrors;\n readonly middleware?: readonly CapabilityMiddleware<\n CapabilityTreeContext<TCapabilities>\n >[];\n readonly meta?: TMeta;\n readonly capabilities: TCapabilities;\n}): CapabilityGroupDefinition<TCapabilities, TErrors, TMeta> {\n assertCapabilityTree(config.capabilities, \"group.capabilities\");\n return Object.freeze({\n [CAPABILITY_GROUP_SYMBOL]: true as const,\n ...(config.title ? { title: config.title } : {}),\n ...(config.description ? { description: config.description } : {}),\n errors: (config.errors ?? NO_ERRORS) as TErrors,\n middleware: Object.freeze([...(config.middleware ?? [])]),\n meta: Object.freeze({ ...(config.meta ?? {}) }) as TMeta,\n capabilities: config.capabilities,\n });\n}\n\nexport type LocatedCapability = {\n readonly path: readonly string[];\n readonly groups: readonly AnyCapabilityGroup[];\n readonly groupPaths: readonly (readonly string[])[];\n readonly capability: AnyCapability;\n readonly errors: CapabilityErrorContract;\n readonly middleware: readonly CapabilityMiddleware<any>[];\n};\n\nexport type AppDefinition<\n TCapabilities extends CapabilityTree = CapabilityTree,\n TContext = unknown,\n> = {\n readonly [APPLICATION_SYMBOL]: true;\n readonly name: string;\n readonly version: string;\n readonly description?: string;\n readonly capabilities: TCapabilities;\n readonly locatedCapabilities: readonly LocatedCapability[];\n readonly \"~capable/context\"?: TContext;\n};\n\ntype CapabilityTreeContext<TTree> =\n TTree extends CapabilityDefinition<infer TContext, any, any, any, any>\n ? TContext\n : TTree extends CapabilityGroupDefinition<infer TCapabilities, any, any>\n ? CapabilityTreeContext<TCapabilities>\n : TTree extends Readonly<Record<string, unknown>>\n ? CapabilityTreeContext<TTree[keyof TTree]>\n : never;\n\ntype UnionToIntersection<TValue> =\n (TValue extends unknown ? (value: TValue) => void : never) extends\n (value: infer TIntersection) => void ? TIntersection : never;\n\nexport type AppContext<\n TDefinition extends AppDefinition<any, any>,\n> = TDefinition extends AppDefinition<any, infer TContext>\n ? TContext\n : never;\n\nexport function defineApp<\n const TCapabilities extends CapabilityTree,\n>(config: {\n readonly name?: string;\n readonly version?: string;\n readonly description?: string;\n readonly capabilities: TCapabilities;\n}): AppDefinition<\n TCapabilities,\n UnionToIntersection<CapabilityTreeContext<TCapabilities>>\n> {\n assertCapabilityTree(config.capabilities, \"application.capabilities\");\n const located = locateCapabilities(config.capabilities);\n assertUniqueCapabilities(located);\n\n return Object.freeze({\n [APPLICATION_SYMBOL]: true as const,\n name: config.name ?? \"Capable application\",\n version: config.version ?? \"0.0.0\",\n ...(config.description ? { description: config.description } : {}),\n capabilities: config.capabilities,\n locatedCapabilities: Object.freeze(located),\n });\n}\n\nfunction locateCapabilities(\n tree: CapabilityTree,\n path: readonly string[] = [],\n groups: readonly AnyCapabilityGroup[] = [],\n groupPaths: readonly (readonly string[])[] = [],\n inheritedErrors: CapabilityErrorContract = {},\n inheritedMiddleware: readonly CapabilityMiddleware<any>[] = [],\n): LocatedCapability[] {\n const located: LocatedCapability[] = [];\n for (const [key, value] of Object.entries(tree)) {\n const nextPath = [...path, key];\n if (isCapability(value)) {\n const capabilityErrors = errorDefinitions(value.errors);\n assertAdditionalErrors(\n inheritedErrors,\n capabilityErrors,\n `Capability \"${value.id}\"`,\n );\n located.push(Object.freeze({\n path: Object.freeze(nextPath),\n groups: Object.freeze([...groups]),\n groupPaths: Object.freeze([...groupPaths]),\n capability: value,\n errors: Object.freeze({ ...inheritedErrors, ...capabilityErrors }),\n middleware: Object.freeze([\n ...inheritedMiddleware,\n ...value.middleware,\n ]),\n }));\n continue;\n }\n if (isCapabilityGroup(value)) {\n const groupErrors = errorDefinitions(value.errors);\n assertAdditionalErrors(\n inheritedErrors,\n groupErrors,\n `Group at \"${nextPath.join(\".\")}\"`,\n );\n located.push(...locateCapabilities(\n value.capabilities,\n nextPath,\n [...groups, value],\n [...groupPaths, nextPath],\n { ...inheritedErrors, ...groupErrors },\n [\n ...inheritedMiddleware,\n ...(value.middleware as readonly CapabilityMiddleware<any>[]),\n ],\n ));\n continue;\n }\n located.push(...locateCapabilities(\n value,\n nextPath,\n groups,\n groupPaths,\n inheritedErrors,\n inheritedMiddleware,\n ));\n }\n return located;\n}\n\nfunction assertCapabilityTree(\n value: unknown,\n label: string,\n): asserts value is CapabilityTree {\n if (!isRecord(value)) {\n throw new Error(\n `${label} must be a named object tree; arrays are not supported`,\n );\n }\n for (const [key, child] of Object.entries(value)) {\n if (!key) throw new Error(`${label} has an empty key`);\n if (key === \"then\") {\n throw new Error(`${label} uses reserved key \"then\"`);\n }\n if (isCapability(child)) continue;\n if (isCapabilityGroup(child)) {\n assertCapabilityTree(child.capabilities, `${label}.${key}.capabilities`);\n continue;\n }\n assertCapabilityTree(child, `${label}.${key}`);\n }\n}\n\nfunction assertUniqueCapabilities(\n located: readonly LocatedCapability[],\n): void {\n const ids = new Map<string, string>();\n const objects = new Map<AnyCapability, string>();\n for (const entry of located) {\n const path = entry.path.join(\".\");\n const previousIdPath = ids.get(entry.capability.id);\n if (previousIdPath) {\n throw new Error(\n `Duplicate Capability id \"${entry.capability.id}\" at \"${previousIdPath}\" and \"${path}\"`,\n );\n }\n const previousObjectPath = objects.get(entry.capability);\n if (previousObjectPath) {\n throw new Error(\n `Capability \"${entry.capability.id}\" is included at both \"${previousObjectPath}\" and \"${path}\"`,\n );\n }\n ids.set(entry.capability.id, path);\n objects.set(entry.capability, path);\n }\n}\n\nfunction assertAdditionalErrors(\n inherited: CapabilityErrorContract,\n additional: CapabilityErrorContract,\n label: string,\n): void {\n const duplicate = Object.keys(additional).find((code) => code in inherited);\n if (duplicate) {\n throw new Error(`${label} redeclares inherited error ${duplicate}`);\n }\n}\n\nexport function isCapabilityGroup(\n value: unknown,\n): value is AnyCapabilityGroup {\n return Boolean(\n value &&\n typeof value === \"object\" &&\n (value as Partial<AnyCapabilityGroup>)[CAPABILITY_GROUP_SYMBOL] === true,\n );\n}\n\nfunction isRecord(value: unknown): value is Record<string, any> {\n return Boolean(value && typeof value === \"object\" && !Array.isArray(value));\n}\n"],"mappings":";AAMA,MAAa,2BAA0C,OAAO,IAC5D,2BACF;AACA,MAAa,sCAAqD,OAAO,IACvE,sCACF;AAsBA,IAAa,eAAb,cAGU,MAAM;CACd;CACA;CACA;CAEA,YACE,MACA,UAKI,CAAC,GACL;EACA,MAAM,QAAQ,WAAW,MAAM,EAAE,OAAO,QAAQ,MAAM,CAAC;EACvD,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,SAAS,QAAQ;EACtB,KAAK,OAAO,QAAQ;CACtB;AACF;AA0DA,SAAgB,aAEd,aAAwD;CACxD,MAAM,oBAAoB,OAAO,OAAO,EAAE,GAAG,YAAY,CAAC;CAC1D,MAAM,SAAuC,CAAC;CAE9C,KAAK,MAAM,CAAC,MAAM,eAAe,OAAO,QAAQ,iBAAiB,GAAG;EAClE,MAAM,WACJ,OACA,WACG;GACH,MAAM,UAAU,WAAW,SAAS,KAAA;GACpC,MAAM,OAAO,UAAU,QAAQ,KAAA;GAC/B,MAAM,UAAW,UAAU,SAAS;GAGpC,OAAO,IAAI,aAAa,MAAM;IAC5B,GAAI,WAAW,UAAU,EAAE,SAAS,WAAW,QAAQ,IAAI,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CAAC,MAAM,QAAQ,KAAK,CAAC;AAC5E"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"src-D_0PIhqq.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 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 rawMeta = node.meta.cli as CliCapabilityMeta | undefined;\n if (rawMeta === false) continue;\n const meta = rawMeta ?? {};\n commands.push({\n command: meta.command ?? [...parent, meta.name ?? node.path.at(-1)!],\n capability: node,\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 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} <command> [options]`,\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 renderSection(\"Options\", renderRows(GLOBAL_OPTIONS, style, { column }), style),\n hint(`Run \\`${invocationName} <command> --help\\` for details on a command.`, style),\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 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.subscription\n ? [{ label: \"--watch\", description: \"Stream updates until interrupted\" }]\n : []),\n ];\n const column = descriptionColumn([\n ...argumentRows,\n ...optionRows,\n ...GLOBAL_OPTIONS,\n ]);\n\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 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 ]);\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 } from \"markdansi\";\n\nexport type CliPresentationOptions = {\n readonly color: boolean;\n readonly isTTY: boolean;\n readonly columns: number;\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 })\n : markdown;\n}\n","import 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\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};\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 ...(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 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 if (argv.length === 0) {\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.subscription) {\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) {\n return await runWatchedCommand({\n runtime,\n command,\n input,\n json,\n io,\n color,\n isTTY,\n columns,\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 }),\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}): Promise<number> {\n const controller = new AbortController();\n const abort = () => controller.abort();\n process.once(\"SIGINT\", abort);\n const stream = options.runtime.subscribe({\n id: options.command.capability.id,\n input: options.input,\n ...(!options.json ? { presentation: true } : {}),\n signal: controller.signal,\n });\n\n try {\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 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":";;;;AA2BA,SAAgB,gBACd,OACA,SAA4B,CAAC,GACV;CACnB,MAAM,WAAyB,CAAC;CAChC,MAAM,SAA4B,CAAC;CAEnC,KAAK,MAAM,QAAQ,OAAO;EACxB,IAAI,KAAK,SAAS,SAAS;GACzB,MAAM,OAAQ,KAAK,KAAK,OAAO,CAAC;GAChC,MAAM,UAAU,CAAC,GAAG,QAAQ,KAAK,QAAQ,KAAK,GAAG;GAC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