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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/CHANGELOG.md +385 -0
  2. package/LICENSE +21 -0
  3. package/README.md +12 -0
  4. package/dist/ai-sdk.d.mts +3 -3
  5. package/dist/ai-sdk.mjs +9 -7
  6. package/dist/ai-sdk.mjs.map +1 -1
  7. package/dist/app.d.mts +2 -2
  8. package/dist/app.mjs +2 -2
  9. package/dist/bin.mjs +19 -15
  10. package/dist/bin.mjs.map +1 -1
  11. package/dist/cli.d.mts +9 -1
  12. package/dist/cli.mjs +1 -1
  13. package/dist/core.d.mts +3 -3
  14. package/dist/core.mjs +2 -2
  15. package/dist/eve.d.mts +92 -9
  16. package/dist/eve.mjs +606 -26
  17. package/dist/eve.mjs.map +1 -1
  18. package/dist/http.d.mts +1 -1
  19. package/dist/http.mjs +1 -1
  20. package/dist/{index-_qKFfWV4.d.mts → index-BIO_hbXJ.d.mts} +69 -26
  21. package/dist/{index-hdH_K5Zc.d.mts → index-C0tU5Y2n.d.mts} +4 -4
  22. package/dist/{index-Dl4NK9G0.d.mts → index-CwvjDizW.d.mts} +5 -3
  23. package/dist/{index-F4ba_olD.d.mts → index-F_eaksy8.d.mts} +58 -17
  24. package/dist/index.d.mts +4 -4
  25. package/dist/index.mjs +3 -3
  26. package/dist/mcp.d.mts +19 -4
  27. package/dist/mcp.mjs +2 -2
  28. package/dist/{mount-CEFAplR5.mjs → mount-pvIaehZC.mjs} +159 -107
  29. package/dist/mount-pvIaehZC.mjs.map +1 -0
  30. package/dist/react-query.d.mts +2 -2
  31. package/dist/react-query.mjs +1 -1
  32. package/dist/react-query.mjs.map +1 -1
  33. package/dist/runtime-support.d.mts +1 -1
  34. package/dist/runtime-support.mjs +3 -3
  35. package/dist/server.d.mts +1 -1
  36. package/dist/server.mjs +1 -1
  37. package/dist/{src-rkr5j_NH.mjs → src-Bk3lEhI7.mjs} +63 -25
  38. package/dist/src-Bk3lEhI7.mjs.map +1 -0
  39. package/dist/src-C2OEkZ3c.mjs +760 -0
  40. package/dist/src-C2OEkZ3c.mjs.map +1 -0
  41. package/dist/{src-BWxDO2Ua.mjs → src-DFrxQ_S6.mjs} +9 -7
  42. package/dist/src-DFrxQ_S6.mjs.map +1 -0
  43. package/dist/{src-D_0PIhqq.mjs → src-DklM1g7V.mjs} +69 -40
  44. package/dist/src-DklM1g7V.mjs.map +1 -0
  45. package/dist/{src-D-cm2gQ6.mjs → src-TCQGaWar.mjs} +119 -45
  46. package/dist/src-TCQGaWar.mjs.map +1 -0
  47. package/dist/{subscription-B-auXJbm.d.mts → subscription-fVgS4T8P.d.mts} +2 -2
  48. package/dist/swr.d.mts +2 -2
  49. package/dist/swr.mjs +1 -1
  50. package/dist/swr.mjs.map +1 -1
  51. package/docs/CONTEXT.md +44 -22
  52. package/docs/README.md +3 -0
  53. package/docs/internal/README.md +3 -0
  54. package/docs/internal/adr/0001-capability-is-the-semantic-boundary.md +1 -1
  55. package/docs/internal/adr/0003-capability-reference-customization.md +68 -0
  56. package/docs/internal/architecture.md +31 -17
  57. package/docs/internal/capability-first-model.md +126 -17
  58. package/docs/internal/eve-recovery-validation.md +87 -0
  59. package/docs/internal/feedback/v-ray/README.md +258 -0
  60. package/docs/internal/feedback/v-ray/inference.mjs +43 -0
  61. package/docs/internal/feedback/v-ray/reproduce.mjs +36 -0
  62. package/docs/internal/implementation-friction.md +445 -1
  63. package/docs/internal/releases.md +79 -0
  64. package/docs/site/capable-orpc-and-trpc.mdx +2 -2
  65. package/docs/site/concepts/apps.mdx +7 -1
  66. package/docs/site/concepts/architecture.mdx +9 -1
  67. package/docs/site/concepts/capabilities.mdx +41 -4
  68. package/docs/site/concepts/errors.mdx +26 -4
  69. package/docs/site/concepts/presentations.mdx +20 -0
  70. package/docs/site/hosting/standalone-server.mdx +2 -0
  71. package/docs/site/patterns/composition.mdx +152 -8
  72. package/docs/site/patterns/remote-apps.mdx +29 -3
  73. package/docs/site/patterns/subscriptions.mdx +79 -32
  74. package/docs/site/quickstart.mdx +3 -2
  75. package/docs/site/reference/packages-and-entry-points.mdx +52 -4
  76. package/docs/site/reference/the-cap-cli.mdx +2 -2
  77. package/docs/site/surfaces/cli.mdx +44 -0
  78. package/docs/site/surfaces/eve.mdx +67 -18
  79. package/docs/site/surfaces/mcp.mdx +84 -2
  80. package/docs/site/surfaces/typescript.mdx +3 -3
  81. package/package-docs.mjs +3 -0
  82. package/package.json +17 -12
  83. package/src/bin.ts +0 -0
  84. package/src/index.test.ts +2 -1
  85. package/src/index.ts +8 -1
  86. package/src/package.test.ts +15 -0
  87. package/dist/mount-CEFAplR5.mjs.map +0 -1
  88. package/dist/src-BWxDO2Ua.mjs.map +0 -1
  89. package/dist/src-D-cm2gQ6.mjs.map +0 -1
  90. package/dist/src-D_0PIhqq.mjs.map +0 -1
  91. package/dist/src-betOfnDL.mjs +0 -481
  92. package/dist/src-betOfnDL.mjs.map +0 -1
  93. package/dist/src-rkr5j_NH.mjs.map +0 -1
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  title: "Capabilities"
3
- description: "A capability is one typed capability: input, output, errors, middleware, and a handler."
3
+ description: "Define input, output, errors, middleware, and a handler or subscriber."
4
4
  ---
