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
@@ -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>
@@ -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";
@@ -72,6 +72,10 @@ JSON.
72
72
 
73
73
  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
74
 
75
+ `subscribe()` resolves after the remote stream is opened, then returns its async
76
+ iterator. This keeps request and authorization failures separate from errors
77
+ emitted after streaming begins.
78
+
75
79
  ```ts title="worker-transport.ts"
76
80
  import type { ApplicationTransport } from "capable-kit/app";
77
81
 
@@ -80,7 +84,7 @@ export function createWorkerTransport(worker: Worker): ApplicationTransport {
80
84
  return {
81
85
  manifest: (options) => send(worker, { kind: "manifest" }, options),
82
86
  call: (call) => send(worker, { kind: "call", call }),
83
- subscribe: (call) => stream(worker, call),
87
+ subscribe: async (call) => stream(worker, call),
84
88
  };
85
89
  }
86
90
  ```
@@ -166,6 +170,6 @@ Calling is uniform; placement is still a decision you make in source. A remote c
166
170
  | It needs to work offline or without a server | It enforces authorization the client must not be trusted with |
167
171
  | Latency per call matters more than trust | The implementation must not ship to the caller |
168
172
 
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.
173
+ 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
174
 
171
175
  </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>
@@ -205,7 +205,7 @@ Capable works two ways: as its own service, or embedded in an app you already ha
205
205
 
206
206
  > **Remote apps are apps**
207
207
  >
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).
208
+ > 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
209
 
210
210
  8. ### Build for production
211
211
 
@@ -11,6 +11,14 @@ export const metadata = docMetadata("/reference/packages", frontmatter);
11
11
 
12
12
  Entry points are explicit so that a server mount, a UI projection, or an agent integration never gets pulled into an application that does not use it.
13
13
 
