capable-kit 0.0.1-alpha.2 → 0.0.1-alpha.4
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.
- package/README.md +37 -3
- package/dist/ai-sdk.d.mts +1 -1
- package/dist/app.d.mts +1 -1
- package/dist/bin.mjs +189 -27
- package/dist/bin.mjs.map +1 -1
- package/dist/cli.d.mts +1 -1
- package/dist/eve.d.mts +3 -3
- package/dist/eve.mjs.map +1 -1
- package/dist/http.d.mts +1 -1
- package/dist/http.mjs +1 -1
- package/dist/{index-BxJhwhKm.d.mts → index-B_I9n6gN.d.mts} +4 -5
- package/dist/{index-Dp-D73pf.d.mts → index-DCrxWCTv.d.mts} +3 -3
- package/dist/{index-CThfifn8.d.mts → index-DJ--zcWG.d.mts} +5 -5
- package/dist/index.d.mts +1 -1
- package/dist/mcp.d.mts +2 -2
- package/dist/mcp.mjs +1 -1
- package/dist/{mount--YHrgRHJ.mjs → mount-BEBJ2Tss.mjs} +13 -19
- package/dist/mount-BEBJ2Tss.mjs.map +1 -0
- package/dist/runtime-support.d.mts +1 -1
- package/dist/runtime-support.mjs +18 -6
- package/dist/runtime-support.mjs.map +1 -1
- package/dist/server.d.mts +2 -2
- package/dist/server.mjs +2 -2
- package/dist/src-3UaBqI8H.mjs.map +1 -1
- package/dist/src-B53ZbNtC.mjs.map +1 -1
- package/dist/src-BjBxOv7x.mjs.map +1 -1
- package/dist/{src-DpSA-hBO.mjs → src-ChDFqZaE.mjs} +6 -6
- package/dist/{src-DpSA-hBO.mjs.map → src-ChDFqZaE.mjs.map} +1 -1
- package/dist/{src-XRJ9hgYX.mjs → src-D9pLpfeO.mjs} +19 -3
- package/dist/src-D9pLpfeO.mjs.map +1 -0
- package/docs/CONTEXT.md +108 -0
- package/docs/README.md +28 -0
- package/docs/internal/README.md +16 -0
- package/docs/internal/adr/0001-capability-is-the-semantic-boundary.md +24 -0
- package/docs/internal/architecture.md +126 -0
- package/docs/internal/capability-first-model.md +154 -0
- package/docs/internal/implementation-friction.md +674 -0
- package/docs/internal/why-capable.md +94 -0
- package/docs/site/capable-orpc-and-trpc.mdx +133 -0
- package/docs/site/concepts/apps.mdx +217 -0
- package/docs/site/concepts/architecture.mdx +75 -0
- package/docs/site/concepts/capabilities.mdx +249 -0
- package/docs/site/concepts/errors.mdx +93 -0
- package/docs/site/hosting/any-fetch-host.mdx +74 -0
- package/docs/site/hosting/next-js.mdx +77 -0
- package/docs/site/hosting/standalone-server.mdx +94 -0
- package/docs/site/introduction.mdx +142 -0
- package/docs/site/patterns/composition.mdx +142 -0
- package/docs/site/patterns/remote-apps.mdx +117 -0
- package/docs/site/patterns/subscriptions.mdx +87 -0
- package/docs/site/quickstart.mdx +293 -0
- package/docs/site/reference/packages-and-entry-points.mdx +70 -0
- package/docs/site/reference/surface-metadata.mdx +84 -0
- package/docs/site/reference/the-cap-cli.mdx +81 -0
- package/docs/site/surfaces/ai-sdk.mdx +94 -0
- package/docs/site/surfaces/cli.mdx +138 -0
- package/docs/site/surfaces/eve.mdx +121 -0
- package/docs/site/surfaces/http-and-openapi.mdx +111 -0
- package/docs/site/surfaces/mcp.mdx +97 -0
- package/docs/site/surfaces/react-query.mdx +80 -0
- package/docs/site/surfaces/typescript.mdx +123 -0
- package/docs/site/surfaces.mdx +78 -0
- package/docs/site/why-capable.mdx +99 -0
- package/package.json +13 -3
- package/src/package.test.ts +101 -0
- package/dist/mount--YHrgRHJ.mjs.map +0 -1
- package/dist/src-XRJ9hgYX.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"src-D9pLpfeO.mjs","names":["normalizePath"],"sources":["../../fetch/src/error-response.ts","../../fetch/src/capable.ts","../../fetch/src/http.ts"],"sourcesContent":["import { CapableError } from \"@capable/core\";\nimport { TransportError } from \"@capable/app\";\n\nexport type CapabilityErrorData = {\n readonly code: string;\n readonly message: string;\n readonly status: number;\n readonly data?: unknown;\n};\n\nexport function capabilityErrorData(\n error: unknown,\n fallbackStatus = 500,\n): CapabilityErrorData {\n const capable = error instanceof CapableError || error instanceof TransportError\n ? error\n : new CapableError(\"INTERNAL_SERVER_ERROR\", { cause: error });\n return {\n code: capable.code,\n message: capable.message,\n status: capable.status ?? fallbackStatus,\n ...(capable.data === undefined ? {} : { data: capable.data }),\n };\n}\n\nexport function capabilityErrorResponse(\n error: unknown,\n fallbackStatus = 500,\n): Response {\n const data = capabilityErrorData(error, fallbackStatus);\n return Response.json({\n ok: false,\n error: data,\n }, { status: data.status });\n}\n","import {\n getAppRuntime,\n isApp,\n TransportError,\n type ApplicationManifest,\n type ApplicationTransport,\n type AnyApp,\n type CapabilityCall,\n type CapabilityResult,\n} from \"@capable/app\";\nimport {\n capabilityErrorData,\n capabilityErrorResponse,\n} from \"./error-response.ts\";\n\nexport type FetchHandler = (request: Request) => Response | Promise<Response>;\n\nexport function createProtocolHandler(\n application:\n | AnyApp\n | ((request: Request) => AnyApp | Promise<AnyApp>),\n options: {\n readonly basePath?: string;\n } = {},\n): {\n readonly fetch: FetchHandler;\n} {\n const basePath = normalizePath(options.basePath ?? \"/_capable\");\n\n const fetch: FetchHandler = async (request) => {\n const url = new URL(request.url);\n const app = isApp(application)\n ? application\n : await application(request);\n const runtime = getAppRuntime(app);\n if (url.pathname === `${basePath}/manifest` && request.method === \"GET\") {\n return Response.json(await runtime.manifest());\n }\n const subscribePrefix = `${basePath}/subscribe/`;\n if (\n url.pathname.startsWith(subscribePrefix) &&\n request.method === \"POST\"\n ) {\n const id = decodeURIComponent(\n url.pathname.slice(subscribePrefix.length),\n );\n const controller = new AbortController();\n let stream: AsyncIterableIterator<CapabilityResult> | undefined;\n try {\n const body = await request.json() as { readonly input?: unknown };\n stream = runtime.subscribe({\n id,\n input: body.input ?? {},\n signal: AbortSignal.any([request.signal, controller.signal]),\n });\n const first = await stream.next();\n return subscriptionResponse(stream, first, controller);\n } catch (error) {\n controller.abort();\n await stream?.return?.().catch(() => undefined);\n return capabilityErrorResponse(error);\n }\n }\n const callPrefix = `${basePath}/call/`;\n if (!url.pathname.startsWith(callPrefix) || request.method !== \"POST\") {\n return new Response(\"Not Found\", { status: 404 });\n }\n const id = decodeURIComponent(url.pathname.slice(callPrefix.length));\n try {\n const body = await request.json() as { readonly input?: unknown };\n const result = await runtime.call({\n id,\n input: body.input ?? {},\n signal: request.signal,\n });\n return Response.json({\n ok: true,\n ...result,\n });\n } catch (error) {\n return capabilityErrorResponse(error);\n }\n };\n\n return { fetch };\n}\n\nexport type TransportHeaders =\n | HeadersInit\n | (() => HeadersInit | Promise<HeadersInit>);\n\nexport function createHttpTransport(options: {\n readonly url: string | URL | (() => string | URL);\n readonly fetch?: (request: Request) => Response | Promise<Response>;\n readonly headers?: TransportHeaders;\n}): ApplicationTransport {\n const fetchImplementation = options.fetch ?? globalThis.fetch;\n\n async function request(\n path: string,\n init: RequestInit,\n ): Promise<Response> {\n const base = normalizeUrl(\n typeof options.url === \"function\" ? options.url() : options.url,\n );\n const configured = typeof options.headers === \"function\"\n ? await options.headers()\n : options.headers;\n const headers = new Headers(configured);\n new Headers(init.headers).forEach((value, name) => headers.set(name, value));\n return fetchImplementation(\n new Request(new URL(path, base), { ...init, headers }),\n );\n }\n\n return Object.freeze({\n async manifest(\n { signal }: { readonly signal?: AbortSignal } = {},\n ) {\n const response = await request(\"manifest\", {\n method: \"GET\",\n ...(signal ? { signal } : {}),\n });\n if (!response.ok) throw await responseError(response);\n return await responseJson<ApplicationManifest>(\n response,\n \"Application manifest\",\n );\n },\n async call({ id, input = {}, signal }: CapabilityCall) {\n const response = await request(`call/${encodeURIComponent(id)}`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ input }),\n ...(signal ? { signal } : {}),\n });\n const body = await response.json() as\n | {\n readonly ok: true;\n readonly output: unknown;\n readonly markdown?: string;\n }\n | {\n readonly ok: false;\n readonly error: {\n readonly code: string;\n readonly message?: string;\n readonly status?: number;\n readonly data?: unknown;\n };\n };\n if (!body.ok) {\n throw new TransportError(body.error.code, body.error);\n }\n return {\n output: body.output,\n ...(body.markdown ? { markdown: body.markdown } : {}),\n };\n },\n async *subscribe({\n id,\n input = {},\n signal,\n }: CapabilityCall) {\n const response = await request(`subscribe/${encodeURIComponent(id)}`, {\n method: \"POST\",\n headers: {\n accept: \"text/event-stream\",\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify({ input }),\n ...(signal ? { signal } : {}),\n });\n if (!response.ok) throw await responseError(response);\n yield* decodeEventStream(response);\n },\n });\n}\n\nfunction subscriptionResponse(\n stream: AsyncIterableIterator<CapabilityResult>,\n first: IteratorResult<CapabilityResult>,\n subscriptionController: AbortController,\n): Response {\n const encoder = new TextEncoder();\n let initial: IteratorResult<CapabilityResult> | undefined = first;\n\n return new Response(new ReadableStream({\n async pull(controller) {\n try {\n const result = initial ?? await stream.next();\n initial = undefined;\n if (result.done) {\n subscriptionController.abort();\n controller.close();\n return;\n }\n controller.enqueue(encoder.encode(sseFrame(\"output\", result.value)));\n } catch (error) {\n subscriptionController.abort();\n controller.enqueue(encoder.encode(\n sseFrame(\"error\", capabilityErrorData(error)),\n ));\n controller.close();\n await stream.return?.();\n }\n },\n async cancel() {\n subscriptionController.abort();\n await stream.return?.();\n },\n }, {\n highWaterMark: 0,\n }), {\n headers: {\n \"cache-control\": \"no-cache\",\n \"content-type\": \"text/event-stream; charset=utf-8\",\n },\n });\n}\n\nasync function* decodeEventStream(\n response: Response,\n): AsyncIterableIterator<CapabilityResult> {\n if (!response.headers.get(\"content-type\")?.includes(\"text/event-stream\")) {\n throw new TransportError(\"TRANSPORT_ERROR\", {\n status: response.status,\n message: \"Subscription response is not an event stream\",\n });\n }\n if (!response.body) {\n throw new TransportError(\"TRANSPORT_ERROR\", {\n status: response.status,\n message: \"Subscription response has no body\",\n });\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n try {\n while (true) {\n const { done, value } = await reader.read();\n buffer += decoder.decode(value, { stream: !done });\n let boundary = eventBoundary(buffer);\n while (boundary) {\n const block = buffer.slice(0, boundary.index);\n buffer = buffer.slice(boundary.index + boundary.length);\n const event = parseEventBlock(block);\n if (event) {\n if (event.type === \"error\") {\n throw new TransportError(event.error.code, event.error);\n }\n yield event.result;\n }\n boundary = eventBoundary(buffer);\n }\n if (done) break;\n }\n } finally {\n await reader.cancel().catch(() => undefined);\n }\n}\n\nfunction eventBoundary(\n value: string,\n): { readonly index: number; readonly length: number } | undefined {\n const lf = value.indexOf(\"\\n\\n\");\n const crlf = value.indexOf(\"\\r\\n\\r\\n\");\n if (lf < 0 && crlf < 0) {\n return undefined;\n }\n if (crlf >= 0 && (lf < 0 || crlf < lf)) {\n return { index: crlf, length: 4 };\n }\n return { index: lf, length: 2 };\n}\n\nfunction parseEventBlock(block: string):\n | { readonly type: \"output\"; readonly result: CapabilityResult }\n | {\n readonly type: \"error\";\n readonly error: {\n readonly code: string;\n readonly message?: string;\n readonly status?: number;\n readonly data?: unknown;\n };\n }\n | undefined {\n let type = \"message\";\n const data: string[] = [];\n for (const line of block.replace(/\\r\\n/g, \"\\n\").split(\"\\n\")) {\n if (line.startsWith(\":\")) continue;\n if (line.startsWith(\"event:\")) type = line.slice(6).trim();\n if (line.startsWith(\"data:\")) data.push(line.slice(5).trimStart());\n }\n if (!data.length) return undefined;\n const value = JSON.parse(data.join(\"\\n\")) as any;\n return type === \"error\"\n ? { type: \"error\", error: value }\n : { type: \"output\", result: value };\n}\n\nfunction sseFrame(event: string, data: unknown): string {\n return `event: ${event}\\ndata: ${JSON.stringify(data)}\\n\\n`;\n}\n\nfunction normalizeUrl(value: string | URL): URL {\n const url = new URL(value);\n if (!url.pathname.endsWith(\"/\")) url.pathname += \"/\";\n url.search = \"\";\n url.hash = \"\";\n return url;\n}\n\nasync function responseError(response: Response): Promise<TransportError> {\n const text = await response.text().catch(() => \"\");\n let data: unknown = text;\n try {\n data = JSON.parse(text);\n } catch {\n // Preserve the response text as transport diagnostics.\n }\n if (\n data &&\n typeof data === \"object\" &&\n \"ok\" in data &&\n data.ok === false &&\n \"error\" in data &&\n data.error &&\n typeof data.error === \"object\" &&\n \"code\" in data.error &&\n typeof data.error.code === \"string\"\n ) {\n const error = data.error as {\n readonly code: string;\n readonly message?: unknown;\n readonly status?: unknown;\n readonly data?: unknown;\n };\n return new TransportError(error.code, {\n ...(typeof error.message === \"string\"\n ? { message: error.message }\n : {}),\n status: typeof error.status === \"number\"\n ? error.status\n : response.status,\n ...(\"data\" in error ? { data: error.data } : {}),\n });\n }\n return new TransportError(\"TRANSPORT_ERROR\", {\n status: response.status,\n message: `Transport request failed with ${response.status}`,\n data,\n });\n}\n\nasync function responseJson<T>(\n response: Response,\n label: string,\n): Promise<T> {\n const contentType = response.headers.get(\"content-type\");\n if (!contentType?.toLowerCase().includes(\"json\")) {\n throw new TransportError(\"TRANSPORT_ERROR\", {\n status: response.status,\n message:\n `${label} request returned ${contentType ?? \"a non-JSON response\"}${\n response.url ? ` from ${response.url}` : \"\"\n }`,\n });\n }\n try {\n return await response.json() as T;\n } catch (cause) {\n throw new TransportError(\"TRANSPORT_ERROR\", {\n status: response.status,\n message: `${label} response contained invalid JSON`,\n cause,\n });\n }\n}\n\nfunction normalizePath(value: string): string {\n return `/${value.split(\"/\").filter(Boolean).join(\"/\")}`;\n}\n","import {\n executeLocatedCapability,\n schemaToJsonSchema,\n type AppDefinition,\n type GroupMetaRegistry,\n type LocatedCapability,\n type CapabilityMetaRegistry,\n type CapabilityTree,\n} from \"@capable/core\";\nimport {\n type ApplicationSelection,\n type JsonSchema,\n} from \"@capable/app\";\nimport {\n capabilityErrorResponse,\n} from \"./error-response.ts\";\nimport type { FetchHandler } from \"./capable.ts\";\n\nexport type HttpMethod = \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n\nexport type HttpCapabilityMeta =\n | false\n | {\n readonly method?: HttpMethod;\n readonly route?: string;\n readonly status?: number;\n };\n\nexport type HttpGroupMeta = {\n readonly prefix?: string;\n};\n\ndeclare module \"@capable/core\" {\n interface CapabilityMetaRegistry {\n readonly http?: HttpCapabilityMeta;\n }\n\n interface GroupMetaRegistry {\n readonly http?: HttpGroupMeta;\n }\n}\n\nexport type ContextProvider<TContext> = (args: {\n readonly request: Request;\n}) => TContext | Promise<TContext>;\n\nexport type CapabilitySelection<\n TTree extends CapabilityTree = CapabilityTree,\n> = ApplicationSelection<TTree>;\n\nexport type CompiledHttpRoute = {\n readonly method: HttpMethod;\n readonly path: string;\n readonly capability: LocatedCapability;\n};\n\nexport function createHttpHandler<\n const TCapabilities extends CapabilityTree,\n TContext,\n>(\n app: AppDefinition<TCapabilities, TContext>,\n options: {\n readonly context?: ContextProvider<TContext>;\n readonly basePath?: string;\n readonly openapiPath?: string | false;\n readonly requireExplicitRoutes?: boolean;\n readonly selection?: CapabilitySelection<TCapabilities>;\n } = {},\n): {\n readonly fetch: FetchHandler;\n readonly routes: readonly CompiledHttpRoute[];\n readonly openapi: Readonly<Record<string, unknown>>;\n} {\n const basePath = normalizePath(options.basePath ?? \"/api\");\n const selected = selectCapabilities(app.locatedCapabilities, options.selection)\n .filter((entry) => capabilityHttp(entry) !== false);\n const routes = selected.map((entry) => compileHttpRoute(entry, basePath));\n assertUniqueRoutes(routes);\n if (options.requireExplicitRoutes) {\n const implicit = selected.find((entry) => {\n const meta = capabilityHttp(entry);\n return !meta || !meta.method || !meta.route;\n });\n if (implicit) {\n throw new Error(\n `Capability \"${implicit.capability.id}\" requires an explicit HTTP method and route`,\n );\n }\n }\n const openapi = createOpenApi(app, routes);\n const openapiPath = options.openapiPath === false\n ? undefined\n : normalizePath(options.openapiPath ?? \"/openapi.json\");\n\n return {\n routes,\n openapi,\n async fetch(request) {\n const url = new URL(request.url);\n if (\n openapiPath &&\n url.pathname === openapiPath &&\n request.method === \"GET\"\n ) {\n return Response.json(openapi);\n }\n const match = routes\n .map((route) => ({ route, params: matchPath(route.path, url.pathname) }))\n .find(({ route, params }) => route.method === request.method && params);\n if (!match?.params) return new Response(\"Not Found\", { status: 404 });\n\n try {\n const input = await readHttpInput(\n request,\n match.params,\n match.route.capability.capability.input,\n );\n const context = options.context\n ? await options.context({ request })\n : undefined as TContext;\n const output = await executeLocatedCapability(match.route.capability, input, {\n context,\n signal: request.signal,\n });\n if (\n request.headers.get(\"accept\")?.includes(\"text/markdown\") &&\n match.route.capability.capability.toMarkdown\n ) {\n return new Response(\n await match.route.capability.capability.toMarkdown(output, { context }),\n {\n status: httpSuccessStatus(match.route.capability),\n headers: { \"content-type\": \"text/markdown; charset=utf-8\" },\n },\n );\n }\n return Response.json(output, {\n status: httpSuccessStatus(match.route.capability),\n });\n } catch (error) {\n return capabilityErrorResponse(error);\n }\n },\n };\n}\n\nfunction compileHttpRoute(\n entry: LocatedCapability,\n basePath: string,\n): CompiledHttpRoute {\n const meta = capabilityHttp(entry);\n const defaultPath = entry.path.flatMap((segment, index) => {\n const groupIndex = entry.groupPaths.findIndex(\n (path) => path.length === index + 1,\n );\n const prefix = groupIndex >= 0\n ? (entry.groups[groupIndex]?.meta.http as HttpGroupMeta | undefined)\n ?.prefix\n : undefined;\n return prefix ? prefix.split(\"/\").filter(Boolean) : [segment];\n }).join(\"/\");\n const groupPrefix = entry.groups.flatMap((group) => {\n const prefix = (group.meta.http as HttpGroupMeta | undefined)?.prefix;\n return prefix ? prefix.split(\"/\").filter(Boolean) : [];\n }).join(\"/\");\n const authoredRoute = meta && meta.route ? meta.route : defaultPath;\n assertPathParameters(entry, authoredRoute);\n return Object.freeze({\n method: meta && meta.method\n ? meta.method\n : entry.capability.effect === \"read\"\n ? \"GET\"\n : \"POST\",\n path: joinPath(\n basePath,\n meta && meta.route ? groupPrefix : \"\",\n authoredRoute,\n ),\n capability: entry,\n });\n}\n\nfunction capabilityHttp(entry: LocatedCapability): HttpCapabilityMeta | undefined {\n return entry.capability.meta.http as HttpCapabilityMeta | undefined;\n}\n\nfunction httpSuccessStatus(entry: LocatedCapability): number {\n const meta = capabilityHttp(entry);\n return meta && typeof meta.status === \"number\" ? meta.status : 200;\n}\n\nasync function readHttpInput(\n request: Request,\n params: Record<string, string>,\n schema: LocatedCapability[\"capability\"][\"input\"],\n): Promise<Record<string, unknown>> {\n const url = new URL(request.url);\n const jsonSchema = schema\n ? schemaToJsonSchema(schema, \"input\")\n : undefined;\n const properties = jsonSchema?.properties as\n | Record<string, Readonly<Record<string, unknown>>>\n | undefined;\n const coerceEntries = (entries: Iterable<readonly [string, string]>) =>\n Object.fromEntries(\n [...entries].map(([key, value]) => [\n key,\n coerceHttpValue(value, properties?.[key]),\n ]),\n );\n const rest: Record<string, unknown> =\n request.method === \"GET\"\n ? coerceEntries(url.searchParams)\n : request.headers.get(\"content-type\")?.includes(\"application/json\")\n ? await request.json() as Record<string, unknown>\n : {};\n return {\n ...rest,\n ...coerceEntries(Object.entries(params)),\n };\n}\n\nfunction coerceHttpValue(\n value: string,\n schema: Readonly<Record<string, unknown>> | undefined,\n): unknown {\n if (schema?.type === \"boolean\") return value === \"true\"\n ? true\n : value === \"false\"\n ? false\n : value;\n if (schema?.type === \"integer\" || schema?.type === \"number\") {\n const number = Number(value);\n return Number.isFinite(number) ? number : value;\n }\n return value;\n}\n\nfunction assertPathParameters(\n entry: LocatedCapability,\n path: string,\n): void {\n const parameters = [...path.matchAll(/:([^/]+)/g)].map((match) => match[1]!);\n if (parameters.length === 0) return;\n const schema = entry.capability.input\n ? schemaToJsonSchema(entry.capability.input, \"input\")\n : undefined;\n const properties = schema?.properties as\n | Record<string, unknown>\n | undefined;\n for (const parameter of parameters) {\n if (!properties?.[parameter]) {\n throw new Error(\n `HTTP path parameter \":${parameter}\" is not present in Capability \"${entry.capability.id}\" input`,\n );\n }\n }\n}\n\nfunction matchPath(\n pattern: string,\n pathname: string,\n): Record<string, string> | undefined {\n const expected = pattern.split(\"/\").filter(Boolean);\n const actual = pathname.split(\"/\").filter(Boolean);\n if (expected.length !== actual.length) return undefined;\n const params: Record<string, string> = {};\n for (let index = 0; index < expected.length; index++) {\n const token = expected[index]!;\n const value = actual[index]!;\n if (token.startsWith(\":\")) params[token.slice(1)] = decodeURIComponent(value);\n else if (token !== value) return undefined;\n }\n return params;\n}\n\nfunction createOpenApi(\n app: AppDefinition<any, any>,\n routes: readonly CompiledHttpRoute[],\n): Readonly<Record<string, unknown>> {\n const paths: Record<string, unknown> = {};\n for (const route of routes) {\n const method = route.method.toLowerCase();\n const path = route.path.replace(/:([^/]+)/g, \"{$1}\");\n const capability = route.capability.capability;\n const input = capability.input\n ? schemaToJsonSchema(capability.input, \"input\")\n : undefined;\n const properties = (input?.properties ?? {}) as Record<string, JsonSchema>;\n const required = new Set((input?.required ?? []) as readonly string[]);\n const pathNames = new Set(\n [...route.path.matchAll(/:([^/]+)/g)].map((match) => match[1]!),\n );\n const parameters = [...pathNames].map((name) => ({\n name,\n in: \"path\",\n required: true,\n schema: properties[name] ?? {},\n }));\n const remaining = Object.fromEntries(\n Object.entries(properties).filter(([name]) => !pathNames.has(name)),\n );\n if (route.method === \"GET\") {\n parameters.push(\n ...Object.entries(remaining).map(([name, schema]) => ({\n name,\n in: \"query\",\n required: required.has(name),\n schema,\n })),\n );\n }\n const responses: Record<string, unknown> = {\n [String(httpSuccessStatus(route.capability))]: {\n description: \"Successful response\",\n content: {\n \"application/json\": {\n schema: capability.output\n ? schemaToJsonSchema(capability.output, \"output\")\n : {},\n },\n },\n },\n };\n for (const [code, error] of Object.entries(route.capability.errors)) {\n const status = typeof error.status === \"number\"\n ? String(error.status)\n : \"default\";\n responses[status] ??= {\n description: error.message ?? code,\n };\n }\n const current = paths[path] as Record<string, unknown> | undefined ?? {};\n current[method] = {\n capabilityId: capability.id,\n ...(capability.title ? { summary: capability.title } : {}),\n ...(capability.description ? { description: capability.description } : {}),\n ...(parameters.length ? { parameters } : {}),\n ...(route.method !== \"GET\" && Object.keys(remaining).length\n ? {\n requestBody: {\n required: [...required].some((name) => !pathNames.has(name)),\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: remaining,\n required: [...required].filter((name) =>\n !pathNames.has(name)\n ),\n },\n },\n },\n },\n }\n : {}),\n responses,\n };\n paths[path] = current;\n }\n return {\n openapi: \"3.1.0\",\n info: { title: app.name, version: app.version },\n paths,\n };\n}\n\nfunction selectCapabilities(\n capabilities: readonly LocatedCapability[],\n selection: CapabilitySelection | undefined,\n): readonly LocatedCapability[] {\n return capabilities.filter((entry) => {\n const included = selection?.include\n ? matchesTree(selection.include, entry.path)\n : true;\n return included && !matchesTree(selection?.exclude, entry.path);\n });\n}\n\nfunction matchesTree(\n tree: Readonly<Record<string, unknown>> | undefined,\n path: readonly string[],\n): boolean {\n if (!tree) return false;\n let current: unknown = tree;\n for (const segment of path) {\n if (current === true) return true;\n if (!current || typeof current !== \"object\" || Array.isArray(current)) {\n return false;\n }\n current = (current as Record<string, unknown>)[segment];\n }\n return current === true || (\n Boolean(current) && typeof current === \"object\" && !Array.isArray(current)\n );\n}\n\nfunction assertUniqueRoutes(routes: readonly CompiledHttpRoute[]): void {\n const seen = new Set<string>();\n for (const route of routes) {\n const identity = `${route.method} ${route.path}`;\n if (seen.has(identity)) throw new Error(`Duplicate HTTP route ${identity}`);\n seen.add(identity);\n }\n}\n\nfunction normalizePath(value: string): string {\n return `/${value.split(\"/\").filter(Boolean).join(\"/\")}`;\n}\n\nfunction joinPath(...parts: readonly string[]): string {\n return normalizePath(parts.join(\"/\"));\n}\n"],"mappings":";;;AAUA,SAAgB,oBACd,OACA,iBAAiB,KACI;CACrB,MAAM,UAAU,iBAAiB,gBAAgB,iBAAiB,iBAC9D,QACA,IAAI,aAAa,yBAAyB,EAAE,OAAO,MAAM,CAAC;CAC9D,OAAO;EACL,MAAM,QAAQ;EACd,SAAS,QAAQ;EACjB,QAAQ,QAAQ,UAAU;EAC1B,GAAI,QAAQ,SAAS,KAAA,IAAY,CAAC,IAAI,EAAE,MAAM,QAAQ,KAAK;CAC7D;AACF;AAEA,SAAgB,wBACd,OACA,iBAAiB,KACP;CACV,MAAM,OAAO,oBAAoB,OAA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ACH;AAEA,SAAS,YACP,MACA,MACS;CACT,IAAI,CAAC,MAAM,OAAO;CAClB,IAAI,UAAmB;CACvB,KAAK,MAAM,WAAW,MAAM;EAC1B,IAAI,YAAY,MAAM,OAAO;EAC7B,IAAI,CAAC,WAAW,OAAO,YAAY,YAAY,MAAM,QAAQ,OAAO,GAClE,OAAO;EAET,UAAW,QAAoC;CACjD;CACA,OAAO,YAAY,QACjB,QAAQ,OAAO,KAAK,OAAO,YAAY,YAAY,CAAC,MAAM,QAAQ,OAAO;AAE7E;AAEA,SAAS,mBAAmB,QAA4C;CACtE,MAAM,uBAAO,IAAI,IAAY;CAC7B,KAAK,MAAM,SAAS,QAAQ;EAC1B,MAAM,WAAW,GAAG,MAAM,OAAO,GAAG,MAAM;EAC1C,IAAI,KAAK,IAAI,QAAQ,GAAG,MAAM,IAAI,MAAM,wBAAwB,UAAU;EAC1E,KAAK,IAAI,QAAQ;CACnB;AACF;AAEA,SAAS,cAAc,OAAuB;CAC5C,OAAO,IAAI,MAAM,MAAM,GAAG,CAAC,CAAC,OAAO,OAAO,CAAC,CAAC,KAAK,GAAG;AACtD;AAEA,SAAS,SAAS,GAAG,OAAkC;CACrD,OAAO,cAAc,MAAM,KAAK,GAAG,CAAC;AACtC"}
|
package/docs/CONTEXT.md
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
# Capable domain language
|
|
2
|
+
|
|
3
|
+
**Capability**: one typed capability with a canonical string ID, optional
|
|
4
|
+
object-shaped input, optional output schema, declared errors, middleware,
|
|
5
|
+
optional effect, unary handler, optional replacement subscriber, open surface
|
|
6
|
+
metadata, and optional `toMarkdown`.
|
|
7
|
+
It has no canonical HTTP method or path.
|
|
8
|
+
|
|
9
|
+
**App Definition**: immutable named object nesting created by `defineApp()`
|
|
10
|
+
whose leaves are Capabilities. It carries no context provider or execution
|
|
11
|
+
placement. Its paths drive navigational interfaces and surface defaults.
|
|
12
|
+
|
|
13
|
+
**Group**: an anonymous decorated subtree created with `group()`. It has no ID.
|
|
14
|
+
It contributes semantic middleware and errors and exposes its metadata ancestry
|
|
15
|
+
to surface compilers.
|
|
16
|
+
|
|
17
|
+
**Capability ID**: canonical execution and transport identity. IDs are unique
|
|
18
|
+
within an Application.
|
|
19
|
+
|
|
20
|
+
**Application path**: the unique object path to a Capability, such as
|
|
21
|
+
`admin.users.create`. It drives direct App calls, CLI, and MCP navigation but
|
|
22
|
+
is not the Capability's identity.
|
|
23
|
+
|
|
24
|
+
**Effect**: optional `read`, `write`, or `destructive` intent. HTTP may derive
|
|
25
|
+
GET only from `read`; MCP may derive safety hints. Absence means unknown.
|
|
26
|
+
|
|
27
|
+
**Error set**: a branded contract created by `defineErrors()`. Its named,
|
|
28
|
+
callable members construct type-safe declared errors and narrow those errors
|
|
29
|
+
after local or remote execution. Groups may contribute inherited Error sets.
|
|
30
|
+
Any handler or middleware failure outside the located Capability's declared
|
|
31
|
+
sets becomes `INTERNAL_SERVER_ERROR`.
|
|
32
|
+
|
|
33
|
+
**Context declaration**: the `capabilities<TContext>()` factory used to bind
|
|
34
|
+
Capabilities to a context type without constructing that context.
|
|
35
|
+
|
|
36
|
+
**Context provider**: opt-in, boundary-owned context construction. A
|
|
37
|
+
context-free definition uses `createApp(definition)` with no options. When a
|
|
38
|
+
Capability declares context, local consumers must provide it through
|
|
39
|
+
`createApp()` and Fetch servers derive it from the incoming Request. An App
|
|
40
|
+
Definition derives any required context type from its Capability tree but
|
|
41
|
+
stores no provider.
|
|
42
|
+
|
|
43
|
+
**App**: a context-erased typed callable object tree. `createApp()` closes over
|
|
44
|
+
direct execution and its provider; `createRemoteApp()` wraps a transport
|
|
45
|
+
without performing I/O. Remote manifest discovery is lazy, validated, and
|
|
46
|
+
cached. `mergeApps()` returns the same shape. A low-level
|
|
47
|
+
`manifest() + call() + subscribe()` runtime lives behind internal symbols for
|
|
48
|
+
surfaces and composition.
|
|
49
|
+
|
|
50
|
+
**Application merge**: strict root-tree combination through `mergeApps()`.
|
|
51
|
+
Calls dispatch by immutable Capability ID. All path, ID, double-mount, and
|
|
52
|
+
leaf/subtree conflicts fail when the merged manifest first resolves.
|
|
53
|
+
|
|
54
|
+
**Capable transport**: an asynchronous boundary exposing `manifest()`,
|
|
55
|
+
`call()`, and `subscribe()`. `createRemoteApp()` wraps and caches it without
|
|
56
|
+
turning module evaluation into a network boundary. Its HTTP client/server
|
|
57
|
+
encoding lives in `@capable/fetch` as server plumbing, separate from authored
|
|
58
|
+
HTTP APIs and from transport-neutral App semantics.
|
|
59
|
+
|
|
60
|
+
**HTTP projection**: a server mount that derives routes from the Application
|
|
61
|
+
tree and `effect`, then applies optional `meta.http` overrides. It also owns
|
|
62
|
+
OpenAPI.
|
|
63
|
+
|
|
64
|
+
**AI SDK projection**: an asynchronous projection that resolves an executable
|
|
65
|
+
App manifest into typed AI SDK tools. It derives portable names and JSON
|
|
66
|
+
Schemas, then dispatches execution and cancellation through the App runtime.
|
|
67
|
+
|
|
68
|
+
**Surface metadata**: open Capability or Group metadata interpreted only by its
|
|
69
|
+
surface package. Core preserves ancestry and never performs generic merging.
|
|
70
|
+
|
|
71
|
+
**Selection**: tree-shaped `include` and `exclude` policy owned by an exposure
|
|
72
|
+
boundary. Omitted include means all; exclude wins.
|
|
73
|
+
`selectApp()` applies that policy before passing an App to a
|
|
74
|
+
surface.
|
|
75
|
+
|
|
76
|
+
**Canonical output**: handler output after optional output validation.
|
|
77
|
+
`toMarkdown` is an alternate representation, not a second semantic result.
|
|
78
|
+
|
|
79
|
+
**Replacement subscription**: an optional pull-based execution mode on a
|
|
80
|
+
`read` Capability. It shares that Capability's ID, input, Canonical Output,
|
|
81
|
+
declared errors, middleware, placement, and representations. Every emitted
|
|
82
|
+
item is a complete replacement Canonical Output. `subscribe(appCall, input)`
|
|
83
|
+
keeps App navigation collision-free.
|
|
84
|
+
|
|
85
|
+
## Invariants
|
|
86
|
+
|
|
87
|
+
- `@capable/core` depends on no transport, host, CLI, MCP, or HTTP package.
|
|
88
|
+
- Application and Group capability collections are named object trees, never
|
|
89
|
+
arrays.
|
|
90
|
+
- `then` is reserved at every App path so callable proxies cannot become
|
|
91
|
+
promise-like values.
|
|
92
|
+
- App Definitions never carry context providers.
|
|
93
|
+
- A context-free `createApp()` needs no provider; a contextual one satisfies
|
|
94
|
+
and erases only its own context before merging.
|
|
95
|
+
- A Capability object and ID may each occur only once in an Application.
|
|
96
|
+
- Handlers receive only `{ input, context, signal }`.
|
|
97
|
+
- Semantic middleware and declared errors execute identically for every
|
|
98
|
+
surface.
|
|
99
|
+
- Subscription input is parsed once, every replacement is output-validated,
|
|
100
|
+
middleware encloses the complete iterator lifetime, and cancellation aborts
|
|
101
|
+
before iterator cleanup.
|
|
102
|
+
- Platform adapters only translate their host to Fetch Request/Response.
|
|
103
|
+
- HTTP is a projection and deployment concern, not Capability identity.
|
|
104
|
+
- Generic event streams, patches, buffering, replay, resumption, delivery
|
|
105
|
+
guarantees, and reconnection policy are not replacement subscription
|
|
106
|
+
semantics.
|
|
107
|
+
- Idempotence, approvals, and durable tasks remain deferred until a concrete
|
|
108
|
+
consumer proves their contract.
|
package/docs/README.md
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
# Capable documentation
|
|
2
|
+
|
|
3
|
+
This directory is assembled from Capable's canonical documentation sources when
|
|
4
|
+
the npm package is packed. It matches the installed package version.
|
|
5
|
+
|
|
6
|
+
## For coding agents
|
|
7
|
+
|
|
8
|
+
Do not rely on remembered Capable APIs. Read the relevant bundled guide and
|
|
9
|
+
inspect `../src/` when you need a detail the guides do not cover.
|
|
10
|
+
|
|
11
|
+
Start here:
|
|
12
|
+
|
|
13
|
+
1. [Introduction](./site/introduction.mdx)
|
|
14
|
+
2. [Quickstart](./site/quickstart.mdx)
|
|
15
|
+
3. [Capabilities](./site/concepts/capabilities.mdx)
|
|
16
|
+
4. [Apps](./site/concepts/apps.mdx)
|
|
17
|
+
5. [Surfaces](./site/surfaces.mdx)
|
|
18
|
+
6. [Packages and entry points](./site/reference/packages-and-entry-points.mdx)
|
|
19
|
+
|
|
20
|
+
Public guides are grouped by section and named from their frontmatter titles.
|
|
21
|
+
To find a topic, search the files under `site/` or list its `.mdx` files.
|
|
22
|
+
|
|
23
|
+
- `site/` contains the canonical, human- and agent-readable MDX guides.
|
|
24
|
+
- `internal/` contains design notes for contributors.
|
|
25
|
+
- `CONTEXT.md` defines the framework's domain language and invariants.
|
|
26
|
+
|
|
27
|
+
The canonical sources live in `website/`, `docs/`, and `CONTEXT.md` in the
|
|
28
|
+
Capable repository. Edit those sources rather than the generated package copy.
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
# Internal docs
|
|
2
|
+
|
|
3
|
+
User-facing documentation lives in the site under `website/` (`bun run
|
|
4
|
+
docs:dev`). This directory is for people working *on* Capable.
|
|
5
|
+
|
|
6
|
+
| Document | Contains |
|
|
7
|
+
| -------------------------------------------------------------- | --------------------------------------------------------------------- |
|
|
8
|
+
| [../CONTEXT.md](../CONTEXT.md) | The domain language and the invariants every change must preserve |
|
|
9
|
+
| [capability-first-model.md](./capability-first-model.md) | Normative rules of the model: identity, placement, errors, subscriptions |
|
|
10
|
+
| [architecture.md](./architecture.md) | How the packages are layered and why |
|
|
11
|
+
| [adr/](./adr) | Accepted decisions |
|
|
12
|
+
| [implementation-friction.md](./implementation-friction.md) | Live log of awkward or leaky implementation work |
|
|
13
|
+
| [why-capable.md](./why-capable.md) | The original internal argument for the project |
|
|
14
|
+
|
|
15
|
+
If a change contradicts CONTEXT.md, change CONTEXT.md in the same commit or do
|
|
16
|
+
not make the change.
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
---
|
|
2
|
+
status: accepted
|
|
3
|
+
---
|
|
4
|
+
|
|
5
|
+
# Keep Capability as the application-semantic boundary
|
|
6
|
+
|
|
7
|
+
Capable defines protocol-neutral Capabilities and composes them into an Application
|
|
8
|
+
object tree. HTTP endpoints, CLI commands, MCP tools, clients, jobs, and future
|
|
9
|
+
workflows invoke the same Capability executor rather than introducing competing
|
|
10
|
+
business runtimes.
|
|
11
|
+
|
|
12
|
+
A Capability ID is canonical execution identity. The Application path is
|
|
13
|
+
navigational. HTTP method/path and other surface identities are projections.
|
|
14
|
+
|
|
15
|
+
Future approval or durable-task coordination wraps invocation before semantic
|
|
16
|
+
middleware and the handler. It may suspend and resume execution, but it does
|
|
17
|
+
not enter the handler contract or canonical output.
|
|
18
|
+
|
|
19
|
+
App Definitions do not own context provision. `createApp()` satisfies one
|
|
20
|
+
definition's context and erases it into a directly callable App;
|
|
21
|
+
`createRemoteApp()` returns the same callable shape while lazily discovering
|
|
22
|
+
and validating transport execution. `mergeApps()` combines these
|
|
23
|
+
context-erased Apps, so unrelated local contexts never become one giant merged
|
|
24
|
+
context.
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
# Architecture
|
|
2
|
+
|
|
3
|
+
Dependencies point inward. Surfaces and hosts depend on the semantic packages;
|
|
4
|
+
`@capable/core` depends on none of them.
|
|
5
|
+
|
|
6
|
+
```text
|
|
7
|
+
Capability definitions
|
|
8
|
+
│
|
|
9
|
+
▼
|
|
10
|
+
App Definition ──────────────► createServer(definition, { mounts })
|
|
11
|
+
│ ├─ protocol() /_capable/* manifest, call, subscribe
|
|
12
|
+
│ ├─ http() /api/* routes + /openapi.json
|
|
13
|
+
│ └─ mcp() /mcp Streamable HTTP tools
|
|
14
|
+
│ │
|
|
15
|
+
├─ createApp(definition) └─► Next / Nitro / Hono / H3 / Fetch host
|
|
16
|
+
│ └─ context provider only when declared
|
|
17
|
+
└─ createRemoteApp(transport)
|
|
18
|
+
│ lazy manifest discovery
|
|
19
|
+
│
|
|
20
|
+
mergeApps / selectApp
|
|
21
|
+
│
|
|
22
|
+
▼
|
|
23
|
+
App (typed callable object tree)
|
|
24
|
+
│
|
|
25
|
+
┌─────────────┼──────────────┬────────────────────┐
|
|
26
|
+
▼ ▼ ▼ ▼
|
|
27
|
+
direct calls createCli await createMcp await createAiSdkTools
|
|
28
|
+
createEveTools
|
|
29
|
+
createReactQuery
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## Package responsibilities
|
|
33
|
+
|
|
34
|
+
| Package | Owns |
|
|
35
|
+
| ------------------- | -------------------------------------------------------------------- |
|
|
36
|
+
| `capable` | Public facade and the user-installed `cap` command |
|
|
37
|
+
| `@capable/core` | Authoring, tree composition, validation, middleware, errors, execution |
|
|
38
|
+
| `@capable/app` | Callable local and remote Apps, merge, selection, manifests |
|
|
39
|
+
| `@capable/fetch` | Capable transport encoding and the HTTP/OpenAPI projection |
|
|
40
|
+
| `@capable/server` | Fetch server composition and protocol mounts |
|
|
41
|
+
| `@capable/cli` | Command derivation, parsing, help, and rendering |
|
|
42
|
+
| `@capable/mcp` | Tool derivation and the Streamable HTTP mount |
|
|
43
|
+
| `@capable/ai-sdk` | Typed AI SDK v7 tool projection |
|
|
44
|
+
| `@capable/eve` | Native in-process Eve tool projection |
|
|
45
|
+
| `@capable/react-query` | Query keys, query options, mutations, live queries |
|
|
46
|
+
| `@capable/next` | Method-export translation for the App Router |
|
|
47
|
+
| `@capable/nitro-host` | Development server, build, and preview for standalone projects |
|
|
48
|
+
| `@capable/toolchain` | Internal command implementation and project discovery |
|
|
49
|
+
|
|
50
|
+
Core follows the two semantic concepts directly: `capability.ts` owns authoring
|
|
51
|
+
and the complete execution lifecycle, `application.ts` owns Groups, App
|
|
52
|
+
Definitions, placement, and uniqueness. Keeping execution beside authoring
|
|
53
|
+
preserves the Capability seam from [ADR-0001](./adr/0001-capability-is-the-semantic-boundary.md).
|
|
54
|
+
|
|
55
|
+
The App package is transport-neutral: `runtime.ts` owns callable local and
|
|
56
|
+
remote Apps, `composition.ts` owns merge and selection, `manifest.ts` owns
|
|
57
|
+
manifest construction and tree invariants, and `index.ts` is only a facade.
|
|
58
|
+
|
|
59
|
+
## Lazy transport discovery
|
|
60
|
+
|
|
61
|
+
The external transport may perform I/O to discover an Application:
|
|
62
|
+
|
|
63
|
+
```ts
|
|
64
|
+
interface ApplicationTransport {
|
|
65
|
+
manifest(): Promise<ApplicationManifest>;
|
|
66
|
+
call({ id, input, signal }): Promise<{ output: unknown; markdown?: string }>;
|
|
67
|
+
subscribe({ id, input, signal }): AsyncIterableIterator<{
|
|
68
|
+
output: unknown;
|
|
69
|
+
markdown?: string;
|
|
70
|
+
}>;
|
|
71
|
+
}
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
`createRemoteApp(transport)` returns synchronously without performing I/O.
|
|
75
|
+
The first direct call or manifest-dependent projection resolves, validates, and
|
|
76
|
+
caches the manifest. This keeps browser module evaluation free of network work
|
|
77
|
+
while preserving one discovery request per App.
|
|
78
|
+
|
|
79
|
+
The server decides whether that protocol is exposed remotely. Direct App calls
|
|
80
|
+
never manufacture Requests. Apps keep the runtime behind an internal symbol so
|
|
81
|
+
authored Capability keys cannot collide with `manifest` or `call`.
|
|
82
|
+
|
|
83
|
+
Its HTTP encoding lives in `@capable/fetch` — `createHttpTransport()` and
|
|
84
|
+
`createProtocolHandler()` — giving request, response, and SSE encoding one home,
|
|
85
|
+
separate from authored HTTP APIs and from transport-neutral App semantics.
|
|
86
|
+
|
|
87
|
+
Subscriptions are encoded at `POST /_capable/subscribe/:id` as SSE. Errors before
|
|
88
|
+
the first replacement are ordinary HTTP errors; a terminal error after streaming
|
|
89
|
+
began uses a typed SSE error frame.
|
|
90
|
+
|
|
91
|
+
## Composition
|
|
92
|
+
|
|
93
|
+
`mergeApps(a, b)` merges root trees rather than building a pipeline. It returns
|
|
94
|
+
synchronously and resolves its inputs together when its manifest is first
|
|
95
|
+
needed. Path and ID conflicts therefore fail at that discovery boundary, before
|
|
96
|
+
the first Capability is dispatched. Namespaces belong in the authored App
|
|
97
|
+
Definition:
|
|
98
|
+
|
|
99
|
+
```ts
|
|
100
|
+
const remote = createRemoteApp<typeof serverDefinition>(transport);
|
|
101
|
+
const app = mergeApps(
|
|
102
|
+
remote,
|
|
103
|
+
createApp(localDefinition, { context: createLocalContext }),
|
|
104
|
+
);
|
|
105
|
+
|
|
106
|
+
await app.local.login({ token });
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
## Surface compilation
|
|
110
|
+
|
|
111
|
+
HTTP compilation is independent of the other surfaces. Its default route is the
|
|
112
|
+
Application path, with decorated Group prefixes replacing their corresponding
|
|
113
|
+
segment. `effect: "read"` derives GET; anything else derives POST. `meta.http`
|
|
114
|
+
disables or overrides a route, and `requireExplicitRoutes: true` turns implicit
|
|
115
|
+
routes into a startup error.
|
|
116
|
+
|
|
117
|
+
The CLI reads the Capable manifest, derives commands from the same object tree,
|
|
118
|
+
maps configured top-level scalar fields to positional arguments, and maps the
|
|
119
|
+
rest to flags. It never needs to understand the application's HTTP routes, which
|
|
120
|
+
is why local and remote CLIs are identical.
|
|
121
|
+
|
|
122
|
+
The AI SDK projection awaits the manifest it needs to enumerate JSON
|
|
123
|
+
Schema-backed function tools, then dispatches execution through the App runtime.
|
|
124
|
+
Its mapped return type follows the authored Capability tree retained by the App,
|
|
125
|
+
preserving literal tool names and Capability input/output types for typed local
|
|
126
|
+
and remote Apps.
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
# The capability-first model
|
|
2
|
+
|
|
3
|
+
Normative rules of the model. Guides and examples live in the docs site; this
|
|
4
|
+
file records what must remain true. Terminology is defined in
|
|
5
|
+
[CONTEXT.md](../CONTEXT.md).
|
|
6
|
+
|
|
7
|
+
## Identity and placement
|
|
8
|
+
|
|
9
|
+
- A Capability ID is canonical execution identity. It is unique within an
|
|
10
|
+
Application and must not change when a Capability moves.
|
|
11
|
+
- The Application path (`todos.delete`) is navigational structure. Surfaces may
|
|
12
|
+
derive routes, commands, and tool names from it.
|
|
13
|
+
- Application and Group collections are named object trees, never arrays, so
|
|
14
|
+
every Capability has one deterministic path.
|
|
15
|
+
- The same Capability object or ID may occur only once in an Application.
|
|
16
|
+
- Groups are anonymous decorated subtrees. They contribute middleware and error
|
|
17
|
+
sets, and expose their metadata ancestry to surface compilers. Core never
|
|
18
|
+
merges surface metadata generically.
|
|
19
|
+
|
|
20
|
+
```ts
|
|
21
|
+
const deleteTodo = todo({
|
|
22
|
+
id: "delete-todo",
|
|
23
|
+
effect: "destructive",
|
|
24
|
+
input: z.object({ todoId: z.string() }),
|
|
25
|
+
errors: TodoErrors,
|
|
26
|
+
meta: {
|
|
27
|
+
http: { method: "DELETE", route: "/:todoId" },
|
|
28
|
+
cli: { positional: ["todoId"] },
|
|
29
|
+
},
|
|
30
|
+
handler: async ({ input, context }) => {
|
|
31
|
+
if (!await context.todos.delete(input.todoId)) throw TodoErrors.NOT_FOUND();
|
|
32
|
+
return { deleted: true as const };
|
|
33
|
+
},
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
const todos = group({
|
|
37
|
+
middleware: [requireUser],
|
|
38
|
+
errors: AuthErrors,
|
|
39
|
+
meta: { http: { prefix: "/todos" } },
|
|
40
|
+
capabilities: { delete: deleteTodo },
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
const definition = defineApp({
|
|
44
|
+
capabilities: { todos },
|
|
45
|
+
});
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Core-owned Capability fields are `id`, descriptive metadata, optional `effect`,
|
|
49
|
+
optional object-shaped `input`, optional `output`, errors, middleware, `handler`,
|
|
50
|
+
optional `subscribe`, and optional `toMarkdown`. The open `meta` registry is
|
|
51
|
+
typed through module augmentation from surface packages, so core never depends
|
|
52
|
+
on HTTP, CLI, MCP, or Eve.
|
|
53
|
+
|
|
54
|
+
## Execution
|
|
55
|
+
|
|
56
|
+
Input is parsed once, group middleware wraps capability middleware, the handler
|
|
57
|
+
runs, thrown errors are normalized against the located error sets, and output is
|
|
58
|
+
validated. Every surface enters this same lifecycle.
|
|
59
|
+
|
|
60
|
+
A Capability executes without an Application:
|
|
61
|
+
|
|
62
|
+
```ts
|
|
63
|
+
await executeCapability(deleteTodo, { input, context, signal });
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
That boundary applies the Capability's own validation, middleware, and declared
|
|
67
|
+
errors. Group middleware and Group error sets are properties of placement and
|
|
68
|
+
therefore require execution through the tree.
|
|
69
|
+
|
|
70
|
+
## Errors
|
|
71
|
+
|
|
72
|
+
```ts
|
|
73
|
+
const TodoErrors = defineErrors({
|
|
74
|
+
NOT_FOUND: { status: 404, data: z.object({ todoId: z.string() }) },
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
throw TodoErrors.NOT_FOUND({ todoId });
|
|
78
|
+
|
|
79
|
+
if (TodoErrors.NOT_FOUND.is(error)) console.error(error.data.todoId);
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
Declared error data is validated by the executor. Anything outside the located
|
|
83
|
+
Capability's error sets becomes `INTERNAL_SERVER_ERROR`, retaining the original
|
|
84
|
+
value only as a server-side `cause`. A Group and a Capability may not declare
|
|
85
|
+
the same code twice; the conflict fails when the definition is created.
|
|
86
|
+
|
|
87
|
+
## Context and placement
|
|
88
|
+
|
|
89
|
+
`defineApp()` stores no context provider. `createApp()` supplies and erases one
|
|
90
|
+
context; `createRemoteApp()` returns a lazy, transport-backed App. Unrelated
|
|
91
|
+
local contexts are erased before `mergeApps()` and never become one combined
|
|
92
|
+
context:
|
|
93
|
+
|
|
94
|
+
```ts
|
|
95
|
+
const remote = createRemoteApp<typeof serverDefinition>(transport);
|
|
96
|
+
const app = mergeApps(
|
|
97
|
+
remote,
|
|
98
|
+
createApp(localDefinition, { context: createLocalContext }),
|
|
99
|
+
);
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
Merging validates path, ID, double-mount, and leaf/subtree conflicts when its
|
|
103
|
+
manifest first resolves, then dispatches by Capability ID. It never repositions
|
|
104
|
+
trees or rewrites IDs; namespaces belong in the authored definition.
|
|
105
|
+
|
|
106
|
+
## Replacement subscriptions
|
|
107
|
+
|
|
108
|
+
A `read` Capability may define `subscribe` beside `handler`. Both modes share one
|
|
109
|
+
ID, input, output, error set, middleware, placement, and metadata.
|
|
110
|
+
|
|
111
|
+
```ts
|
|
112
|
+
subscribe: ({ input, context, signal }) =>
|
|
113
|
+
watchQuery({
|
|
114
|
+
snapshot: () => context.prices.get(input.symbol),
|
|
115
|
+
invalidations: () => context.prices.watch(input.symbol, { signal }),
|
|
116
|
+
signal,
|
|
117
|
+
}),
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
`watchQuery()` pulls the invalidation source before reading its first snapshot,
|
|
121
|
+
so a concurrent change causes another snapshot instead of being missed.
|
|
122
|
+
Subscription input is parsed once, every replacement is output-validated,
|
|
123
|
+
middleware encloses the complete iterator lifetime, and cancellation aborts the
|
|
124
|
+
subscriber before cleanup.
|
|
125
|
+
|
|
126
|
+
Out of scope, deliberately: patches, generic domain events, buffering, replay,
|
|
127
|
+
resumption, delivery guarantees, and reconnection policy. The Capable transport
|
|
128
|
+
happens to use SSE; that encoding is not part of core semantics. MCP invokes the
|
|
129
|
+
unary snapshot.
|
|
130
|
+
|
|
131
|
+
## Surface direction
|
|
132
|
+
|
|
133
|
+
- Direct calls, CLI, MCP, AI SDK, Eve, and remote clients derive navigation from the
|
|
134
|
+
object tree.
|
|
135
|
+
- HTTP derives `GET` from `effect: "read"` and `POST` otherwise, with the
|
|
136
|
+
Application path as the default route and decorated Group prefixes replacing
|
|
137
|
+
their tree segment. `meta.http` overrides or disables a route, and
|
|
138
|
+
`requireExplicitRoutes` turns implicit routes into a startup error.
|
|
139
|
+
- The Capable transport discovers the tree and calls Capabilities by ID. It is
|
|
140
|
+
separate from an authored or derived HTTP surface.
|
|
141
|
+
- One Fetch server composition mounts the Capable transport, HTTP/OpenAPI, MCP,
|
|
142
|
+
or another protocol, and is shared by Capable-owned Nitro hosting and by embedded
|
|
143
|
+
Next.js or Hono hosting.
|
|
144
|
+
|
|
145
|
+
## Deferred
|
|
146
|
+
|
|
147
|
+
- Generic response and event streaming, separate from replacement subscriptions.
|
|
148
|
+
- `idempotent`, until a retrying transport, Workflow integration, or another
|
|
149
|
+
real consumer proves its contract.
|
|
150
|
+
- Approvals and durable tasks. They wrap an invocation and never enter canonical
|
|
151
|
+
output: a future pre-execution gate may suspend before semantic middleware and
|
|
152
|
+
`handler`, while an execution-boundary coordinator owns grants, task state,
|
|
153
|
+
webhooks, and resumption. The first durable integration should prove that
|
|
154
|
+
boundary vertically with the Workflow SDK and an agent-facing surface.
|