5
5
 
6
6
  import { DocsPage, docMetadata } from "../../_components/docs-page";
@@ -145,6 +145,43 @@ export const listTodos = todoCapability({
145
145
 
146
146
  Put middleware on a `group()` when several capabilities in one branch share the policy and the rest of the app does not.
147
147
 
148
+ Put middleware on `defineApp()` to apply it to every capability in that app.
149
+ All three scopes receive a readonly `capability` descriptor containing the
150
+ authored `id` and optional `effect`, plus `mode: "call" | "subscribe"`.
151
+ The ID stays the same when a capability moves to another application path.
152
+ An omitted effect remains `undefined`.
153
+
154
+ ```ts title="capable.app.ts"
155
+ const AccessErrors = defineErrors({
156
+ FORBIDDEN: { status: 403, message: "Access denied" },
157
+ });
158
+
159
+ const definition = defineApp({
160
+ capabilities: { todos },
161
+ errors: AccessErrors,
162
+ middleware: [async ({ capability, mode, context, next }) => {
163
+ if (!await canCall(context.user, capability.id)) {
164
+ throw AccessErrors.FORBIDDEN();
165
+ }
166
+ console.info({ capabilityId: capability.id, mode });
167
+ return next();
168
+ }],
169
+ });
170
+ ```
171
+
172
+ App middleware uses the Context required by the app's capabilities. It does
173
+ not add or narrow Context fields. Declare capabilities separately, then
174
+ compose them into the app so TypeScript can infer that Context before typing
175
+ the middleware. Input is parsed before middleware runs; at app and group
176
+ scope it is typed as `unknown`, because each capability can have a different
177
+ input schema. Middleware receives identity, not the handler or internal
178
+ capability definition.
179
+
180
+ The order is app middleware, outer-to-inner group middleware, capability
181
+ middleware, then the handler. Return values unwind in reverse order.
182
+ Subscriptions use the same chain for the complete subscription lifetime.
183
+ Middleware does not see input-validation failures or Context-provider failures.
184
+
148
185
  ## Describe each surface with metadata [#metadata]
149
186
 
150
187
  App paths give every surface enough information to derive routes, commands, and tool names. Add `meta` when a surface needs details that the capability itself cannot express.
@@ -187,7 +224,7 @@ Only surfaces that need a presentation ask the runtime to produce it. The CLI re
187
224
  Once these pieces are present, every caller enters the same lifecycle. A surface only translates its own transport into an input object.
188
225
 
189
226
  1. **Parse input.** The input schema runs once.
190
- 2. **Run middleware.** Group middleware runs outermost, then capability middleware, in declaration order.
227
+ 2. **Run middleware.** App middleware runs outermost, followed by outer-to-inner group middleware and capability middleware, in declaration order.
191
228
  3. **Run the handler.** It receives `{ input, context, signal }`.
192
229
  4. **Normalize errors.** Declared errors keep their contract; unexpected failures become `INTERNAL_SERVER_ERROR`.
193
230
  5. **Validate output.** The optional output schema runs before the canonical result is returned.
@@ -206,13 +243,13 @@ const todo = await executeCapability(getTodo, {
206
243
  });
207
244
  ```
208
245
 
209
- Direct execution applies the capability's own validation, middleware, and declared errors. Middleware and errors contributed by a group only exist when the capability is executed through the app tree that contains it.
246
+ Direct execution applies the capability's own validation, middleware, and declared errors. Middleware and errors contributed by an app or group only exist when the capability is executed through the app tree that contains it. A handler that requires a user must check that requirement itself if it can also be executed directly; a check in group middleware does not narrow the handler's Context type.
210
247
 
211
248
  ## Put it all together [#complete]
212
249
 
213
250
  A capability can grow into the full declaration below, but only as each concern becomes real. The handler remains the centre; every other field either strengthens its contract, shares semantic policy, or helps a surface present it.
214
251
 
215
- Subscriptions are the remaining optional execution mode. A read capability can add `subscribe` beside its handler when it needs to emit replacement snapshots; see [Subscriptions](/patterns/subscriptions).
252
+ A read capability can add `subscribe` beside its handler to emit replacement snapshots, or define only `subscribe` to emit individual events such as logs. Event-only capabilities have no unary handler. See [Subscriptions](/patterns/subscriptions).
216
253
 
217
254
  ```ts title="capabilities.ts"
218
255
  import { capability, defineErrors, md } from "capable-kit";
@@ -70,11 +70,23 @@ The same guard works against a remote app, because the error code and data cross
70
70
 
71
71
  ## Undeclared failures [#undeclared]
72
72
 
73
- Any failure that is not in the located capability's error sets becomes `INTERNAL_SERVER_ERROR`. The original value is kept as `cause` on the server and is never serialized to a caller.
73
+ Where an unexpected failure is handled depends on the boundary:
74
74
 
75
- > **Why the strictness**
75
+ - **In-process (`executeCapability()`, local `createApp()`, local CLI):** Unexpected runtime errors (such as database or third-party SDK errors) propagate unchanged with their original class, message, and stack trace. Declared `CapableError`s throw directly without extra wrapper layers. Throwing an undeclared `CapableError` still normalizes to `INTERNAL_SERVER_ERROR`.
76
+ - **External boundaries (`http()`, `protocol()`, `mcp()`):** Any unexpected or undeclared failure is masked to `INTERNAL_SERVER_ERROR` (HTTP 500) before crossing the wire so internal details never leak to external clients or agents. Pass `onError` to `createServer()` (or `createHttpHandler()` / `createProtocolHandler()`) to observe the original error in logs or error tracking.
77
+
78
+ ```ts title="server.ts"
79
+ const server = createServer(definition, {
80
+ mounts: [protocol(), http(), mcp()],
81
+ onError(error) {
82
+ logger.error(error); // receives the original unexpected error
83
+ },
84
+ });
85
+ ```
86
+
87
+ > **Why mask at the wire boundary**
76
88
  >
77
- > A surface can only present failures it can describe. Declared errors appear in OpenAPI, in CLI output, and in agent-visible schemas. Leaking arbitrary exception text would make those contracts unreliable and would risk exposing internals.
89
+ > A remote surface can only present failures it can describe. Declared errors appear in OpenAPI, in CLI output, and in agent-visible schemas. Masking unexpected exceptions at HTTP, protocol, and MCP boundaries keeps wire contracts safe without blinding in-process callers, tests, or local CLIs.
78
90
 
79
91
  ## Inherited errors [#groups]
80
92
 
@@ -88,6 +100,16 @@ const todos = group({
88
100
  });
89
101
  ```
90
102
 
91
- A group and a capability may not declare the same error code twice. The conflict is reported when the app definition is created, not at call time.
103
+ An app can contribute errors to every capability, including failures from app-wide middleware:
104
+
105
+ ```ts title="capable.app.ts"
106
+ const definition = defineApp({
107
+ capabilities: { todos },
108
+ errors: AccessErrors,
109
+ middleware: [authorizeCapability],
110
+ });
111
+ ```
112
+
113
+ An app, its nested groups, and a capability may not redeclare an inherited error code. The conflict is reported when the app definition is created, not at call time. Inherited errors appear on each affected capability in the manifest and OpenAPI. Standalone `executeCapability()` calls only use errors declared on that capability.
92
114
 
93
115
  </DocsPage>
@@ -34,6 +34,22 @@ export const getWeather = capability({
34
34
 
35
35
  Typed calls still receive `{ city, temperature }`. The string is only produced when a presentation-aware surface asks for it.
36
36
 
37
+ A typed named renderer can appear before or after `handler`:
38
+
39
+ ```ts
40
+ const presentWeather = (weather: { city: string; temperature: number }) =>
41
+ `${weather.city}: ${weather.temperature}°C`;
42
+
43
+ capability({
44
+ id: "weather.get",
45
+ toPresentation: presentWeather,
46
+ handler: () => ({ city: "Vienna", temperature: 24 }),
47
+ });
48
+ ```
49
+
50
+ When using an inline renderer with an inferred parameter, keep it after
51
+ `handler` so TypeScript can infer the result first.
52
+
37
53
  ## Compose richer output [#parts]
38
54
 
39
55
  `toPresentation` may also return one part or an ordered array of strings and parts. Import the builders from the same root entry point:
@@ -158,4 +174,8 @@ An empty array means that no presentation is available, so the surface falls bac
158
174
 
159
175
  This is a portable presentation model, not an MCP authoring API and not a UI component framework. It has no JSX, layout system, callbacks, or protocol-specific fields. New part types should be added only when several surfaces can give them a useful meaning.
160
176
 
177
+ ## Subscription presentations [#subscriptions]
178
+
179
+ `toPresentation` describes each validated subscription value using the same API as unary results. Event-only subscriptions append presentations in the CLI; replacement subscriptions redraw the current snapshot in terminals. Typed `subscribe()` consumers and CLI `--json` output use canonical values without generating presentations. An empty presentation selects canonical-output fallback, not suppression. See [Subscriptions](/patterns/subscriptions).
180
+
161
181
  </DocsPage>
@@ -56,6 +56,8 @@ cap build --preset vercel # build for another target
56
56
  | `cap preview` | Runs a `node-server` build locally |
57
57
  | `cap cli` | Invokes capabilities in the local project or against a URL |
58
58
 
59
+ `cap build` bundles with [Rolldown](https://rolldown.rs), which you install yourself so apps that never build with `cap` stay light. `cap init` adds it for you; otherwise run `pnpm add -D rolldown`. `cap dev` does not need it.
60
+
59
61
  Full options and project discovery rules are in the [CLI reference](/reference/cli).
60
62
 
61
63
  ## Growing the boundary [#boundary]
@@ -80,21 +80,26 @@ export const local = createApp(localDefinition, {
80
80
  });
81
81
  ```
82
82
 
83
- Both definitions compose named capabilities under the same `todos` path. When the apps are merged, those branches combine — `todos list` and `todos create` from the server, `todos import` from here.
83
+ Both definitions contribute named capabilities under the same `todos` path.
84
+ When the Apps are composed, those branches combine: `todos list` and
85
+ `todos create` run on the server, while `todos import` runs here.
84
86
 
85
- ## Merge them into one CLI [#merge]
87
+ ## Compose them into one CLI [#compose]
86
88
 
87
- `mergeApps()` combines the two apps into one. Calls dispatch by capability id to whichever app owns them. No proxy server, no logic moved — the import runs in this process, the creates run on the server.
89
+ `composeApps()` combines the two apps into one. App arguments contribute their
90
+ trees at the root, so the two `todos` branches become one. Calls dispatch by
91
+ capability id to whichever app owns them. No proxy server, no logic moved — the
92
+ import runs in this process, the creates run on the server.
88
93
 
89
94
  ```ts title="cli.ts"
90
- import { mergeApps } from "capable-kit";
95
+ import { composeApps } from "capable-kit";
91
96
  import { createCli } from "capable-kit/cli";
92
97
  import { remote } from "./remote";
93
98
  import { local } from "./local";
94
99
 
95
100
  // One command tree. Calls dispatch by capability id to whichever
96
101
  // app owns them — the server for list and create, this process for import.
97
- const app = mergeApps(remote, local);
102
+ const app = composeApps(remote, local);
98
103
 
99
104
  process.exit(
100
105
  await createCli(app, { invocationName: "mycli" }).run(process.argv.slice(2)),
@@ -118,15 +123,154 @@ mycli todos import ./todos.txt
118
123
  # { "imported": 2 }
119
124
  ```
120
125
 
121
- Path collisions, duplicate ids, and leaf/subtree conflicts fail when the merged manifest first resolves, not at call time. Namespaces belong in the app definitions, so the final command tree stays visible in source.
126
+ Path collisions, duplicate ids, and leaf/subtree conflicts fail when the
127
+ composed manifest first resolves, not at call time.
128
+
129
+ Object keys place an App or one of its executable subtrees beneath a
130
+ navigational branch. This is useful for external Apps that should keep a
131
+ visible namespace or contribute one existing group:
132
+
133
+ ```ts title="integrations.ts"
134
+ const app = composeApps(local, {
135
+ deepwiki,
136
+ tools: remote.admin,
137
+ integrations: {
138
+ linear,
139
+ github,
140
+ },
141
+ });
142
+
143
+ await app.deepwiki.search({ query: "routing" });
144
+ await app.integrations.linear.issue({ id: "CAP-1" });
145
+ ```
146
+
147
+ The object shape is the resulting callable tree. Namespacing changes application
148
+ paths, not Capability IDs or where execution happens. A direct call beneath one
149
+ namespace discovers only that branch; complete-manifest surfaces such as CLI
150
+ still discover and validate the entire composition.
151
+
152
+ The same App may deliberately appear at more than one path:
153
+
154
+ ```ts title="aliases.ts"
155
+ const app = composeApps({
156
+ internal: todos,
157
+ public: todos,
158
+ });
159
+ ```
160
+
161
+ Those paths are aliases backed by one terminal execution owner. Repeating the
162
+ same operation through a nested composition or another Remote App over the same
163
+ transport remains an alias. Independently bound local Apps and distinct
164
+ transports may not claim the same Capability ID, even when their manifests
165
+ happen to look identical.
122
166
 
123
167
  > **Placement stays explicit**
124
168
  >
125
- > Merging makes calling uniform, not location-transparent. Each capability still executes where it was created — behind the server's context and policy, or in this process. The CLI does not hide which is which; the source code does.
169
+ > Composition makes calling uniform, not location-transparent. Each capability
170
+ > still executes where it was created — behind the server's context and policy,
171
+ > or in this process. The CLI does not hide which is which; the source code does.
172
+
173
+ ## Curate individual capabilities [#references]
174
+
175
+ Use individual references when the local tree should choose exactly which
176
+ capabilities to expose and where they appear. Both local and remote references
177
+ retain their original execution binding:
178
+
179
+ ```ts title="radar-cli.ts"
180
+ import { composeApps, customize } from "capable-kit";
181
+ import { createCli } from "capable-kit/cli";
182
+
183
+ // desktop is a createRemoteApp<DesktopApp>(transport).
184
+ // local is a createApp(localDefinition), with its context already supplied.
185
+ const cliApp = composeApps({
186
+ stop: customize(desktop.plugins.stop, {
187
+ description: "Stop a running desktop instance.",
188
+ meta: { cli: { positional: ["instanceId"] } },
189
+ }),
190
+ debug: {
191
+ status: desktop.plugins.status,
192
+ continue: desktop.plugins.continue,
193
+ screenshot: local.screenshot,
194
+ },
195
+ });
196
+
197
+ await createCli(cliApp, { invocationName: "radar" }).run(process.argv.slice(2));
198
+ await cliApp.debug.status({ instanceId: "one" });
199
+ ```
200
+
201
+ References preserve input/output types, IDs, errors, cancellation, subscriptions,
202
+ and the backend's app/group middleware. Construction performs no discovery.
203
+ The local tree determines paths and CLI/MCP names. Authored `cli.name`,
204
+ `cli.command`, and `mcp.name` do not override an individually placed reference;
205
+ use `customize()` to set a name or command explicitly in the curated tree.
206
+ Other source metadata, such as positional arguments, remains available unless
207
+ its namespace is replaced. Source group display metadata is not copied when
208
+ moving a leaf. Place a whole App or executable Group subtree to retain its
209
+ existing internal navigation and presentation:
210
+
211
+ ```ts
212
+ const app = composeApps({
213
+ debug: desktop.plugins,
214
+ });
215
+ ```
216
+
217
+ The destination key names the placed Group, so this example creates `debug` even
218
+ if `plugins` has an authored CLI name. Its title, description, and navigation
219
+ inside the subtree remain authored. An absolute `meta.cli.command` on a child may
220
+ therefore place that command outside `debug`. Use individual references when
221
+ every CLI/MCP name should follow the destination tree.
222
+
223
+ `customize(reference, options)` accepts `title`, `description`, and `meta`.
224
+ CLI and MCP metadata are supported initially. Import the relevant surface entry
225
+ point to load its metadata types. It returns an immutable **composition entry**,
226
+ not a callable; invoke or subscribe through the resulting App. Bind local
227
+ capability definitions with `createApp()` first. Remote references do not belong
228
+ inside `defineApp()`.
229
+
230
+ Each supplied metadata namespace replaces that namespace, retaining other
231
+ namespaces. For example, overriding `meta.cli` does not replace `meta.mcp`.
232
+ Customizing an already customized entry, or a reference from a composed App,
233
+ applies outer overrides last. Title and description can be set to an empty
234
+ string to suppress authored text. Execution fields and output renderers cannot
235
+ be overridden.
236
+
237
+ The same source capability can appear at several paths with different display
238
+ settings. Repeating an identical placement is deduplicated; conflicting settings
239
+ at the same path fail. A manifest stores overrides separately from the source
240
+ contract, so nested composition, `selectApp()`, and remote discovery preserve
241
+ them. Policy callbacks still receive the original metadata. CLI, MCP, AI SDK,
242
+ and Eve honor customized descriptions; HTTP/OpenAPI continue to use authored
243
+ definitions. Older clients may ignore overrides or reject customized aliases;
244
+ use the updated client when re-exporting these Apps.
245
+
246
+ Composition cannot add middleware, errors, Context requirements, or another
247
+ execution lifecycle around a reference. Local workflow capabilities remain
248
+ normal capabilities: read stdin, save files, or orchestrate remote calls inside
249
+ their handlers. A local wrapper is a new operation with its own ID and input
250
+ schema, so forwarding a call inside a handler does not automatically forward its
251
+ remote error declarations or subscriptions.
252
+
253
+ ## Offline help [#offline-help]
254
+
255
+ Help requires runtime schemas; the TypeScript generic alone cannot supply them.
256
+ Bundle the manifest with the CLI and return it from the transport:
257
+
258
+ ```ts
259
+ const desktop = createRemoteApp<DesktopApp>({
260
+ manifest: async () => bundledManifest,
261
+ call: request => transport.call(request),
262
+ subscribe: request => transport.subscribe(request),
263
+ });
264
+ ```
265
+
266
+ Help then works without the backend. Execution still needs it. Keep the bundled
267
+ manifest aligned with the backend contract and the client types. A curated leaf
268
+ still resolves against its source App's manifest; it does not introduce a
269
+ per-capability discovery protocol.
126
270
 
127
271
  ## Narrow what a surface sees [#select]
128
272
 
129
- The same merged tree can feed more than one surface. Before handing it to an agent, narrow it with `selectApp()`. An omitted `include` means everything; `exclude` wins.
273
+ The same composed tree can feed more than one surface. Before handing it to an agent, narrow it with `selectApp()`. An omitted `include` means everything; `exclude` wins.
130
274
 
131
275
  ```ts title="agent-surface.ts"
132
276
  import { selectApp } from "capable-kit";
@@ -38,9 +38,31 @@ export async function openTodos(app: typeof local | typeof remote) {
38
38
  | --- | --- | --- |
39
39
  | Needs | The implementation, and context only if one is declared | A transport, and the definition as a type |
40
40
  | Executes | In this process | Wherever the server placed it |
41
- | Manifest | Derived from the definition | Fetched once, then cached, on first call |
41
+ | Manifest | Derived from the definition | Fetched once on first call, or supplied statically via `{ manifest }` |
42
42
  | Failure mode | Throws from the handler | Also transport errors |
43
43
 
44
+ ## Static manifests for CLIs [#static-manifest]
45
+
46
+ By default, `createRemoteApp()` fetches the manifest from `transport.manifest()` on first use and caches it in memory. For short-lived processes such as a CLI, that adds a network round trip to every run. Pass a prebuilt manifest to `createRemoteApp()` to validate it up front and skip discovery completely:
47
+
48
+ ```ts title="cli.ts"
49
+ import { createRemoteApp, type ApplicationManifest } from "capable-kit";
50
+ import { createHttpTransport } from "capable-kit/http";
51
+ import { createCli } from "capable-kit/cli";
52
+ import type { AppDefinition } from "./capable.app";
53
+ import manifest from "./generated/capable-manifest.json" with { type: "json" };
54
+
55
+ const remote = createRemoteApp<AppDefinition>(
56
+ createHttpTransport({ url: "https://todos.example.com/~capable/" }),
57
+ { manifest: manifest as ApplicationManifest },
58
+ );
59
+
60
+ // Runs help offline and sends only POST /~capable/call/<id> on invocation.
61
+ await createCli(remote).run(process.argv.slice(2));
62
+ ```
63
+
64
+ Generate the static JSON artifact at build time with `createAppManifest(definition)` from `capable-kit/app`.
65
+
44
66
  > **No code generation**
45
67
  >
46
68
  > Export a named type derived from the definition, then import that type in remote consumers. The type is erased at build time, so no server code or generated client ends up in the caller. Ship the definition's types in a package and any consumer can be typed against it.
@@ -72,6 +94,10 @@ JSON.
72
94
 
73
95
  HTTP is the transport that ships, but it is not privileged. `ApplicationTransport` is an interface with `manifest()`, `call()`, and `subscribe()`, so "remote" can mean a worker, a child process, a message queue, a browser extension port, or a stub in a test.
74
96
 
97
+ `subscribe()` resolves after the remote stream is opened, then returns its async
98
+ iterator. This keeps request and authorization failures separate from errors
99
+ emitted after streaming begins.
100
+
75
101
  ```ts title="worker-transport.ts"
76
102
  import type { ApplicationTransport } from "capable-kit/app";
77
103
 
@@ -80,7 +106,7 @@ export function createWorkerTransport(worker: Worker): ApplicationTransport {
80
106
  return {
81
107
  manifest: (options) => send(worker, { kind: "manifest" }, options),
82
108
  call: (call) => send(worker, { kind: "call", call }),
83
- subscribe: (call) => stream(worker, call),
109
+ subscribe: async (call) => stream(worker, call),
84
110
  };
85
111
  }
86
112
  ```
@@ -166,6 +192,6 @@ Calling is uniform; placement is still a decision you make in source. A remote c
166
192
  | It needs to work offline or without a server | It enforces authorization the client must not be trusted with |
167
193
  | Latency per call matters more than trust | The implementation must not ship to the caller |
168
194
 
169
- When one process needs both, merge them: [composition](/patterns/composition) combines a remote app and a local app into a single tree that dispatches each call to whichever app owns it.
195
+ When one process needs both, compose them: [composition](/patterns/composition) combines a remote app and a local app into a single tree that dispatches each call to whichever app owns it.
170
196
 
171
197
  </DocsPage>
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  title: "Subscriptions"
3
- description: "Give a read capability a second execution mode that emits complete replacements."
3
+ description: "Follow replacement snapshots or individual events with typed read capabilities."
4
4
  ---
5
5
 
6
6
  import { DocsPage, docMetadata } from "../../_components/docs-page";
@@ -9,11 +9,48 @@ export const metadata = docMetadata("/patterns/subscriptions", frontmatter);
9
9
 
10
10
  <DocsPage href="/patterns/subscriptions" frontmatter={frontmatter}>
11
11
 
12
- A `read` capability can define `subscribe` beside its `handler`. Both modes share one id, input, output, error set, middleware, placement, and metadata — so a subscription is not a second capability, it is a second way to execute the same one.
12
+ A `read` capability can subscribe to changing state or individual events. The operations you define determine its meaning:
13
13
 
14
- ## Add a subscriber [#define]
14
+ | Definition | Meaning |
15
+ | --- | --- |
16
+ | `handler` | One result |
17
+ | `handler` + `subscribe` | One result and a subscription yielding complete replacement snapshots |
18
+ | `subscribe` | Individual events, with no unary operation |
15
19
 
16
- `watchQuery()` is the common shape: read a snapshot, then re-read it whenever an invalidation source signals a change. It pulls the invalidation iterator before reading the first snapshot, so a change that races with the read produces another snapshot instead of being lost.
20
+ ## Follow logs and events [#events]
21
+
22
+ Omit `handler` when each value is another event. No dummy unary result or initial event is required, and a stream may complete without yielding anything.
23
+
24
+ ```ts title="capabilities.ts"
25
+ import { capability } from "capable-kit";
26
+ import { z } from "zod";
27
+
28
+ const runCapability = capability.withContext<RunContext>();
29
+
30
+ export const logs = runCapability({
31
+ id: "runs.logs",
32
+ effect: "read",
33
+ input: z.object({ runId: z.string() }),
34
+ output: z.object({
35
+ at: z.date(),
36
+ level: z.enum(["info", "warn", "error"]),
37
+ message: z.string(),
38
+ }),
39
+ subscribe: ({ input, context, signal }) =>
40
+ context.runs.followLogs(input.runId, { signal }),
41
+ toPresentation: entry => `**${entry.level}** ${entry.message}`,
42
+ });
43
+ ```
44
+
45
+ Without an `output` schema, the event type is inferred from the subscriber's yielded values. With a schema, each yielded value is parsed before delivery; schema transforms also apply before `toPresentation` runs.
46
+
47
+ An event stream can emit a discriminated union, such as `started`, `progress`, and `completed` events from an existing job. For a progress bar that must immediately reflect current state when opened, use replacement snapshots instead.
48
+
49
+ ## Follow replacement state [#define]
50
+
51
+ Keep `handler` alongside `subscribe` when each update describes the entire current value. Both operations share one ID, input, output, errors, middleware, and presentation.
52
+
53
+ `watchQuery()` reads a snapshot, then re-reads it whenever an invalidation source signals a change. It pulls the invalidation iterator before reading the first snapshot, so a change that races with the read produces another snapshot instead of being lost.
17
54
 
18
55
  ```ts title="capabilities.ts"
19
56
  import { capability, watchQuery } from "capable-kit";
@@ -35,53 +72,63 @@ export const listTodos = todoCapability({
35
72
  });
36
73
  ```
37
74
 
38
- An async generator works too when there is nothing to watch:
75
+ The subscriber supplies its own initial snapshot. Subscribing does not invoke the unary handler first. A replacement stream that completes without yielding a snapshot is an error.
39
76
 
40
- ```ts title="capabilities.ts"
41
- subscribe: async function* ({ signal }) {
42
- while (!signal.aborted) {
43
- yield { now: new Date().toISOString() };
44
- await wait(1000, signal);
45
- }
46
- },
47
- ```
77
+ Adding a handler to an event-only capability changes its contract to replacement state. Define separate capabilities when you need a snapshot and unrelated events.
48
78
 
49
- ## Consume it [#consume]
79
+ ## Consume a subscription [#consume]
50
80
 
51
- `subscribe()` takes a capability call from an app, which keeps app navigation free of extra method names. It works the same against local, remote, merged, and selected apps.
81
+ `subscribe()` takes a capability reference from an app, keeping app navigation free of extra method names. It works against local, remote, composed, and selected apps.
52
82
 
53
83
  ```ts title="watch.ts"
54
84
  import { subscribe } from "capable-kit";
55
85
 
56
- const updates = subscribe(app.todos.list, {}, { signal });
86
+ for await (const entry of subscribe(app.runs.logs, { runId }, { signal })) {
87
+ appendLog(entry); // another individual event
88
+ }
57
89
 
58
- for await (const todos of updates) {
59
- render(todos); // a complete, validated list every time
90
+ for await (const todos of subscribe(app.todos.list, {}, { signal })) {
91
+ render(todos); // a complete replacement list
60
92
  }
61
93
  ```
62
94
 
63
- Input is parsed once. Every emitted item is validated against the output schema, middleware encloses the whole iterator lifetime, and cancelling the signal aborts the subscriber before cleanup runs.
95
+ Event references have no unary call signature: `app.runs.logs({ runId })` is a type error, and untyped unary calls fail with `METHOD_NOT_ALLOWED`. `app.todos.list()` remains callable.
64
96
 
65
- ## Over the wire [#transport]
97
+ Input is parsed once. Every emitted item is validated against the output schema, middleware encloses the iterator lifetime, and cancellation aborts the subscriber's signal before cleanup. Sources must observe that signal to release pending work.
66
98
 
67
- The Capable transport encodes subscriptions as server-sent events at `POST /~capable/subscribe/:id`. Errors raised before the first replacement are ordinary HTTP errors; a terminal error after streaming began arrives as a typed SSE error frame.
99
+ ## Present each value [#presentation]
100
+
101
+ `toPresentation` describes one validated value. Typed `subscribe()` consumers receive canonical values without materializing presentation. A presentation-aware surface can request canonical values plus their derived presentations.
102
+
103
+ The CLI appends each event's presentation. For replacement subscriptions, it redraws the current snapshot in a terminal and separates snapshots in piped output. An empty presentation falls back to canonical output; it does not hide an event.
68
104
 
69
105
  ```sh title="terminal"
70
- curl -N -X POST \
71
- -H 'accept: text/event-stream' \
72
- -H 'content-type: application/json' \
73
- --data '{"input":{}}' \
74
- http://localhost:3000/~capable/subscribe/todos.list
106
+ # Events stream automatically; no --watch is needed.
107
+ radar runs logs --run-id run_123
108
+
109
+ # Each canonical event becomes one JSON line; presentation is not generated.
110
+ radar runs logs --run-id run_123 --json
111
+
112
+ # Replacement snapshots still use --watch.
113
+ radar todos list --watch
75
114
  ```
76
115
 
77
- The CLI exposes the same mode with `--watch`, and [React Query](/surfaces/react-query) exposes it as `liveQueryOptions()`. MCP always calls the unary snapshot.
116
+ ## Over the wire [#transport]
117
+
118
+ The Capable transport encodes subscriptions as server-sent events at `POST /~capable/subscribe/:id`, using its rich-value codec for events, replacements, and errors.
119
+
120
+ Replacement streams preserve ordinary HTTP errors before the first snapshot; subsequent failures arrive as typed SSE error frames. Event streams establish without waiting for an event. Before committing the response, Capable parses input, resolves context, enters middleware, invokes the subscriber, and verifies its AsyncIterable result. Failures in that preparation retain their HTTP status. An initial SSE comment then flushes the response without creating a canonical event.
121
+
122
+ An async-generator body starts only when its iterator is pulled. Failures, authorization, or listener setup inside that body therefore happen after establishment; failures arrive as typed SSE error frames. Put request rejection in middleware when it must determine the HTTP status. Listener readiness requires an application-level handshake if it must be known before returning the response.
123
+
124
+ Manifest protocol `capable.capabilities.v4` identifies each capability with `execution: "unary"`, `"live"`, or `"events"`. Upgrade clients and servers together and regenerate bundled manifests when migrating from v3. The value codec remains `capable.rich-json.v1`.
125
+
126
+ ## Other surfaces and scope [#scope]
78
127
 
79
- ## What this is not [#scope]
128
+ [React Query](/surfaces/react-query) and [SWR](/surfaces/swr) expose replacement subscriptions as state updates. Event-only capabilities are excluded from those typed projections and from automatic unary HTTP/OpenAPI, MCP, AI SDK, and Eve tools. Explicit unsupported HTTP or tool metadata is rejected; use `false` to disable that surface. Unary tools can still call a replacement capability's handler.
80
129
 
81
- > **Deliberately out of scope**
82
- >
83
- > Replacement subscriptions are not an event system. There are no patches, no domain events, no buffering, no replay, no resumption, no delivery guarantees, and no reconnection policy. Every item is a complete replacement of the canonical output.
130
+ Subscriptions observe work and require `effect: "read"`. A command that starts work and streams results from that same invocation is outside this API.
84
131
 
85
- That constraint is what keeps one capability honest across surfaces: a consumer that can render the unary result can render every update without additional state.
132
+ Buffering, replay, resumption, delivery guarantees, and reconnection policy remain application responsibilities. Starting a job and then subscribing can miss early events unless the backing service retains them. A pull-based iterator alone does not guarantee lossless capture of a push-based event source.
86
133
 
87
134
  </DocsPage>
@@ -17,10 +17,11 @@ Capable works two ways: as its own service, or embedded in an app you already ha
17
17
 
18
18
  1. ### Install Capable
19
19
 
20
- The `capable` package includes the runtime and the `capable` command for development, builds, and derived CLI access. Zod is the schema authoring library in this example; Capable consumes its Standard Schema and Standard JSON Schema interfaces.
20
+ The `capable` package includes the runtime and the `capable` command for development, builds, and derived CLI access. Zod is the schema authoring library in this example; Capable consumes its Standard Schema and Standard JSON Schema interfaces. `cap build` bundles the server with Rolldown, so add it as a development dependency.
21
21
 
22
22
  ```sh title="terminal"
23
23
  pnpm add capable-kit zod
24
+ pnpm add -D rolldown
24
25
  ```
25
26
 
26
27
  2. ### Create capable.app.ts
@@ -205,7 +206,7 @@ Capable works two ways: as its own service, or embedded in an app you already ha
205
206
 
206
207
  > **Remote apps are apps**
207
208
  >
208
- > A remote app can be merged with a local one using `mergeApps()`, so one command tree can mix capabilities that run on the server with capabilities that must run here. See [Composition](/patterns/composition).
209
+ > A remote app can be combined with a local one using `composeApps()`, so one command tree can mix capabilities that run on the server with capabilities that must run here. See [Composition](/patterns/composition).
209
210
 
210
211
  8. ### Build for production
211
212