14
+ ## Changes and upgrades [#changes]
15
+
16
+ Read the [versioned changelog](https://github.com/vercel-labs/capable/blob/main/packages/capable/CHANGELOG.md)
17
+ for features, fixes, and breaking changes. It also ships at
18
+ `node_modules/capable-kit/CHANGELOG.md`. When upgrading, read the target version’s
19
+ changelog and apply entries after your installed version through your target
20
+ version, oldest first. Repository main may be ahead of your installed version.
21
+
14
22
  ## The root entry point [#root]
15
23
 
16
24
  `capable-kit` is deliberately limited to authoring and composing apps. Everything you need to define capabilities lives here.
@@ -26,7 +34,8 @@ import {
26
34
  watchQuery, // snapshot + invalidation subscriber
27
35
  createApp, // definition + context -> callable app
28
36
  createRemoteApp, // transport + definition type -> callable app
29
- mergeApps, // combine apps
37
+ composeApps, // place apps, subtrees, and individual references
38
+ customize, // customize a reference for presentation
30
39
  selectApp, // narrow an app
31
40
  subscribe, // iterate replacements
32
41
  executeCapability, // run one capability without an app
@@ -60,14 +69,52 @@ import {
60
69
  | --- | --- | --- |
61
70
  | `capability()` | `capability(config)` | `capability<Context>()` or `capability.withContext<Context>()` binds a context type |
62
71
  | `present` | `present.table(), .image(), .file()` | Portable presentation parts for `toPresentation` |
63
- | `defineApp()` | `defineApp({ name, version, capabilities })` | Immutable definition, no context |
72
+ | `defineApp()` | `defineApp({ name, version, capabilities, middleware, errors })` | Immutable definition, no context |
64
73
  | `group()` | `group({ middleware, errors, meta, capabilities })` | Anonymous decorated subtree |
65
74
  | `createApp()` | `createApp(definition)` | Callable tree; context options exist only when declared |
66
75
  | `createRemoteApp()` | `createRemoteApp<AppDefinition>(transport)` | Lazy, transport-backed remote placement |
67
- | `mergeApps()` | `mergeApps(a, b, ...)` | Root-tree merge, dispatch by id |
76
+ | `composeApps()` | `composeApps(a, { tools: b.plugins })` | Place whole Apps, executable subtrees, or individual references; dispatch by ID |
77
+ | `customize()` | `customize(app.status, { description, meta: { cli: { positional: ["id"] } } })` | Immutable title, description, and CLI/MCP overrides for a composition entry |
68
78
  | `selectApp()` | `selectApp(app, { include, exclude })` | Exclude wins over include |
69
79
  | `subscribe()` | `subscribe(app.todos.list, input, { signal })` | Async iterator of replacements |
70
80
  | `executeCapability()` | `executeCapability(capability, { input, context, signal })` | No app tree, no group behaviour |
71
81
  | `createServer()` | `createServer(definition, { context, mounts, middleware })` | Returns `{ fetch }` |
72
82
 
83
+ ## Custom surface display [#custom-display]
84
+
85
+ Custom surfaces can read placement settings without replacing the source
86
+ contract used for execution or policy:
87
+
88
+ ```ts
89
+ import {
90
+ flattenManifestCapabilities, getAppRuntime, getCapabilityDisplay,
91
+ } from "capable-kit/app";
92
+
93
+ const manifest = await getAppRuntime(app).manifest();
94
+ const help = flattenManifestCapabilities(manifest.capabilities).map(capability => ({
95
+ id: capability.id,
96
+ path: capability.path,
97
+ ...getCapabilityDisplay(capability),
98
+ }));
99
+ ```
100
+
101
+ `getCapabilityDisplay()` returns the effective title, description, and metadata.
102
+ To opt a custom surface into `customize()` metadata, augment the global
103
+ `CapableCustomizationMeta` interface in the surface's types and explicitly read
104
+ that namespace when compiling its display. This registry is separate from the
105
+ open metadata on authored capabilities.
106
+
107
+ ```ts
108
+ // In a custom surface module:
109
+ declare global {
110
+ interface CapableCustomizationMeta {
111
+ readonly inspector?: { readonly label?: string };
112
+ }
113
+ }
114
+
115
+ const reference = customize(app.status, {
116
+ meta: { inspector: { label: "Instance status" } },
117
+ });
118
+ ```
119
+
73
120
  </DocsPage>
@@ -52,6 +52,39 @@ todo --help
52
52
 
53
53
  `run()` resolves to an exit code: `0` on success, `1` for a failed capability, and `2` for a usage error.
54
54
 
55
+ For a single-operation CLI, map the Capability to an empty command path:
56
+
57
+ ```ts
58
+ capability({
59
+ id: "analysis.url",
60
+ input: z.object({ url: z.string() }),
61
+ meta: { cli: { command: [], positional: ["url"] } },
62
+ handler: ({ input }) => analyzeURL(input.url),
63
+ });
64
+ // pnpm cli vercel.com
65
+ ```
66
+
67
+ Bare invocation and `--help` keep the app name and command listing, with the root
68
+ Capability's arguments and options underneath. `--json`
69
+ or `--watch` selects execution even without positional arguments, applying schema
70
+ defaults or reporting missing required input. Only one Capability may map to the
71
+ root; longer subcommands still take precedence.
72
+
73
+ Pass markdansi's `RenderOptions` directly through `markdown` to customize terminal
74
+ presentations:
75
+
76
+ ```ts
77
+ createCli(app, {
78
+ invocationName: "pnpm cli",
79
+ markdown: { codeBox: false, tableBorder: "none", tableDense: true },
80
+ });
81
+ ```
82
+
83
+ These options are forwarded unchanged for ordinary and watched presentations in
84
+ a TTY. `markdown.color` and `markdown.width`, when supplied, override the CLI's
85
+ color and columns defaults for presentation rendering. Redirected output remains
86
+ Markdown, and `--json` returns canonical output.
87
+
55
88
  ## How commands are derived [#mapping]
56
89
 
57
90
  | Authored | Becomes |
@@ -135,4 +168,15 @@ cap cli --app ./ todos list
135
168
  cap cli --app https://todos.example.com todos list
136
169
  ```
137
170
 
171
+ ## Stream events and live state [#subscriptions]
172
+
173
+ A capability with only `subscribe` streams individual events by default. Readable output appends each event's presentation, with canonical output as the fallback. `--json` emits one canonical event per line without generating presentations.
174
+
175
+ ```sh title="terminal"
176
+ radar runs logs --run-id run_123
177
+ radar runs logs --run-id run_123 --json
178
+ ```
179
+
180
+ Capabilities with both `handler` and `subscribe` keep their unary command and use `--watch` for replacement snapshots. See [Subscriptions](/patterns/subscriptions).
181
+
138
182
  </DocsPage>