@ai-matrx/applets 0.2.7

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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/react/index.ts","../src/react/context.tsx","../src/types.ts","../src/react/data.ts","../src/react/jobs.ts","../src/react/surface.ts","../src/react/nav.tsx","../src/react/nesting.tsx"],"sourcesContent":["/**\n * `@ai-matrx/applets/react` — what Applet code imports (CONTRACTS §2). One\n * module, in the frame. Every hook returns `status` and an `error` carrying\n * the system's own sentence; none throws into React.\n */\nexport { AppletFrame, type AppletFrameProps, type FrameRenderers, type PageActionHandler, newQueryClient } from \"./context\";\nexport {\n useRows,\n useRow,\n useColumns,\n useSources,\n type RowsState,\n type RowState,\n type ColumnsState,\n type SourcesState,\n} from \"./data\";\nexport { useJob, useJobs, type JobState, type JobStatus, type JobInfo, type JobsState, type JobRun } from \"./jobs\";\nexport { useValue, useAction, defineActions, type ActionState } from \"./surface\";\nexport { usePage, navigate, Link, Pages, matchPage, type PageState, type LinkProps, type PagesLayout, type PagesProps } from \"./nav\";\nexport { Applet, Kind, DataPage, type AppletProps, type KindProps, type DataPageProps } from \"./nesting\";\n","/**\n * The frame: `<AppletFrame host>` and the per-frame machinery every hook reads\n * (CONTRACTS §1–§2). One frame per mounted Applet; a nested Applet gets its own\n * frame over the child host, sharing the parent's query cache (keys carry the\n * hostId, so aliases never collide across nesting).\n *\n * The engine is TanStack Query, one QueryClient per frame tree. Rows go through\n * ONE engine, `@ai-matrx/records/data/react`, which the frame mounts with\n * `DataPortProvider` (port `host.data`, events `host.events`, portKey `hostId`).\n */\nimport * as React from \"react\";\nimport { QueryClient, QueryClientProvider } from \"@tanstack/react-query\";\nimport { DataPortProvider, type DataScope } from \"@ai-matrx/records/data/react\";\n\nimport type {\n ActionContext,\n AppletChannel,\n AppletError,\n AppletRecord,\n DataEvents,\n DataPort,\n EventMessage,\n NavLocation,\n PageActionEvent,\n RecordsError,\n RecordsResult,\n Result,\n RowsEvent,\n Viewer,\n} from \"../types\";\nimport { fail, PAGE_ACTION_STREAM, toAppletError } from \"../types\";\n\n// ─── event hub: one host subscription per stream, many listeners ──────────\n\ntype Listener = (payload: unknown) => void;\n\ninterface StreamEntry {\n listeners: Set<Listener>;\n subscriptionId: string | null;\n ready: Promise<void>;\n}\n\n/**\n * Routes `{ subscriptionId, payload }` messages to listeners by stream. A\n * stream is subscribed at the host ONCE however many hooks listen, and\n * released when the last listener leaves.\n */\nexport class EventHub {\n private readonly streams = new Map<string, StreamEntry>();\n private readonly bySubscription = new Map<string, string>();\n private detach: (() => void) | null = null;\n\n constructor(private readonly channel: AppletChannel) {}\n\n subscribe(stream: string, listener: Listener): { unsubscribe: () => void; ready: Promise<void> } {\n if (!this.detach) this.detach = this.channel.receive((m) => this.deliver(m));\n let entry = this.streams.get(stream);\n if (!entry) {\n const created: StreamEntry = { listeners: new Set(), subscriptionId: null, ready: Promise.resolve() };\n created.ready = this.channel.events.on(stream, null).then(\n ({ subscriptionId }) => {\n if (this.streams.get(stream) !== created) {\n void this.channel.events.off(subscriptionId);\n return;\n }\n created.subscriptionId = subscriptionId;\n this.bySubscription.set(subscriptionId, stream);\n },\n (err: unknown) => {\n void this.channel.reportError({ ...toAppletError(err), where: `events.on(${stream})` });\n },\n );\n this.streams.set(stream, created);\n entry = created;\n }\n const current = entry;\n current.listeners.add(listener);\n return {\n ready: current.ready,\n unsubscribe: () => {\n current.listeners.delete(listener);\n if (current.listeners.size > 0 || this.streams.get(stream) !== current) return;\n this.streams.delete(stream);\n if (current.subscriptionId) {\n this.bySubscription.delete(current.subscriptionId);\n void this.channel.events.off(current.subscriptionId);\n }\n if (this.streams.size === 0 && this.detach) {\n this.detach();\n this.detach = null;\n }\n },\n };\n }\n\n private deliver(message: EventMessage): void {\n const stream = this.bySubscription.get(message.subscriptionId);\n if (!stream) return;\n for (const l of [...(this.streams.get(stream)?.listeners ?? [])]) l(message.payload);\n }\n}\n\n/**\n * `host.events` in the shape records' data layer listens on (`DataEvents`):\n * one `rows:<alias>` subscription at the host however many hooks listen.\n */\nexport function frameDataEvents(hub: EventHub): DataEvents {\n return {\n on(event, listener) {\n return hub.subscribe(event, (payload) => listener(payload as RowsEvent)).unsubscribe;\n },\n };\n}\n\nfunction dataScopeFor(channel: AppletChannel, hub: EventHub): DataScope {\n return { port: channel.data, portKey: channel.hostId, events: frameDataEvents(hub) };\n}\n\n// ─── the context ──────────────────────────────────────────────────────────\n\nexport type PageActionHandler = (input: unknown, ctx: ActionContext) => unknown | Promise<unknown>;\n\nexport interface FrameRenderers {\n /** Renders a kind envelope's data. The real one comes from `@ai-matrx/content-ir-react`. */\n renderKind?: (kind: string, value: unknown) => React.ReactNode;\n /** Renders a table-built page from its `pages.definition`. */\n renderDataPage?: (id: string, definition: unknown) => React.ReactNode;\n /** Renders a nested Applet over its child host (`mountApplet` supplies this). */\n renderApplet?: (child: AppletChannel) => React.ReactNode;\n /** The component for one of the record's page files (`mountApplet` supplies this). */\n pageComponent?: (file: string) => React.ComponentType<Record<string, unknown>> | null;\n}\n\nexport interface FrameContextValue extends FrameRenderers {\n channel: AppletChannel;\n hub: EventHub;\n queryClient: QueryClient;\n /**\n * What records' data layer reads through: `port = host.data`, `events` =\n * `host.events` over this frame's hub, `portKey = hostId` (so nested Applets\n * never share a cache entry).\n */\n dataScope: DataScope;\n /** Handlers `defineActions` registered for this frame's page Actions. */\n actions: Map<string, PageActionHandler>;\n parent: FrameContextValue | null;\n /** False only for the detached stand-in a hook gets outside any frame. */\n attached: boolean;\n}\n\n/**\n * The context object lives on `globalThis` so the ESM and CJS builds, and the\n * copies `/react` and `/frame` each carry, all share ONE context.\n */\nconst CONTEXT_KEY = Symbol.for(\"ai-matrx.applets.frameContext\");\nfunction frameContext(): React.Context<FrameContextValue | null> {\n const g = globalThis as unknown as Record<symbol, React.Context<FrameContextValue | null> | undefined>;\n let ctx = g[CONTEXT_KEY];\n if (!ctx) {\n ctx = React.createContext<FrameContextValue | null>(null);\n ctx.displayName = \"AppletFrame\";\n g[CONTEXT_KEY] = ctx;\n }\n return ctx;\n}\n\nexport function newQueryClient(): QueryClient {\n return new QueryClient({\n defaultOptions: {\n // Events keep the cache true (rows:<alias>, value:<name>, run:<id>), so a key is requested once.\n queries: { staleTime: Number.POSITIVE_INFINITY, retry: false, refetchOnWindowFocus: false, refetchOnReconnect: false },\n mutations: { retry: false },\n },\n });\n}\n\n// ─── detached: what a hook gets outside every frame (it never throws) ─────\n\nconst DETACHED_KEY = Symbol.for(\"ai-matrx.applets.detached\");\nconst NO_FRAME: AppletError = {\n code: \"no_frame\",\n message: \"This part of the Applet is not inside an AppletFrame.\",\n retryable: false,\n};\n\nconst NO_FRAME_DATA: RecordsError = { code: \"not_supported\", message: NO_FRAME.message, diagnostic: NO_FRAME.code };\n\nfunction detachedChannel(): AppletChannel {\n const refuse = async <T,>(): Promise<Result<T>> => ({ ok: false, error: NO_FRAME });\n const refuseData = async <T,>(): Promise<RecordsResult<T>> => ({ ok: false, error: NO_FRAME_DATA });\n const reject = async <T,>(): Promise<T> => {\n throw NO_FRAME;\n };\n return {\n hostId: \"detached\",\n viewer: reject<Viewer>,\n record: reject<AppletRecord>,\n child: reject<{ hostId: string }>,\n kinds: { definition: refuse, component: refuse },\n pages: { definition: refuse },\n data: {\n sources: refuseData,\n columns: refuseData,\n list: refuseData,\n get: refuseData,\n create: refuseData,\n update: refuseData,\n archive: refuseData,\n restore: refuseData,\n } satisfies DataPort,\n intelligence: {\n describe: refuse,\n run: refuse,\n result: refuse,\n answer: refuse,\n rejoin: refuse,\n listRuns: refuse,\n createSoft: refuse,\n },\n surface: {\n mount: refuse,\n unmount: async () => undefined,\n getValue: async () => undefined,\n setValue: reject<void>,\n listActions: async () => [],\n runAction: refuse,\n completeAction: async () => undefined,\n },\n nav: { go: reject<void>, current: async (): Promise<NavLocation> => ({ path: [], params: {} }) },\n events: { on: reject<{ subscriptionId: string }>, off: async () => undefined },\n reportError: async () => undefined,\n receive: () => () => undefined,\n forHost: () => null,\n };\n}\n\nfunction detachedFrame(): FrameContextValue {\n const g = globalThis as unknown as Record<symbol, FrameContextValue | undefined>;\n let frame = g[DETACHED_KEY];\n if (!frame) {\n const channel = detachedChannel();\n const hub = new EventHub(channel);\n frame = { channel, hub, queryClient: newQueryClient(), dataScope: dataScopeFor(channel, hub), actions: new Map(), parent: null, attached: false };\n g[DETACHED_KEY] = frame;\n }\n return frame;\n}\n\n/** The frame a hook runs in; a refusing stand-in outside every frame. */\nexport function useFrame(): FrameContextValue {\n return React.useContext(frameContext()) ?? detachedFrame();\n}\n\n/** The nearest frame, or null outside every frame. */\nexport function useOptionalFrame(): FrameContextValue | null {\n return React.useContext(frameContext());\n}\n\n// ─── shared query keys ────────────────────────────────────────────────────\n\nexport const keys = {\n root: (hostId: string) => [\"applets\", hostId] as const,\n record: (hostId: string) => [\"applets\", hostId, \"record\"] as const,\n viewer: (hostId: string) => [\"applets\", hostId, \"viewer\"] as const,\n nav: (hostId: string) => [\"applets\", hostId, \"nav\"] as const,\n};\n\nexport function recordQuery(channel: AppletChannel) {\n return { queryKey: keys.record(channel.hostId), queryFn: () => channel.record() };\n}\nexport function viewerQuery(channel: AppletChannel) {\n return { queryKey: keys.viewer(channel.hostId), queryFn: () => channel.viewer() };\n}\n\n// ─── the frame live registry (for the context-free `navigate`) ───────────\n\nconst FRAMES_KEY = Symbol.for(\"ai-matrx.applets.frames\");\nexport function liveFrames(): FrameContextValue[] {\n const g = globalThis as unknown as Record<symbol, FrameContextValue[] | undefined>;\n let list = g[FRAMES_KEY];\n if (!list) {\n list = [];\n g[FRAMES_KEY] = list;\n }\n return list;\n}\n\n// ─── <AppletFrame> ────────────────────────────────────────────────────────\n\nexport interface AppletFrameProps extends FrameRenderers {\n host: AppletChannel;\n /** Defaults to the parent frame's client, else a new one for this frame. */\n queryClient?: QueryClient;\n children?: React.ReactNode;\n}\n\n/**\n * Mounts one Applet: provides its host to every hook below, joins its surface\n * to the runtime chain (`applets/<id>` under the parent frame's surface), and\n * routes page-Action runs to the handlers `defineActions` registered.\n */\nexport function AppletFrame({ host, queryClient, children, ...renderers }: AppletFrameProps): React.ReactElement {\n const parent = useOptionalFrame();\n const Context = frameContext();\n const [frame] = React.useState<FrameContextValue>(() => {\n const hub = new EventHub(host);\n const value: FrameContextValue = {\n channel: host,\n hub,\n queryClient: queryClient ?? parent?.queryClient ?? newQueryClient(),\n dataScope: dataScopeFor(host, hub),\n actions: new Map(),\n parent,\n attached: true,\n };\n const inherit = <K extends keyof FrameRenderers>(key: K): void => {\n const own = renderers[key] ?? (key === \"renderKind\" || key === \"renderDataPage\" ? parent?.[key] : undefined);\n if (own !== undefined) value[key] = own as FrameContextValue[K];\n };\n inherit(\"renderKind\");\n inherit(\"renderDataPage\");\n inherit(\"renderApplet\");\n inherit(\"pageComponent\");\n return value;\n });\n\n // Register for `navigate`, join the surface chain, route page Actions.\n React.useEffect(() => {\n const frames = liveFrames();\n frames.push(frame);\n let cancelled = false;\n let mountId: string | null = null;\n void (async () => {\n try {\n const record = await frame.queryClient.fetchQuery(recordQuery(host));\n const parentName = parent ? (await parent.queryClient.fetchQuery(recordQuery(parent.channel))).surfaceName : null;\n if (cancelled) return;\n const mounted = await host.surface.mount(record.surfaceName, parentName);\n if (!mounted.ok) {\n void host.reportError({ ...mounted.error, where: \"surface.mount\" });\n return;\n }\n if (cancelled) void host.surface.unmount(mounted.data.mountId);\n else mountId = mounted.data.mountId;\n } catch (err) {\n void host.reportError({ ...toAppletError(err), where: \"AppletFrame mount\" });\n }\n })();\n const { unsubscribe } = frame.hub.subscribe(PAGE_ACTION_STREAM, (payload) => {\n void routePageAction(frame, payload as PageActionEvent);\n });\n return () => {\n cancelled = true;\n unsubscribe();\n if (mountId) void host.surface.unmount(mountId);\n const i = frames.indexOf(frame);\n if (i >= 0) frames.splice(i, 1);\n };\n }, [frame, host, parent]);\n\n const { port, events, portKey } = frame.dataScope;\n const body = (\n <Context.Provider value={frame}>\n <DataPortProvider port={port} portKey={portKey} queryClient={frame.queryClient} {...(events ? { events } : {})}>\n {children}\n </DataPortProvider>\n </Context.Provider>\n );\n return parent?.queryClient === frame.queryClient ? body : <QueryClientProvider client={frame.queryClient}>{body}</QueryClientProvider>;\n}\n\nasync function routePageAction(frame: FrameContextValue, event: PageActionEvent): Promise<void> {\n const { channel } = frame;\n const handler = frame.actions.get(event.action);\n if (!handler) {\n await channel.surface.completeAction(event.runId, fail(\"action_unhandled\", `This page has no handler for \"${event.action}\".`));\n return;\n }\n let viewerId: string | null = null;\n try {\n viewerId = (await frame.queryClient.fetchQuery(viewerQuery(channel))).userId;\n } catch {\n viewerId = null;\n }\n try {\n const data = await handler(event.input, { runId: event.runId, by: event.by ?? \"applet\", viewerId });\n await channel.surface.completeAction(event.runId, { ok: true, data });\n } catch (err) {\n await channel.surface.completeAction(event.runId, { ok: false, error: toAppletError(err) });\n }\n}\n","/**\n * The Applets contract types (CONTRACTS v2 §0, §1, §3, §4, §6, §8).\n *\n * One owner per type. Types another package owns are RE-EXPORTED from it,\n * never redefined; types whose owner has not exported them yet are written\n * here structurally, each naming its owner and contract section, and are\n * replaced by a re-export the release the owner ships them.\n *\n * Framework-free: no React, no runtime imports. Every import below is a type.\n */\nimport type { EntityRefWithWords, Uuid as RecordsUuid } from \"@ai-matrx/records\";\nimport type { IntelligencePort as AgentsIntelligencePort } from \"@ai-matrx/agents/intelligence\";\nimport type { ActionResult, SurfacePort as AlchemySurfacePort } from \"@ai-matrx/alchemy/actions\";\nimport type { ScopeSpec } from \"@ai-matrx/code-runtime\";\nimport type { DataPort, DataSource, WhereClause } from \"@ai-matrx/records/data\";\nimport type { RecordsError } from \"@ai-matrx/records\";\n\n// ─── §0 — owned elsewhere, re-exported ─────────────────────────────────────\n\n/** `@ai-matrx/records` — a UUID string. */\nexport type Uuid = RecordsUuid;\n\n/** `@ai-matrx/records` (AP-3) — every link everywhere reads as `EntityRef[]` (`EntityRefWithWords`). */\nexport type EntityRef = EntityRefWithWords;\n\n/** `@ai-matrx/agents/intelligence` (AP-1). */\nexport type {\n RunRef,\n ServedInput,\n RunEvent,\n KindEnvelope,\n MandateDescription,\n RunRequest,\n RunResult,\n RunListing,\n SoftMandateSpec,\n} from \"@ai-matrx/agents/intelligence\";\n\n/** `@ai-matrx/alchemy/actions` (AP-2). */\nexport type {\n ActionDeclaration,\n ActionInfo,\n ActionContext,\n ActionCaller,\n ActionPolicy,\n ActionRuns,\n} from \"@ai-matrx/alchemy/actions\";\n\n/** `@ai-matrx/code-runtime` (AP-5). */\nexport type { ScopeSpec, CompileResult, Finding } from \"@ai-matrx/code-runtime\";\n\n/**\n * `@ai-matrx/content-ir` — a registered kind slug. content-ir types it as a\n * plain string and exports no named alias; this is that string.\n */\nexport type KindRef = string;\n\n// ─── §0 — owned here ───────────────────────────────────────────────────────\n\n/**\n * The system's own sentence. Superset of `RecordsError` in the sense of the\n * contract: `code` + the store's `message`, plus `retryable`.\n */\nexport interface AppletError {\n code: string;\n message: string;\n retryable: boolean;\n diagnostic?: string;\n}\n\n/** Never throws: every port call and every hook write answers one of these. */\nexport type Result<T> = { ok: true; data: T } | { ok: false; error: AppletError };\n\nexport type Status = \"idle\" | \"loading\" | \"ready\" | \"saving\" | \"error\";\n\n// ─── §0/§4 — owned by @ai-matrx/records (AP-3), re-exported ──────────────\n//\n// AP-3 owns Column, Row, Values, Filter, Query, Page and DataPort (CONTRACTS\n// §0 and §4); `@ai-matrx/records/data` exports them. The frame sees only the\n// port (`DataPort`, no `subscribe`); `HostDataPort` is the host's producer\n// (amendment 2.2) and never crosses the channel.\n\nexport type {\n Column,\n Row,\n Values,\n Query,\n Page,\n DataPort,\n HostDataPort,\n RowsEvent,\n DataSource,\n DataEvents,\n WhereClause,\n WhereOp,\n Lane,\n} from \"@ai-matrx/records/data\";\n\n/** CONTRACTS §4 one `where` clause — records' `WhereClause`. */\nexport type Filter = WhereClause;\n\n/** One source an Applet declared (CONTRACTS §2 `useSources`, §4 `sources()`) — records' `DataSource`. */\nexport type SourceInfo = DataSource;\n\n/** A refusal in the store's words (`RecordsError`) — what a DataPort answers. */\nexport type { RecordsError, RecordsResult } from \"@ai-matrx/records\";\n\n// ─── §3 / §6 — the ports as the host exposes them ──────────────────────────\n\n/**\n * CONTRACTS §3 `IntelligencePort` (owner `@ai-matrx/agents`, AP-1) as a host\n * port: the agents package's port minus its in-process `events` listener —\n * across the doorway, run events arrive on the host's `run:<requestId>`\n * stream instead (no port takes a function).\n */\nexport type IntelligencePort = Omit<AgentsIntelligencePort, \"events\">;\n\n/** CONTRACTS §6 `SurfacePort` (owner `@ai-matrx/alchemy`, AP-2). Events: `value:<name>`. */\nexport type SurfacePort = AlchemySurfacePort;\n\n/**\n * The payload of the `actions` event stream: a `runs: \"page\"` Action routed to\n * the frame (CONTRACTS §6). The frame answers with `surface.completeAction`.\n * `by` is a superset field so the handler's `ActionContext` is truthful.\n */\nexport interface PageActionEvent {\n action: string;\n input: unknown;\n runId: string;\n by?: \"person\" | \"agent\" | \"applet\" | \"automation\";\n}\n\n/** The stream page-Action runs arrive on. */\nexport const PAGE_ACTION_STREAM = \"actions\";\n/** The stream a host announces route changes on (payload: `NavLocation`). */\nexport const NAV_STREAM = \"nav\";\n\nexport const rowsStream = (alias: string): string => `rows:${alias}`;\nexport const runStream = (requestId: string): string => `run:${requestId}`;\nexport const valueStream = (name: string): string => `value:${name}`;\n\n/** Re-exported so hosts can type completeAction answers without importing alchemy. */\nexport type ActionAnswer<T = unknown> = ActionResult<T>;\n\n// ─── §8 — the Applet record ────────────────────────────────────────────────\n\nexport interface AppletPage {\n path: string;\n title: string;\n file: string;\n parent?: string;\n}\n\nexport interface AppletMandate {\n alias: string;\n key: string;\n}\n\nexport type AppletSource =\n | { alias: string; table_id: Uuid; organization_id: Uuid }\n | { alias: string; entity: string };\n\n/** CONTRACTS §8 `AppletRecord` (owner `@ai-matrx/applets`, AP-0). */\nexport interface AppletRecord {\n id: Uuid;\n version: number;\n organizationId: Uuid;\n slug: string;\n published: boolean;\n files: Record<string, string>;\n entry: string;\n scope: ScopeSpec;\n pages: AppletPage[];\n mandates: AppletMandate[];\n sources: AppletSource[];\n parentId: Uuid | null;\n /** `applets/<id>` */\n surfaceName: string;\n}\n\n// ─── §1 — the doorway ──────────────────────────────────────────────────────\n\nexport interface Viewer {\n userId: Uuid | null;\n organizationIds: Uuid[];\n activeOrganizationId: Uuid | null;\n guest: boolean;\n}\n\nexport interface NavLocation {\n path: string[];\n params: Record<string, string>;\n}\n\nexport interface KindComponentSource {\n files: Record<string, string>;\n entry: string;\n}\n\n/**\n * CONTRACTS §1 `AppletHost`. Every call is an async request with JSON in and\n * JSON out (kind envelopes allowed), scoped to ONE mounted Applet.\n */\nexport interface AppletHost {\n viewer(): Promise<Viewer>;\n record(): Promise<AppletRecord>;\n child(appletId: Uuid): Promise<{ hostId: string }>;\n kinds: {\n definition(slug: string): Promise<Result<unknown>>;\n component(slug: string, platform: string): Promise<Result<KindComponentSource | null>>;\n };\n pages: { definition(pageId: Uuid): Promise<Result<unknown>> };\n data: DataPort;\n intelligence: IntelligencePort;\n surface: SurfacePort;\n nav: { go(to: string): Promise<void>; current(): Promise<NavLocation> };\n events: {\n on(stream: string, filter: unknown): Promise<{ subscriptionId: string }>;\n off(subscriptionId: string): Promise<void>;\n };\n reportError(err: AppletError & { where: string }): Promise<void>;\n}\n\n/** What the frame receives for each event (CONTRACTS §1). */\nexport interface EventMessage {\n subscriptionId: string;\n payload: unknown;\n}\n\n/**\n * The frame's side of the doorway: the contract's `AppletHost` plus the two\n * things §1 says the CHANNEL supplies — receiving `{ subscriptionId, payload }`\n * messages, and addressing a child host by the `hostId` that `child()` answered.\n * An in-page host implements these in memory; a sandbox host maps them onto a\n * message channel. Neither is a port: nothing here crosses the doorway as data.\n */\nexport interface AppletChannel extends AppletHost {\n readonly hostId: string;\n /** Subscribe to every event message for this host. Returns an unsubscribe. */\n receive(listener: (message: EventMessage) => void): () => void;\n /** The scoped host for a `hostId` that `child()` answered. */\n forHost(hostId: string): AppletChannel | null;\n}\n\n// ─── helpers every half uses ───────────────────────────────────────────────\n\nexport function ok<T>(data: T): Result<T> {\n return { ok: true, data };\n}\n\nexport function fail<T = never>(code: string, message: string, retryable = false, diagnostic?: string): Result<T> {\n const error: AppletError = { code, message, retryable };\n if (diagnostic !== undefined) error.diagnostic = diagnostic;\n return { ok: false, error };\n}\n\n/**\n * A DataPort refusal (`RecordsError`) as the §0 `AppletError`: the store's code\n * and sentence verbatim, `retryable` true only where a second try could change\n * the answer (the call never reached the store, or ran out of time).\n */\nexport function fromRecordsError(error: RecordsError): AppletError {\n const out: AppletError = { code: error.code, message: error.message, retryable: error.code === \"unreachable\" || error.code === \"timed_out\" };\n if (error.diagnostic !== undefined) out.diagnostic = error.diagnostic;\n return out;\n}\n\n/** Any thrown value → an `AppletError`, keeping a system sentence when there is one. */\nexport function toAppletError(err: unknown, code = \"internal\"): AppletError {\n if (err && typeof err === \"object\") {\n const o = err as Record<string, unknown>;\n if (typeof o.code === \"string\" && typeof o.message === \"string\") {\n const out: AppletError = { code: o.code, message: o.message, retryable: o.retryable === true };\n if (typeof o.diagnostic === \"string\") out.diagnostic = o.diagnostic;\n return out;\n }\n if (err instanceof Error) return { code, message: err.message, retryable: false };\n }\n return { code, message: String(err), retryable: false };\n}\n","/**\n * The data hooks (CONTRACTS §2, over §4's DataPort): `useRows`, `useRow`,\n * `useColumns`, `useSources` and their writes.\n *\n * ONE ENGINE, RECORDS'. Every hook here is a thin wrapper over\n * `@ai-matrx/records/data/react` (AP-3 owns the frame-side data layer, §4):\n * one cache entry and one request per key, keyset pages, optimistic writes\n * rolled back with the store's own sentence, every update carrying the row's\n * `_version`, and `rows:<alias>` events re-reading only the ids they name.\n * This file only reshapes records' answers into §2's (`status`, an\n * `AppletError`, `Result<T>`). `AppletFrame` mounts `DataPortProvider` with\n * `port = host.data`, `events = host.events` and `portKey = hostId`.\n */\nimport * as React from \"react\";\nimport {\n useDataColumns,\n useDataMutations,\n useDataRow,\n useDataRows,\n useDataSources,\n type DataMutations,\n type DataScope,\n} from \"@ai-matrx/records/data/react\";\n\nimport type { AppletChannel, AppletError, Column, Query, RecordsResult, Result, Row, SourceInfo, Status, Uuid, Values } from \"../types\";\nimport { fromRecordsError, toAppletError } from \"../types\";\nimport { useFrame, type FrameContextValue } from \"./context\";\n\n/** A port answer → data, or the error thrown into Query (never into React). */\nasync function unwrap<T>(answer: Promise<Result<T>>): Promise<T> {\n const r = await answer;\n if (!r.ok) throw r.error;\n return r.data;\n}\n\nfunction asAppletError(err: unknown): AppletError | null {\n return err == null ? null : toAppletError(err);\n}\n\nfunction queryStatus(q: { status: \"pending\" | \"error\" | \"success\"; fetchStatus: \"fetching\" | \"paused\" | \"idle\" }, saving: boolean): Status {\n if (q.status === \"error\") return \"error\";\n if (saving) return \"saving\";\n if (q.status === \"pending\") return q.fetchStatus === \"idle\" ? \"idle\" : \"loading\";\n return \"ready\";\n}\n\nfunction toResult<T>(answer: RecordsResult<T>): Result<T> {\n return answer.ok ? answer : { ok: false, error: fromRecordsError(answer.error) };\n}\n\n/** Outside every frame there is no DataPortProvider: the detached stand-in's port is passed explicitly. */\nfunction scopeOf(frame: FrameContextValue): DataScope | undefined {\n return frame.attached ? undefined : frame.dataScope;\n}\n\nfunction readStatus(loading: boolean, failed: boolean, saving: boolean): Status {\n if (failed) return \"error\";\n if (saving) return \"saving\";\n return loading ? \"loading\" : \"ready\";\n}\n\n// ─── the writer every data hook shares ───────────────────────────────────\n\ninterface Writer {\n saving: boolean;\n error: AppletError | null;\n create(values: Values): Promise<Result<Row>>;\n update(id: Uuid, patch: Values, baseVersion?: number): Promise<Result<Row>>;\n archive(id: Uuid): Promise<Result<void>>;\n restore(id: Uuid): Promise<Result<void>>;\n}\n\n/** Records' optimistic mutations, answered as `Result` and tracked for `status` / `error`. */\nfunction useWriter(frame: FrameContextValue, alias: string): Writer {\n const mutations: DataMutations = useDataMutations(alias, scopeOf(frame));\n const [pending, setPending] = React.useState(0);\n const [writeError, setWriteError] = React.useState<AppletError | null>(null);\n\n const track = async <T,>(work: () => Promise<RecordsResult<T>>): Promise<Result<T>> => {\n setPending((n) => n + 1);\n try {\n const answer = toResult(await work());\n setWriteError(answer.ok ? null : answer.error);\n return answer;\n } catch (err) {\n const error = toAppletError(err);\n setWriteError(error);\n return { ok: false, error };\n } finally {\n setPending((n) => n - 1);\n }\n };\n\n return {\n saving: pending > 0,\n error: writeError,\n create: (values) => track(() => mutations.create(values)),\n update: (id, patch, baseVersion) =>\n track(async () => {\n if (baseVersion !== undefined) return mutations.update(id, patch, { baseVersion });\n // Records sends the version a loaded page drew; a row this frame never drew is read first.\n const first = await mutations.update(id, patch);\n if (first.ok || first.error.code !== \"stale_read\") return first;\n const read = await frame.channel.data.get(alias, id);\n if (!read.ok) return read;\n if (!read.data) return { ok: false, error: { code: \"not_found\", message: \"This record is not here any more.\" } };\n return mutations.update(id, patch, { baseVersion: read.data._version });\n }),\n archive: (id) => track(() => mutations.archive(id)),\n restore: (id) => track(() => mutations.restore(id)),\n };\n}\n\n// ─── hooks ────────────────────────────────────────────────────────────────\n\nexport interface RowsState {\n rows: Row[];\n total: number | null;\n status: Status;\n error: AppletError | null;\n hasMore: boolean;\n loadMore(): void;\n /** Rows others wrote that belong somewhere in this (deep, filtered or sorted) list; `refresh()` reads them in. */\n newer: number;\n /** Read this list again from the store. */\n refresh(): void;\n create(values: Values): Promise<Result<Row>>;\n update(id: Uuid, patch: Values): Promise<Result<Row>>;\n archive(id: Uuid): Promise<Result<void>>;\n restore(id: Uuid): Promise<Result<void>>;\n}\n\n/** The rows of one declared source (an alias), paged by keyset cursor. */\nexport function useRows(source: string, q?: Query): RowsState {\n const frame = useFrame();\n const list = useDataRows(source, q ?? {}, scopeOf(frame));\n const writer = useWriter(frame, source);\n return {\n rows: list.rows,\n total: list.total,\n status: readStatus(list.loading, list.error !== null, writer.saving),\n error: (list.error ? fromRecordsError(list.error) : null) ?? writer.error,\n hasMore: list.hasMore,\n loadMore: list.loadMore,\n newer: list.newer,\n refresh: list.refresh,\n create: writer.create,\n update: (id, patch) => writer.update(id, patch, list.rows.find((r) => r._id === id)?._version),\n archive: writer.archive,\n restore: writer.restore,\n };\n}\n\nexport interface RowState {\n row: Row | null;\n status: Status;\n error: AppletError | null;\n update(patch: Values): Promise<Result<Row>>;\n archive(): Promise<Result<void>>;\n /** Read this row again from the store. */\n refresh(): void;\n}\n\n/** One row of a source, sharing the list caches (an update shows in both). */\nexport function useRow(source: string, id: Uuid): RowState {\n const frame = useFrame();\n const one = useDataRow(source, id, scopeOf(frame));\n const writer = useWriter(frame, source);\n const row = one.data ?? null;\n return {\n row,\n status: readStatus(one.loading, one.error !== null, writer.saving),\n error: (one.error ? fromRecordsError(one.error) : null) ?? writer.error,\n update: (patch) => writer.update(id, patch, row?._version),\n archive: () => writer.archive(id),\n refresh: one.refresh,\n };\n}\n\nexport interface ColumnsState {\n columns: Column[];\n status: Status;\n error: AppletError | null;\n}\n\nexport function useColumns(source: string): ColumnsState {\n const frame = useFrame();\n const q = useDataColumns(source, scopeOf(frame));\n return { columns: q.data ?? [], status: readStatus(q.loading, q.error !== null, false), error: q.error ? fromRecordsError(q.error) : null };\n}\n\nexport interface SourcesState {\n sources: SourceInfo[];\n status: Status;\n error: AppletError | null;\n}\n\nexport function useSources(): SourcesState {\n const frame = useFrame();\n const q = useDataSources(scopeOf(frame));\n return { sources: q.data ?? [], status: readStatus(q.loading, q.error !== null, false), error: q.error ? fromRecordsError(q.error) : null };\n}\n\nexport { unwrap, queryStatus, asAppletError };\nexport type { AppletChannel };\n","/**\n * The intelligence hooks (CONTRACTS §2, over §3's IntelligencePort): `useJob`\n * runs one of the Applet's declared jobs by ALIAS (the record's `mandates`\n * maps alias → key) and streams it through the host's `run:<requestId>`\n * events; `useJobs` lists them.\n */\nimport * as React from \"react\";\nimport { useQuery } from \"@tanstack/react-query\";\n\nimport type { AppletError, KindEnvelope, Result, RunEvent, RunRef, ServedInput } from \"../types\";\nimport { runStream, toAppletError } from \"../types\";\nimport { recordQuery, useFrame, viewerQuery } from \"./context\";\nimport { asAppletError, queryStatus, unwrap } from \"./data\";\nimport type { Status } from \"../types\";\n\nexport type JobStatus = \"idle\" | \"resolving\" | \"running\" | \"needs_input\" | \"done\" | \"error\";\n\nexport interface JobRun {\n ref: RunRef;\n startedAt: string;\n status: string;\n}\n\nexport interface JobState {\n run(variables?: Record<string, unknown>, opts?: { userInput?: string }): Promise<Result<RunRef>>;\n status: JobStatus;\n error: AppletError | null;\n text: string;\n result: KindEnvelope | null;\n inputs: ServedInput[];\n answer(values: Record<string, unknown>): Promise<Result<void>>;\n runs: JobRun[];\n}\n\ninterface RunState {\n status: JobStatus;\n error: AppletError | null;\n text: string;\n result: KindEnvelope | null;\n inputs: ServedInput[];\n}\n\nconst IDLE: RunState = { status: \"idle\", error: null, text: \"\", result: null, inputs: [] };\nconst TERMINAL = new Set([\"done\", \"complete\", \"completed\", \"succeeded\", \"success\"]);\n\ntype Action =\n | { type: \"reset\"; status: JobStatus }\n | { type: \"event\"; event: RunEvent }\n | { type: \"fail\"; error: AppletError }\n | { type: \"status\"; status: JobStatus }\n | { type: \"catch-up\"; text: string; envelope: KindEnvelope | null };\n\nfunction reduce(state: RunState, action: Action): RunState {\n switch (action.type) {\n case \"reset\":\n return { ...IDLE, status: action.status };\n case \"fail\":\n return { ...state, status: \"error\", error: action.error };\n case \"status\":\n return { ...state, status: action.status };\n case \"catch-up\":\n if (state.status === \"done\") return state;\n return { ...state, status: \"done\", result: action.envelope, text: state.text || action.text };\n case \"event\": {\n const e = action.event;\n switch (e.type) {\n case \"text\":\n return { ...state, text: state.text + e.delta };\n case \"status\":\n if (TERMINAL.has(e.status)) return { ...state, status: \"done\" };\n if (e.status === \"error\" || e.status === \"failed\") return { ...state, status: \"error\" };\n return state.status === \"done\" ? state : { ...state, status: \"running\" };\n case \"needs_input\":\n return { ...state, status: \"needs_input\", inputs: e.inputs };\n case \"result\":\n return { ...state, status: \"done\", result: e.envelope };\n case \"error\":\n return { ...state, status: \"error\", error: e.error };\n }\n }\n }\n return state;\n}\n\nconst runsKey = (hostId: string, key: string) => [\"applets\", hostId, \"runs\", key] as const;\n\n/** Run one declared job by alias; stream its text, typed result and questions. */\nexport function useJob(alias: string): JobState {\n const frame = useFrame();\n const { channel, queryClient: qc, hub } = frame;\n const [state, dispatch] = React.useReducer(reduce, IDLE);\n const refRef = React.useRef<RunRef | null>(null);\n const unsubscribeRef = React.useRef<(() => void) | null>(null);\n\n React.useEffect(\n () => () => {\n unsubscribeRef.current?.();\n unsubscribeRef.current = null;\n },\n [],\n );\n\n const record = useQuery({ ...recordQuery(channel) }, qc);\n const key = record.data?.mandates.find((m) => m.alias === alias)?.key ?? null;\n const appletId = record.data?.id;\n const runs = useQuery<JobRun[], AppletError>(\n {\n queryKey: runsKey(channel.hostId, key ?? \"\"),\n queryFn: () => unwrap(channel.intelligence.listRuns(key ?? \"\", appletId)),\n enabled: key !== null,\n },\n qc,\n );\n\n const run = async (variables?: Record<string, unknown>, opts?: { userInput?: string }): Promise<Result<RunRef>> => {\n unsubscribeRef.current?.();\n unsubscribeRef.current = null;\n dispatch({ type: \"reset\", status: \"resolving\" });\n try {\n const rec = await qc.fetchQuery(recordQuery(channel));\n const mandate = rec.mandates.find((m) => m.alias === alias);\n if (!mandate) {\n const error: AppletError = { code: \"job_not_found\", message: `This Applet has no job named \"${alias}\".`, retryable: false };\n dispatch({ type: \"fail\", error });\n return { ok: false, error };\n }\n const viewer = await qc.fetchQuery(viewerQuery(channel));\n const req: Parameters<typeof channel.intelligence.run>[0] = {\n key: mandate.key,\n organizationId: viewer.activeOrganizationId,\n appletId: rec.id,\n surfaceName: rec.surfaceName,\n };\n if (variables !== undefined) req.variables = variables;\n if (opts?.userInput !== undefined) req.userInput = opts.userInput;\n const started = await channel.intelligence.run(req);\n if (!started.ok) {\n dispatch({ type: \"fail\", error: started.error });\n return started;\n }\n const ref = started.data;\n refRef.current = ref;\n dispatch({ type: \"status\", status: \"running\" });\n let finished = false;\n const sub = hub.subscribe(runStream(ref.requestId), (payload) => {\n const event = payload as RunEvent;\n dispatch({ type: \"event\", event });\n if (!finished && (event.type === \"result\" || event.type === \"error\" || (event.type === \"status\" && TERMINAL.has(event.status)))) {\n finished = true;\n void qc.invalidateQueries({ queryKey: runsKey(channel.hostId, mandate.key) });\n }\n });\n unsubscribeRef.current = sub.unsubscribe;\n await sub.ready;\n // Anything that finished before the subscription landed is read once.\n const now = await channel.intelligence.result(ref);\n if (now.ok && !finished && (now.data.envelope !== null || TERMINAL.has(now.data.status))) {\n finished = true;\n dispatch({ type: \"catch-up\", text: now.data.text, envelope: now.data.envelope });\n }\n void qc.invalidateQueries({ queryKey: runsKey(channel.hostId, mandate.key) });\n return started;\n } catch (err) {\n const error = toAppletError(err);\n dispatch({ type: \"fail\", error });\n return { ok: false, error };\n }\n };\n\n const answer = async (values: Record<string, unknown>): Promise<Result<void>> => {\n const ref = refRef.current;\n if (!ref) return { ok: false, error: { code: \"no_run\", message: \"There is no run waiting for an answer.\", retryable: false } };\n dispatch({ type: \"status\", status: \"running\" });\n const answered = await channel.intelligence.answer(ref, values);\n if (!answered.ok) dispatch({ type: \"fail\", error: answered.error });\n return answered;\n };\n\n return { run, answer, runs: runs.data ?? [], ...state };\n}\n\nexport interface JobInfo {\n alias: string;\n key: string;\n label: string;\n goal: string;\n outputKind: string | null;\n}\n\nexport interface JobsState {\n jobs: JobInfo[];\n status: Status;\n error: AppletError | null;\n}\n\n/** Every job the Applet declares, described by the server. */\nexport function useJobs(): JobsState {\n const { channel, queryClient } = useFrame();\n const q = useQuery<JobInfo[], AppletError>(\n {\n queryKey: [\"applets\", channel.hostId, \"jobs\"],\n queryFn: async () => {\n const rec = await queryClient.fetchQuery(recordQuery(channel));\n return Promise.all(\n rec.mandates.map(async (m): Promise<JobInfo> => {\n const d = await channel.intelligence.describe(m.key);\n if (!d.ok) throw d.error;\n return { alias: m.alias, key: m.key, label: d.data.label, goal: d.data.goal, outputKind: d.data.outputKind };\n }),\n );\n },\n },\n queryClient,\n );\n return { jobs: q.data ?? [], status: queryStatus(q, false), error: asAppletError(q.error) };\n}\n","/**\n * Surface hooks (CONTRACTS §2, over §6's SurfacePort): `useValue` (a frame-side\n * mirror; writes reach the host asynchronously), `useAction` (run an Action by\n * name), and `defineActions` (this Applet's `runs: \"page\"` handlers — the frame\n * routes each page-Action run to them and answers with `completeAction`).\n */\nimport * as React from \"react\";\nimport { useQuery } from \"@tanstack/react-query\";\n\nimport type { AppletError, Result, Status } from \"../types\";\nimport { toAppletError, valueStream } from \"../types\";\nimport { useFrame, type PageActionHandler } from \"./context\";\n\nconst valueKey = (hostId: string, name: string) => [\"applets\", hostId, \"value\", name] as const;\n\n/** A surface value: `[value, set]`. `set` shows at once and is written to the host after. */\nexport function useValue<T>(name: string): [T, (next: T) => void] {\n const frame = useFrame();\n const { channel, queryClient: qc, hub } = frame;\n const q = useQuery<unknown>({ queryKey: valueKey(channel.hostId, name), queryFn: async () => (await channel.surface.getValue(name)) ?? null }, qc);\n React.useEffect(() => {\n const { unsubscribe } = hub.subscribe(valueStream(name), (payload) => {\n qc.setQueryData(valueKey(channel.hostId, name), payload ?? null);\n });\n return unsubscribe;\n }, [hub, qc, channel, name]);\n const set = (next: T): void => {\n qc.setQueryData(valueKey(channel.hostId, name), next);\n channel.surface.setValue(name, next).catch((err: unknown) => {\n void channel.reportError({ ...toAppletError(err), where: `setValue(${name})` });\n });\n };\n return [(q.data ?? undefined) as T, set];\n}\n\nexport interface ActionState {\n run(input?: unknown): Promise<Result<unknown>>;\n status: Status;\n error: AppletError | null;\n}\n\n/**\n * Run an Action on this Applet's surface chain by name. A press in Applet code\n * is a person's, so runs are `by: \"person\"` unless the caller says otherwise.\n */\nexport function useAction(name: string, options?: { by?: \"person\" | \"agent\" | \"applet\" | \"automation\" }): ActionState {\n const { channel } = useFrame();\n const [status, setStatus] = React.useState<Status>(\"idle\");\n const [error, setError] = React.useState<AppletError | null>(null);\n const run = async (input?: unknown): Promise<Result<unknown>> => {\n setStatus(\"loading\");\n try {\n const answer = await channel.surface.runAction(name, input ?? null, options?.by ?? \"person\");\n if (answer.ok) {\n setError(null);\n setStatus(\"ready\");\n return answer;\n }\n const err: AppletError = { code: answer.error.code, message: answer.error.message, retryable: answer.error.retryable };\n if (answer.error.diagnostic !== undefined) err.diagnostic = answer.error.diagnostic;\n setError(err);\n setStatus(\"error\");\n return { ok: false, error: err };\n } catch (thrown) {\n const err = toAppletError(thrown);\n setError(err);\n setStatus(\"error\");\n return { ok: false, error: err };\n }\n };\n return { run, status, error };\n}\n\n/**\n * This Applet's page-Action handlers. Call it in a component body under the\n * frame (it registers on mount and on every render, and leaves on unmount).\n */\nexport function defineActions(handlers: Record<string, PageActionHandler>): void {\n const frame = useFrame();\n const latest = React.useRef(handlers);\n latest.current = handlers;\n const names = Object.keys(handlers).sort().join(\"\\u0000\");\n React.useEffect(() => {\n const registered = names.split(\"\\u0000\").filter(Boolean);\n for (const name of registered) {\n frame.actions.set(name, (input, ctx) => {\n const handler = latest.current[name];\n if (!handler) throw { code: \"action_unhandled\", message: `This page has no handler for \"${name}\".`, retryable: false };\n return handler(input, ctx);\n });\n }\n return () => {\n for (const name of registered) frame.actions.delete(name);\n };\n }, [frame, names]);\n}\n","/**\n * Navigation and pages (CONTRACTS §2): `usePage`, `navigate`, `<Link>`, and\n * `<Pages layout>` — the optional helper over the record's page list. An Applet\n * is never limited to one page: tabs, a sidebar or a menu, or none at all.\n */\nimport * as React from \"react\";\nimport { useQuery } from \"@tanstack/react-query\";\nimport { Select, Tabs } from \"@ai-matrx/design-system/controls\";\n\nimport type { AppletPage, NavLocation } from \"../types\";\nimport { NAV_STREAM, toAppletError } from \"../types\";\nimport { keys, liveFrames, recordQuery, useFrame, type FrameContextValue } from \"./context\";\n\nfunction parse(to: string): NavLocation {\n const [pathPart = \"\", queryPart = \"\"] = to.split(\"?\");\n const params: Record<string, string> = {};\n for (const pair of queryPart.split(\"&\").filter(Boolean)) {\n const [k = \"\", v = \"\"] = pair.split(\"=\");\n params[decodeURIComponent(k)] = decodeURIComponent(v);\n }\n return { path: pathPart.split(\"/\").filter(Boolean), params };\n}\n\nfunction go(frame: FrameContextValue, to: string): void {\n // Shown at once; the host's answer (and its `nav` events) keep it true.\n frame.queryClient.setQueryData(keys.nav(frame.channel.hostId), parse(to));\n frame.channel.nav.go(to).catch((err: unknown) => {\n void frame.channel.reportError({ ...toAppletError(err), where: `nav.go(${to})` });\n });\n}\n\n/**\n * Go somewhere. Outside a component it uses the outermost mounted frame (the\n * page's route); inside one, `usePage().navigate` is bound to its own frame.\n * With no frame mounted it says so in the console and does nothing.\n */\nexport function navigate(to: string): void {\n const roots = liveFrames().filter((f) => f.parent === null);\n const frame = roots[roots.length - 1];\n if (!frame) {\n console.error(`[applets] navigate(\"${to}\") was called with no AppletFrame mounted.`);\n return;\n }\n go(frame, to);\n}\n\nfunction useLocation(frame: FrameContextValue): NavLocation {\n const { channel, queryClient: qc, hub } = frame;\n const q = useQuery({ queryKey: keys.nav(channel.hostId), queryFn: () => channel.nav.current() }, qc);\n React.useEffect(() => {\n const { unsubscribe } = hub.subscribe(NAV_STREAM, (payload) => {\n qc.setQueryData(keys.nav(channel.hostId), payload as NavLocation);\n });\n return unsubscribe;\n }, [hub, qc, channel]);\n return q.data ?? { path: [], params: {} };\n}\n\nfunction segments(path: string): string[] {\n return path.split(\"/\").filter(Boolean);\n}\n\n/** The page whose path matches (`:name` segments capture params); most specific wins. */\nexport function matchPage(pages: readonly AppletPage[], path: readonly string[]): { page: AppletPage; params: Record<string, string> } | null {\n let best: { page: AppletPage; params: Record<string, string>; score: number } | null = null;\n for (const page of pages) {\n const want = segments(page.path);\n if (want.length !== path.length) continue;\n const params: Record<string, string> = {};\n let score = 0;\n let hit = true;\n want.forEach((w, i) => {\n const got = path[i] ?? \"\";\n if (w.startsWith(\":\")) params[w.slice(1)] = got;\n else if (w === got) score += 1;\n else hit = false;\n });\n if (hit && (!best || score > best.score)) best = { page, params, score };\n }\n return best ? { page: best.page, params: best.params } : null;\n}\n\nexport interface PageState {\n path: string[];\n page: { path: string; title: string };\n params: Record<string, string>;\n /** Bound to this frame (superset of the contract). */\n navigate(to: string): void;\n}\n\nexport function usePage(): PageState {\n const frame = useFrame();\n const location = useLocation(frame);\n const record = useQuery({ ...recordQuery(frame.channel) }, frame.queryClient);\n const pages = record.data?.pages ?? [];\n const matched = matchPage(pages, location.path) ?? (location.path.length === 0 && pages[0] ? { page: pages[0], params: {} } : null);\n return {\n path: location.path,\n page: matched ? { path: matched.page.path, title: matched.page.title } : { path: `/${location.path.join(\"/\")}`, title: \"\" },\n params: { ...location.params, ...(matched?.params ?? {}) },\n navigate: (to) => go(frame, to),\n };\n}\n\nexport interface LinkProps extends Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, \"href\"> {\n to: string;\n}\n\nexport function Link({ to, onClick, children, ...rest }: LinkProps): React.ReactElement {\n const frame = useFrame();\n return (\n <a\n {...rest}\n href={to}\n onClick={(event) => {\n onClick?.(event);\n if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;\n event.preventDefault();\n go(frame, to);\n }}\n >\n {children}\n </a>\n );\n}\n\nexport type PagesLayout = \"tabs\" | \"sidebar\" | \"menu\" | \"none\";\n\nexport interface PagesProps {\n layout?: PagesLayout;\n /** Page components by file, when no `mountApplet` frame supplies them. */\n components?: Record<string, React.ComponentType<Record<string, unknown>>>;\n}\n\n/** The top-level page a page belongs to (itself, or its parent chain's root). */\nfunction topOf(pages: readonly AppletPage[], page: AppletPage): AppletPage {\n let current = page;\n for (let guard = 0; current.parent && guard < pages.length; guard += 1) {\n const up = pages.find((p) => p.path === current.parent);\n if (!up) break;\n current = up;\n }\n return current;\n}\n\n/** The record's pages with a navigation layout, rendering the page the route matches. */\nexport function Pages({ layout = \"tabs\", components }: PagesProps): React.ReactElement {\n const frame = useFrame();\n const location = useLocation(frame);\n const record = useQuery({ ...recordQuery(frame.channel) }, frame.queryClient);\n const pages = record.data?.pages ?? [];\n const top = pages.filter((p) => !p.parent);\n const matched = matchPage(pages, location.path)?.page ?? (location.path.length === 0 ? top[0] : undefined);\n const selected = matched ? topOf(pages, matched).path : null;\n const open = (path: string): void => go(frame, path);\n\n const Component = matched ? (components?.[matched.file] ?? frame.pageComponent?.(matched.file) ?? null) : null;\n const body = matched ? (\n Component ? (\n <Component />\n ) : (\n <div data-applet-stand-in=\"page\" className=\"text-sm text-muted-foreground\">\n Page file {matched.file} is not compiled in this frame\n </div>\n )\n ) : record.isPending ? null : (\n <div data-applet-stand-in=\"no-page\" className=\"text-sm text-muted-foreground\">\n No page at /{location.path.join(\"/\")}\n </div>\n );\n\n let navigation: React.ReactNode = null;\n if (layout === \"tabs\" && top.length > 0) {\n navigation = <Tabs aria-label=\"Pages\" value={selected} onValueChange={open} data={top.map((p) => ({ value: p.path, label: p.title }))} />;\n } else if (layout === \"menu\" && top.length > 0) {\n navigation = <Select aria-label=\"Pages\" value={selected ?? top[0]?.path ?? \"\"} onValueChange={open} options={top.map((p) => ({ value: p.path, label: p.title }))} />;\n } else if (layout === \"sidebar\") {\n navigation = (\n <nav aria-label=\"Pages\" className=\"flex w-48 shrink-0 flex-col gap-1 border-r border-border p-2\">\n {top.map((p) => (\n <button\n key={p.path}\n type=\"button\"\n aria-current={p.path === selected ? \"page\" : undefined}\n data-state={p.path === selected ? \"on\" : \"off\"}\n className=\"rounded-md px-2 py-1 text-left text-sm text-foreground data-[state=off]:text-muted-foreground data-[state=on]:bg-muted\"\n onClick={() => open(p.path)}\n >\n {p.title}\n </button>\n ))}\n </nav>\n );\n }\n\n return (\n <div data-applet-pages={layout} className={layout === \"sidebar\" ? \"flex h-full min-h-0\" : \"flex h-full min-h-0 flex-col\"}>\n {navigation}\n <div className=\"min-h-0 flex-1\">{body}</div>\n </div>\n );\n}\n","/**\n * Nesting and kinds (CONTRACTS §2): `<Applet id>` mounts a nested Applet over\n * its own child host (`host.child`), so names never collide across nesting;\n * `<Kind>` and `<DataPage>` delegate to renderers the frame's host supplies.\n * Each one renders a visible stand-in when its renderer is absent — never\n * nothing.\n */\nimport * as React from \"react\";\n\nimport type { AppletChannel, AppletError } from \"../types\";\nimport { toAppletError } from \"../types\";\nimport { useFrame } from \"./context\";\n\nfunction StandIn({ what, children }: { what: string; children: React.ReactNode }): React.ReactElement {\n return (\n <div data-applet-stand-in={what} className=\"rounded-md border border-dashed border-border p-2 text-sm text-muted-foreground\">\n {children}\n </div>\n );\n}\n\nexport interface AppletProps {\n id: string;\n}\n\n/** A nested Applet, on its own scoped host. */\nexport function Applet({ id }: AppletProps): React.ReactElement {\n const frame = useFrame();\n const [child, setChild] = React.useState<AppletChannel | null>(null);\n const [error, setError] = React.useState<AppletError | null>(null);\n React.useEffect(() => {\n let cancelled = false;\n frame.channel.child(id).then(\n ({ hostId }) => {\n if (cancelled) return;\n const scoped = frame.channel.forHost(hostId);\n if (scoped) setChild(scoped);\n else setError({ code: \"host_not_found\", message: `The host for Applet ${id} did not answer.`, retryable: true });\n },\n (err: unknown) => {\n if (!cancelled) setError(toAppletError(err));\n },\n );\n return () => {\n cancelled = true;\n };\n }, [frame, id]);\n if (error) return <StandIn what=\"applet-error\">{error.message}</StandIn>;\n if (!child) return <div data-applet-loading={id} aria-busy=\"true\" />;\n if (!frame.renderApplet) return <StandIn what=\"applet\">Applet {id} needs mountApplet to render</StandIn>;\n return <>{frame.renderApplet(child)}</>;\n}\n\nexport interface KindProps {\n kind: string;\n value: unknown;\n}\n\n/**\n * A kind, rendered in the frame. The real renderer comes from\n * `@ai-matrx/content-ir-react` and is handed to `<AppletFrame renderKind>` by\n * the host; this component only delegates to it.\n */\nexport function Kind({ kind, value }: KindProps): React.ReactElement {\n const frame = useFrame();\n if (frame.renderKind) return <>{frame.renderKind(kind, value)}</>;\n return <StandIn what={`kind:${kind}`}>No renderer for kind {kind} in this frame</StandIn>;\n}\n\nexport interface DataPageProps {\n id: string;\n}\n\n/** A table-built page, by id, rendered by the host's `renderDataPage`. */\nexport function DataPage({ id }: DataPageProps): React.ReactElement {\n const frame = useFrame();\n const [state, setState] = React.useState<{ definition: unknown } | { error: AppletError } | null>(null);\n React.useEffect(() => {\n let cancelled = false;\n void frame.channel.pages.definition(id).then((r) => {\n if (!cancelled) setState(r.ok ? { definition: r.data } : { error: r.error });\n });\n return () => {\n cancelled = true;\n };\n }, [frame, id]);\n if (!state) return <div data-applet-loading={id} aria-busy=\"true\" />;\n if (\"error\" in state) return <StandIn what=\"data-page-error\">{state.error.message}</StandIn>;\n if (!frame.renderDataPage) return <StandIn what=\"data-page\">Page {id} needs a host page renderer</StandIn>;\n return <>{frame.renderDataPage(id, state.definition)}</>;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACUA,YAAuB;AACvB,yBAAiD;AACjD,mBAAiD;;;ACyH1C,IAAM,qBAAqB;AAE3B,IAAM,aAAa;AAGnB,IAAM,YAAY,CAAC,cAA8B,OAAO,SAAS;AACjE,IAAM,cAAc,CAAC,SAAyB,SAAS,IAAI;AA+G3D,SAAS,KAAgB,MAAc,SAAiB,YAAY,OAAO,YAAgC;AAChH,QAAM,QAAqB,EAAE,MAAM,SAAS,UAAU;AACtD,MAAI,eAAe,OAAW,OAAM,aAAa;AACjD,SAAO,EAAE,IAAI,OAAO,MAAM;AAC5B;AAOO,SAAS,iBAAiB,OAAkC;AACjE,QAAM,MAAmB,EAAE,MAAM,MAAM,MAAM,SAAS,MAAM,SAAS,WAAW,MAAM,SAAS,iBAAiB,MAAM,SAAS,YAAY;AAC3I,MAAI,MAAM,eAAe,OAAW,KAAI,aAAa,MAAM;AAC3D,SAAO;AACT;AAGO,SAAS,cAAc,KAAc,OAAO,YAAyB;AAC1E,MAAI,O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I,MAAM,WAAY,QAAO,6EAAG,gBAAM,WAAW,MAAM,KAAK,GAAE;AAC9D,SAAO,8CAAC,WAAQ,MAAM,QAAQ,IAAI,IAAI;AAAA;AAAA,IAAsB;AAAA,IAAK;AAAA,KAAc;AACjF;AAOO,SAAS,SAAS,EAAE,GAAG,GAAsC;AAClE,QAAM,QAAQ,SAAS;AACvB,QAAM,CAAC,OAAO,QAAQ,IAAU,gBAAkE,IAAI;AACtG,EAAM,iBAAU,MAAM;AACpB,QAAI,YAAY;AAChB,SAAK,MAAM,QAAQ,MAAM,WAAW,EAAE,EAAE,KAAK,CAAC,MAAM;AAClD,UAAI,CAAC,UAAW,UAAS,EAAE,KAAK,EAAE,YAAY,EAAE,KAAK,IAAI,EAAE,OAAO,EAAE,MAAM,CAAC;AAAA,IAC7E,CAAC;AACD,WAAO,MAAM;AACX,kBAAY;AAAA,IACd;AAAA,EACF,GAAG,CAAC,OAAO,EAAE,CAAC;AACd,MAAI,CAAC,MAAO,QAAO,6CAAC,SAAI,uBAAqB,IAAI,aAAU,QAAO;AAClE,MAAI,WAAW,MAAO,QAAO,6CAAC,WAAQ,MAAK,mBAAmB,gBAAM,MAAM,SAAQ;AAClF,MAAI,CAAC,MAAM,eAAgB,QAAO,8CAAC,WAAQ,MAAK,aAAY;AAAA;AAAA,IAAM;AAAA,IAAG;AAAA,KAA2B;AAChG,SAAO,6EAAG,gBAAM,eAAe,IAAI,MAAM,UAAU,GAAE;AACvD;","names":["React","import_react","React","import_react_query","React","import_react_query","React","import_react_query","import_jsx_runtime","React","import_jsx_runtime"]}
@@ -0,0 +1,178 @@
1
+ import { S as Status, A as AppletError, R as Result, U as Uuid, c as SourceInfo, P as PageActionHandler, d as AppletPage } from './context-Dz3PWsJd.cjs';
2
+ export { e as AppletFrame, f as AppletFrameProps, F as FrameRenderers, n as newQueryClient } from './context-Dz3PWsJd.cjs';
3
+ import { Column, Row, Values, Query } from '@ai-matrx/records/data';
4
+ import { RunRef, KindEnvelope, ServedInput } from '@ai-matrx/agents/intelligence';
5
+ import * as React from 'react';
6
+ import '@tanstack/react-query';
7
+ import '@ai-matrx/records';
8
+ import '@ai-matrx/alchemy/actions';
9
+ import '@ai-matrx/code-runtime';
10
+
11
+ interface RowsState {
12
+ rows: Row[];
13
+ total: number | null;
14
+ status: Status;
15
+ error: AppletError | null;
16
+ hasMore: boolean;
17
+ loadMore(): void;
18
+ /** Rows others wrote that belong somewhere in this (deep, filtered or sorted) list; `refresh()` reads them in. */
19
+ newer: number;
20
+ /** Read this list again from the store. */
21
+ refresh(): void;
22
+ create(values: Values): Promise<Result<Row>>;
23
+ update(id: Uuid, patch: Values): Promise<Result<Row>>;
24
+ archive(id: Uuid): Promise<Result<void>>;
25
+ restore(id: Uuid): Promise<Result<void>>;
26
+ }
27
+ /** The rows of one declared source (an alias), paged by keyset cursor. */
28
+ declare function useRows(source: string, q?: Query): RowsState;
29
+ interface RowState {
30
+ row: Row | null;
31
+ status: Status;
32
+ error: AppletError | null;
33
+ update(patch: Values): Promise<Result<Row>>;
34
+ archive(): Promise<Result<void>>;
35
+ /** Read this row again from the store. */
36
+ refresh(): void;
37
+ }
38
+ /** One row of a source, sharing the list caches (an update shows in both). */
39
+ declare function useRow(source: string, id: Uuid): RowState;
40
+ interface ColumnsState {
41
+ columns: Column[];
42
+ status: Status;
43
+ error: AppletError | null;
44
+ }
45
+ declare function useColumns(source: string): ColumnsState;
46
+ interface SourcesState {
47
+ sources: SourceInfo[];
48
+ status: Status;
49
+ error: AppletError | null;
50
+ }
51
+ declare function useSources(): SourcesState;
52
+
53
+ type JobStatus = "idle" | "resolving" | "running" | "needs_input" | "done" | "error";
54
+ interface JobRun {
55
+ ref: RunRef;
56
+ startedAt: string;
57
+ status: string;
58
+ }
59
+ interface JobState {
60
+ run(variables?: Record<string, unknown>, opts?: {
61
+ userInput?: string;
62
+ }): Promise<Result<RunRef>>;
63
+ status: JobStatus;
64
+ error: AppletError | null;
65
+ text: string;
66
+ result: KindEnvelope | null;
67
+ inputs: ServedInput[];
68
+ answer(values: Record<string, unknown>): Promise<Result<void>>;
69
+ runs: JobRun[];
70
+ }
71
+ /** Run one declared job by alias; stream its text, typed result and questions. */
72
+ declare function useJob(alias: string): JobState;
73
+ interface JobInfo {
74
+ alias: string;
75
+ key: string;
76
+ label: string;
77
+ goal: string;
78
+ outputKind: string | null;
79
+ }
80
+ interface JobsState {
81
+ jobs: JobInfo[];
82
+ status: Status;
83
+ error: AppletError | null;
84
+ }
85
+ /** Every job the Applet declares, described by the server. */
86
+ declare function useJobs(): JobsState;
87
+
88
+ /** A surface value: `[value, set]`. `set` shows at once and is written to the host after. */
89
+ declare function useValue<T>(name: string): [T, (next: T) => void];
90
+ interface ActionState {
91
+ run(input?: unknown): Promise<Result<unknown>>;
92
+ status: Status;
93
+ error: AppletError | null;
94
+ }
95
+ /**
96
+ * Run an Action on this Applet's surface chain by name. A press in Applet code
97
+ * is a person's, so runs are `by: "person"` unless the caller says otherwise.
98
+ */
99
+ declare function useAction(name: string, options?: {
100
+ by?: "person" | "agent" | "applet" | "automation";
101
+ }): ActionState;
102
+ /**
103
+ * This Applet's page-Action handlers. Call it in a component body under the
104
+ * frame (it registers on mount and on every render, and leaves on unmount).
105
+ */
106
+ declare function defineActions(handlers: Record<string, PageActionHandler>): void;
107
+
108
+ /**
109
+ * Navigation and pages (CONTRACTS §2): `usePage`, `navigate`, `<Link>`, and
110
+ * `<Pages layout>` — the optional helper over the record's page list. An Applet
111
+ * is never limited to one page: tabs, a sidebar or a menu, or none at all.
112
+ */
113
+
114
+ /**
115
+ * Go somewhere. Outside a component it uses the outermost mounted frame (the
116
+ * page's route); inside one, `usePage().navigate` is bound to its own frame.
117
+ * With no frame mounted it says so in the console and does nothing.
118
+ */
119
+ declare function navigate(to: string): void;
120
+ /** The page whose path matches (`:name` segments capture params); most specific wins. */
121
+ declare function matchPage(pages: readonly AppletPage[], path: readonly string[]): {
122
+ page: AppletPage;
123
+ params: Record<string, string>;
124
+ } | null;
125
+ interface PageState {
126
+ path: string[];
127
+ page: {
128
+ path: string;
129
+ title: string;
130
+ };
131
+ params: Record<string, string>;
132
+ /** Bound to this frame (superset of the contract). */
133
+ navigate(to: string): void;
134
+ }
135
+ declare function usePage(): PageState;
136
+ interface LinkProps extends Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, "href"> {
137
+ to: string;
138
+ }
139
+ declare function Link({ to, onClick, children, ...rest }: LinkProps): React.ReactElement;
140
+ type PagesLayout = "tabs" | "sidebar" | "menu" | "none";
141
+ interface PagesProps {
142
+ layout?: PagesLayout;
143
+ /** Page components by file, when no `mountApplet` frame supplies them. */
144
+ components?: Record<string, React.ComponentType<Record<string, unknown>>>;
145
+ }
146
+ /** The record's pages with a navigation layout, rendering the page the route matches. */
147
+ declare function Pages({ layout, components }: PagesProps): React.ReactElement;
148
+
149
+ /**
150
+ * Nesting and kinds (CONTRACTS §2): `<Applet id>` mounts a nested Applet over
151
+ * its own child host (`host.child`), so names never collide across nesting;
152
+ * `<Kind>` and `<DataPage>` delegate to renderers the frame's host supplies.
153
+ * Each one renders a visible stand-in when its renderer is absent — never
154
+ * nothing.
155
+ */
156
+
157
+ interface AppletProps {
158
+ id: string;
159
+ }
160
+ /** A nested Applet, on its own scoped host. */
161
+ declare function Applet({ id }: AppletProps): React.ReactElement;
162
+ interface KindProps {
163
+ kind: string;
164
+ value: unknown;
165
+ }
166
+ /**
167
+ * A kind, rendered in the frame. The real renderer comes from
168
+ * `@ai-matrx/content-ir-react` and is handed to `<AppletFrame renderKind>` by
169
+ * the host; this component only delegates to it.
170
+ */
171
+ declare function Kind({ kind, value }: KindProps): React.ReactElement;
172
+ interface DataPageProps {
173
+ id: string;
174
+ }
175
+ /** A table-built page, by id, rendered by the host's `renderDataPage`. */
176
+ declare function DataPage({ id }: DataPageProps): React.ReactElement;
177
+
178
+ export { type ActionState, Applet, type AppletProps, type ColumnsState, DataPage, type DataPageProps, type JobInfo, type JobRun, type JobState, type JobStatus, type JobsState, Kind, type KindProps, Link, type LinkProps, PageActionHandler, type PageState, Pages, type PagesLayout, type PagesProps, type RowState, type RowsState, type SourcesState, defineActions, matchPage, navigate, useAction, useColumns, useJob, useJobs, usePage, useRow, useRows, useSources, useValue };
@@ -0,0 +1,178 @@
1
+ import { S as Status, A as AppletError, R as Result, U as Uuid, c as SourceInfo, P as PageActionHandler, d as AppletPage } from './context-Dz3PWsJd.js';
2
+ export { e as AppletFrame, f as AppletFrameProps, F as FrameRenderers, n as newQueryClient } from './context-Dz3PWsJd.js';
3
+ import { Column, Row, Values, Query } from '@ai-matrx/records/data';
4
+ import { RunRef, KindEnvelope, ServedInput } from '@ai-matrx/agents/intelligence';
5
+ import * as React from 'react';
6
+ import '@tanstack/react-query';
7
+ import '@ai-matrx/records';
8
+ import '@ai-matrx/alchemy/actions';
9
+ import '@ai-matrx/code-runtime';
10
+
11
+ interface RowsState {
12
+ rows: Row[];
13
+ total: number | null;
14
+ status: Status;
15
+ error: AppletError | null;
16
+ hasMore: boolean;
17
+ loadMore(): void;
18
+ /** Rows others wrote that belong somewhere in this (deep, filtered or sorted) list; `refresh()` reads them in. */
19
+ newer: number;
20
+ /** Read this list again from the store. */
21
+ refresh(): void;
22
+ create(values: Values): Promise<Result<Row>>;
23
+ update(id: Uuid, patch: Values): Promise<Result<Row>>;
24
+ archive(id: Uuid): Promise<Result<void>>;
25
+ restore(id: Uuid): Promise<Result<void>>;
26
+ }
27
+ /** The rows of one declared source (an alias), paged by keyset cursor. */
28
+ declare function useRows(source: string, q?: Query): RowsState;
29
+ interface RowState {
30
+ row: Row | null;
31
+ status: Status;
32
+ error: AppletError | null;
33
+ update(patch: Values): Promise<Result<Row>>;
34
+ archive(): Promise<Result<void>>;
35
+ /** Read this row again from the store. */
36
+ refresh(): void;
37
+ }
38
+ /** One row of a source, sharing the list caches (an update shows in both). */
39
+ declare function useRow(source: string, id: Uuid): RowState;
40
+ interface ColumnsState {
41
+ columns: Column[];
42
+ status: Status;
43
+ error: AppletError | null;
44
+ }
45
+ declare function useColumns(source: string): ColumnsState;
46
+ interface SourcesState {
47
+ sources: SourceInfo[];
48
+ status: Status;
49
+ error: AppletError | null;
50
+ }
51
+ declare function useSources(): SourcesState;
52
+
53
+ type JobStatus = "idle" | "resolving" | "running" | "needs_input" | "done" | "error";
54
+ interface JobRun {
55
+ ref: RunRef;
56
+ startedAt: string;
57
+ status: string;
58
+ }
59
+ interface JobState {
60
+ run(variables?: Record<string, unknown>, opts?: {
61
+ userInput?: string;
62
+ }): Promise<Result<RunRef>>;
63
+ status: JobStatus;
64
+ error: AppletError | null;
65
+ text: string;
66
+ result: KindEnvelope | null;
67
+ inputs: ServedInput[];
68
+ answer(values: Record<string, unknown>): Promise<Result<void>>;
69
+ runs: JobRun[];
70
+ }
71
+ /** Run one declared job by alias; stream its text, typed result and questions. */
72
+ declare function useJob(alias: string): JobState;
73
+ interface JobInfo {
74
+ alias: string;
75
+ key: string;
76
+ label: string;
77
+ goal: string;
78
+ outputKind: string | null;
79
+ }
80
+ interface JobsState {
81
+ jobs: JobInfo[];
82
+ status: Status;
83
+ error: AppletError | null;
84
+ }
85
+ /** Every job the Applet declares, described by the server. */
86
+ declare function useJobs(): JobsState;
87
+
88
+ /** A surface value: `[value, set]`. `set` shows at once and is written to the host after. */
89
+ declare function useValue<T>(name: string): [T, (next: T) => void];
90
+ interface ActionState {
91
+ run(input?: unknown): Promise<Result<unknown>>;
92
+ status: Status;
93
+ error: AppletError | null;
94
+ }
95
+ /**
96
+ * Run an Action on this Applet's surface chain by name. A press in Applet code
97
+ * is a person's, so runs are `by: "person"` unless the caller says otherwise.
98
+ */
99
+ declare function useAction(name: string, options?: {
100
+ by?: "person" | "agent" | "applet" | "automation";
101
+ }): ActionState;
102
+ /**
103
+ * This Applet's page-Action handlers. Call it in a component body under the
104
+ * frame (it registers on mount and on every render, and leaves on unmount).
105
+ */
106
+ declare function defineActions(handlers: Record<string, PageActionHandler>): void;
107
+
108
+ /**
109
+ * Navigation and pages (CONTRACTS §2): `usePage`, `navigate`, `<Link>`, and
110
+ * `<Pages layout>` — the optional helper over the record's page list. An Applet
111
+ * is never limited to one page: tabs, a sidebar or a menu, or none at all.
112
+ */
113
+
114
+ /**
115
+ * Go somewhere. Outside a component it uses the outermost mounted frame (the
116
+ * page's route); inside one, `usePage().navigate` is bound to its own frame.
117
+ * With no frame mounted it says so in the console and does nothing.
118
+ */
119
+ declare function navigate(to: string): void;
120
+ /** The page whose path matches (`:name` segments capture params); most specific wins. */
121
+ declare function matchPage(pages: readonly AppletPage[], path: readonly string[]): {
122
+ page: AppletPage;
123
+ params: Record<string, string>;
124
+ } | null;
125
+ interface PageState {
126
+ path: string[];
127
+ page: {
128
+ path: string;
129
+ title: string;
130
+ };
131
+ params: Record<string, string>;
132
+ /** Bound to this frame (superset of the contract). */
133
+ navigate(to: string): void;
134
+ }
135
+ declare function usePage(): PageState;
136
+ interface LinkProps extends Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, "href"> {
137
+ to: string;
138
+ }
139
+ declare function Link({ to, onClick, children, ...rest }: LinkProps): React.ReactElement;
140
+ type PagesLayout = "tabs" | "sidebar" | "menu" | "none";
141
+ interface PagesProps {
142
+ layout?: PagesLayout;
143
+ /** Page components by file, when no `mountApplet` frame supplies them. */
144
+ components?: Record<string, React.ComponentType<Record<string, unknown>>>;
145
+ }
146
+ /** The record's pages with a navigation layout, rendering the page the route matches. */
147
+ declare function Pages({ layout, components }: PagesProps): React.ReactElement;
148
+
149
+ /**
150
+ * Nesting and kinds (CONTRACTS §2): `<Applet id>` mounts a nested Applet over
151
+ * its own child host (`host.child`), so names never collide across nesting;
152
+ * `<Kind>` and `<DataPage>` delegate to renderers the frame's host supplies.
153
+ * Each one renders a visible stand-in when its renderer is absent — never
154
+ * nothing.
155
+ */
156
+
157
+ interface AppletProps {
158
+ id: string;
159
+ }
160
+ /** A nested Applet, on its own scoped host. */
161
+ declare function Applet({ id }: AppletProps): React.ReactElement;
162
+ interface KindProps {
163
+ kind: string;
164
+ value: unknown;
165
+ }
166
+ /**
167
+ * A kind, rendered in the frame. The real renderer comes from
168
+ * `@ai-matrx/content-ir-react` and is handed to `<AppletFrame renderKind>` by
169
+ * the host; this component only delegates to it.
170
+ */
171
+ declare function Kind({ kind, value }: KindProps): React.ReactElement;
172
+ interface DataPageProps {
173
+ id: string;
174
+ }
175
+ /** A table-built page, by id, rendered by the host's `renderDataPage`. */
176
+ declare function DataPage({ id }: DataPageProps): React.ReactElement;
177
+
178
+ export { type ActionState, Applet, type AppletProps, type ColumnsState, DataPage, type DataPageProps, type JobInfo, type JobRun, type JobState, type JobStatus, type JobsState, Kind, type KindProps, Link, type LinkProps, PageActionHandler, type PageState, Pages, type PagesLayout, type PagesProps, type RowState, type RowsState, type SourcesState, defineActions, matchPage, navigate, useAction, useColumns, useJob, useJobs, usePage, useRow, useRows, useSources, useValue };