@skaile/skailify-core 0.0.0 → 0.1.0

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,"file":"index.js","names":["z"],"sources":["../src/client.ts","../src/capabilities.ts"],"sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\n/**\n * The Skailify client: one per page. It owns the connection to Skaile (the\n * host handshake, the app channel, a fresh token on every reconnect), keeps\n * the capabilities in step with what the mounted components register, tells\n * the agent which view is on screen, and keeps a short activity log the app\n * can show. It imports no UI framework: an app without one calls it directly,\n * and the React and Angular adapters are thin wrappers around it.\n *\n * It connects only inside a Skaile session: the platform embeds an app with the\n * app channel switched on in an iframe whose URL carries `skaileParentOrigin`.\n * Opened on its own, the app does not connect and registrations cost nothing.\n */\nimport {\n type AppAssistantPresentation,\n type AppConnectionParams,\n type AppHandlerContext,\n type AppLogger,\n type AppSession,\n type AppTransport,\n type AppViewReport,\n consoleLogger,\n createSkaileApp,\n createWebSocketAppTransport,\n type DefineAppCapabilityArgs,\n type DefinedAppCapability,\n defineAppCapability,\n PARENT_ORIGIN_QUERY_PARAM,\n type ReconnectOptions,\n resolveAppConnectionParams,\n type SessionTokenProvider,\n type SkaileApp,\n setAssistantPresentation,\n} from \"@skaile/workspaces/app-sdk\";\nimport type * as z from \"zod\";\nimport { genericCapabilities, type Navigation } from \"./capabilities.ts\";\n\nexport type ConnectionStatus =\n | { state: \"idle\" }\n | { state: \"standalone\" }\n | { state: \"connecting\" }\n | { state: \"connected\"; sessionId: string; userId?: string }\n | { state: \"reconnecting\" }\n | { state: \"error\"; message: string }\n | { state: \"closed\" };\n\n/** One line of the activity log: `in` is a call from the agent, `out` is what the app answered or a connection event. */\nexport interface ActivityEntry {\n id: number;\n at: number;\n direction: \"in\" | \"out\";\n label: string;\n detail?: string;\n error?: boolean;\n}\n\n/**\n * An action the agent can call. `name` is relative (`board.add_card`): the client puts `app.` in front, and the\n * platform shows it to the agent as `app.<appId>.board.add_card`. Everything else is the app SDK's\n * `defineAppCapability` arguments, including `requiresApproval` and `effectClass`.\n */\nexport type AgentAction<T extends z.ZodTypeAny = z.ZodTypeAny, R extends z.ZodTypeAny | undefined = z.ZodTypeAny | undefined> =\n DefineAppCapabilityArgs<T, R> & {\n /** @internal the handler waits for the view itself */\n [SETTLES_ITSELF]?: boolean;\n };\n\n/** Types an action's handler from its input schema, for an action declared outside a component. */\nexport function agentAction<T extends z.ZodTypeAny, R extends z.ZodTypeAny | undefined = undefined>(action: AgentAction<T, R>): AgentAction {\n return action as unknown as AgentAction;\n}\n\n/** What a mounted view says about itself. The last view mounted is the one on screen. */\nexport interface ViewRegistration {\n /** Stable id of the view: a route, a screen name, a record key */\n id: string;\n title?: string;\n /** A small JSON-serialisable summary of what the view shows (filters, selection, counts) */\n state?: unknown;\n /** True while the view is still loading what it shows; the agent waits until it is false */\n loading?: boolean;\n}\n\n/** A capability as the agent sees it, for a panel in the app's own UI. */\nexport interface CapabilityInfo {\n /** As registered: `app.board.add_card` */\n name: string;\n /** As the agent calls it: `app.<appId>.board.add_card` */\n agentName: string;\n displayName?: string;\n description: string;\n kind?: \"effect\" | \"render\" | \"query\";\n requiresApproval?: boolean;\n effectClass?: string;\n}\n\nexport interface SkailifySnapshot {\n status: ConnectionStatus;\n activity: readonly ActivityEntry[];\n capabilities: readonly CapabilityInfo[];\n}\n\ninterface WindowLike {\n readonly parent: unknown;\n readonly location: { readonly search: string };\n}\n\nexport interface SkailifyOptions {\n /** The app's id: the `id` of its entry in the workspace's `skaile.preview.json` */\n appId: string;\n /** `auto` (default): connect when embedded in Skaile; `false`: never, not even over `transport` */\n enabled?: \"auto\" | false;\n /**\n * The app's views and how to show one, router-agnostic. With it the agent gets `list_views` and `navigate`;\n * without it, only what the mounted components register.\n */\n navigation?: Navigation;\n logger?: AppLogger;\n reconnect?: ReconnectOptions | false;\n /** How long a call waits for the view to settle after an action; default 3000 ms, at most {@link MAX_WAIT_MS} */\n settleTimeoutMs?: number;\n /**\n * Resolves once the framework has rendered the latest change (Angular: `ApplicationRef.whenStable()`). Settling\n * waits for it, then for the next frame. A framework adapter sets it; without it settling waits for the next frame.\n */\n rendered?: () => Promise<unknown>;\n /**\n * Where code runs, for a framework that tracks async work (Angular's zone.js). The connection and the settle timers\n * run `outside`, so they never keep the app from becoming stable; the handlers run `inside`, so the app sees what\n * they change. The Angular adapter sets it from `NgZone`; without it everything runs where it is called.\n */\n zone?: { inside<T>(fn: () => T): T; outside<T>(fn: () => T): T };\n /** Entries the activity log keeps; default 40 */\n activityLimit?: number;\n /**\n * Connect over this transport instead of the host handshake and the WebSocket (tests, or an app that\n * resolves its own connection). The client then connects whether or not it is embedded.\n */\n transport?: AppTransport;\n /**\n * How Skaile shows its agent button over the app: `{ kind: \"none\" }` hides it, `{ kind: \"floating\", corner,\n * offset, size, accent }` places it. Without it Skaile shows the button where it chooses. Change it later with\n * {@link Skailify.setAssistant}.\n */\n assistant?: AppAssistantPresentation;\n /** For tests: the window, the host handshake, the transport factory and the assistant message */\n windowRef?: WindowLike;\n resolveParams?: (appId: string, parentOrigin: string, assistant?: AppAssistantPresentation) => Promise<AppConnectionParams>;\n postAssistant?: (appId: string, parentOrigin: string, presentation: AppAssistantPresentation) => void;\n createTransport?: (url: string, token: SessionTokenProvider) => AppTransport;\n}\n\nexport interface Skailify {\n readonly appId: string;\n /** The SDK peer once connecting; null when standalone or not started */\n readonly app: SkaileApp | null;\n /** Connects (once; later calls return the same promise). Never rejects: a failure shows in the status. */\n start(): Promise<void>;\n close(): Promise<void>;\n /**\n * Changes how Skaile shows its agent button over the app (see {@link SkailifyOptions.assistant}). Before the\n * connection it replaces the option; standalone it does nothing.\n */\n setAssistant(presentation: AppAssistantPresentation): void;\n /**\n * Adds an action; returns the function that removes exactly this registration. Of several actions with the same\n * name the one registered last is offered; removing it offers the one before again.\n */\n registerAction<T extends z.ZodTypeAny, R extends z.ZodTypeAny | undefined = undefined>(action: AgentAction<T, R>): () => void;\n /**\n * Adds a view; returns the function that updates it and the one that removes it. Of several mounted views the one\n * with the highest `order` is on screen; without one, the view added last. Pass an order from {@link viewOrder}\n * taken while rendering, so a parent and the child it contains, mounted together, keep the child on top.\n */\n registerView(view: ViewRegistration, order?: number): { update(view: ViewRegistration): void; remove(): void };\n /** A new view order, increasing; take it when a view first renders */\n viewOrder(): number;\n /** Exposes a named piece of state to `get_view_state`; `read` is called on every read. */\n registerState(name: string, read: () => unknown): () => void;\n /** The view on screen: the last one mounted, else the navigation's current view */\n currentView(): ViewRegistration | null;\n /** Every registered state, read now */\n readState(): Record<string, unknown>;\n /** Whether a mounted view says it is still loading */\n loading(): boolean;\n /**\n * Waits until the app has rendered and no mounted view is loading, then tells the agent what is on screen and\n * that it has settled. Resolves false when the timeout came first. The client calls it after every effect.\n */\n settle(timeoutMs?: number): Promise<boolean>;\n /** The full name of a relative one: `board.add_card` → `app.board.add_card` */\n fullName(name: string): string;\n /** The name the agent calls: `board.add_card` → `app.<appId>.board.add_card` */\n agentName(name: string): string;\n /** For the UI: React's `useSyncExternalStore`, Angular's signals, or a plain listener */\n subscribe(listener: () => void): () => void;\n getSnapshot(): SkailifySnapshot;\n /** Adds a line to the activity log, for events of the app's own */\n log(entry: Omit<ActivityEntry, \"id\" | \"at\">): void;\n}\n\n/** The longest a call may wait for the view to settle */\nexport const MAX_WAIT_MS = 10_000;\n\n/**\n * The embedding host's origin, or null when the app is not embedded in Skaile. Read once at start: the app's own\n * navigation may drop the query parameter, and every reconnect needs it.\n */\nexport function skaileParentOrigin(windowRef: WindowLike | undefined = globalThis as unknown as WindowLike): string | null {\n if (!windowRef?.location || !windowRef.parent || windowRef.parent === windowRef) return null;\n const origin = new URLSearchParams(windowRef.location.search).get(PARENT_ORIGIN_QUERY_PARAM);\n return origin && origin !== \"*\" && origin !== \"null\" ? origin : null;\n}\n\n/**\n * Resolves after the browser had a chance to render: the next frame, or after {@link RENDER_FALLBACK_MS} when no frame\n * comes. Browsers pause animation frames in background tabs and hidden iframes, so a frame alone could wait forever.\n */\nfunction afterRender(): Promise<void> {\n return new Promise((resolve) => {\n const raf = (globalThis as { requestAnimationFrame?: (cb: () => void) => number }).requestAnimationFrame;\n setTimeout(() => {\n if (!raf) return resolve();\n const fallback = setTimeout(resolve, RENDER_FALLBACK_MS);\n raf(() => {\n clearTimeout(fallback);\n resolve();\n });\n }, 0);\n });\n}\n\n/** What stands in for state that JSON cannot carry (a BigInt, a cycle) */\nexport const NOT_SERIALISABLE = { error: \"state is not JSON-serialisable\" } as const;\n\n/** The value itself when JSON can carry it, else {@link NOT_SERIALISABLE}: one bad value never fails a whole answer. */\nexport function jsonSafe(value: unknown): unknown {\n try {\n JSON.stringify(value);\n return value;\n } catch {\n return NOT_SERIALISABLE;\n }\n}\n\n/** How long to wait for an animation frame before treating the page as rendered */\nconst RENDER_FALLBACK_MS = 50;\n\n/** The longest agent-visible name the gateway registers, `app.<appId>.<name>` */\nexport const MAX_AGENT_NAME_CHARS = 64;\n\n/** Marks a capability whose handler waits for the view itself, so the wrapper does not wait a second time. */\nexport const SETTLES_ITSELF: unique symbol = Symbol(\"skailify.settlesItself\");\n\nfunction describe(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction summarize(value: unknown, max = 120): string | undefined {\n if (value === undefined) return undefined;\n let text: string;\n try {\n text = typeof value === \"string\" ? value : JSON.stringify(value);\n } catch {\n return undefined;\n }\n return text.length > max ? `${text.slice(0, max - 1)}…` : text;\n}\n\nexport function createSkailify(options: SkailifyOptions): Skailify {\n const baseLogger = options.logger ?? consoleLogger;\n // The SDK says it has given up reconnecting only through its logger; turn that into a status.\n const logger: AppLogger = {\n ...baseLogger,\n error(message: string, fields?: Record<string, unknown>) {\n baseLogger.error(message, fields);\n if (!closed && (message === \"app reconnect gave up\" || message === \"app reconnect refused permanently\")) {\n setStatus({ state: \"error\", message: message.replace(/^app /, \"\") });\n log({ direction: \"out\", label: \"connection lost\", detail: message, error: true });\n }\n },\n };\n const zone = options.zone ?? { inside: <T>(fn: () => T) => fn(), outside: <T>(fn: () => T) => fn() };\n const settleTimeout = Math.min(options.settleTimeoutMs ?? 3000, MAX_WAIT_MS);\n const activityLimit = options.activityLimit ?? 40;\n const fullName = (name: string) => `app.${name}`;\n const agentName = (name: string) => `app.${options.appId}.${name}`;\n\n let app: SkaileApp | null = null;\n let started: Promise<void> | null = null;\n let closed = false;\n // The hints the next ping carries, and the host to send a change to once connecting\n let assistant = options.assistant;\n let hostOrigin: string | null = null;\n\n // ── Snapshot for the UI ───────────────────────────────────────────────────\n let status: ConnectionStatus = { state: \"idle\" };\n let activity: ActivityEntry[] = [];\n let activitySeq = 0;\n let capabilityInfo: CapabilityInfo[] = [];\n let snapshot: SkailifySnapshot = { status, activity, capabilities: capabilityInfo };\n const listeners = new Set<() => void>();\n const emit = () => {\n snapshot = { status, activity, capabilities: capabilityInfo };\n for (const listener of [...listeners]) listener();\n };\n const setStatus = (next: ConnectionStatus) => {\n status = next;\n emit();\n };\n const log = (entry: Omit<ActivityEntry, \"id\" | \"at\">) => {\n activity = [{ ...entry, id: ++activitySeq, at: Date.now() }, ...activity].slice(0, activityLimit);\n emit();\n };\n\n // ── Views and state ───────────────────────────────────────────────────────\n let viewSeq = 0;\n /** Each view with its order: the view rendered last is the one on screen. */\n const views = new Map<number, { view: ViewRegistration; order: number }>();\n const states = new Map<number, { name: string; read: () => unknown }>();\n const viewListeners = new Set<() => void>();\n // A view removed and re-added in one render (React's double mount in development, an Angular component re-created in\n // one change detection) is reported once, after it\n let reportQueued = false;\n const viewChanged = () => {\n for (const listener of [...viewListeners]) listener();\n if (reportQueued) return;\n reportQueued = true;\n queueMicrotask(() => {\n reportQueued = false;\n reportIfChanged();\n });\n };\n\n function currentView(): ViewRegistration | null {\n let top: { view: ViewRegistration; order: number } | undefined;\n for (const entry of views.values()) if (!top || entry.order > top.order) top = entry;\n if (top) return top.view;\n const id = options.navigation?.current?.();\n if (!id) return null;\n const descriptor = options.navigation?.views().find((v) => v.id === id);\n return { id, title: descriptor?.title };\n }\n\n function readState(): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const { name, read } of states.values()) {\n try {\n out[name] = jsonSafe(read());\n } catch (error) {\n out[name] = { error: describe(error) };\n }\n }\n return out;\n }\n\n const loading = () => [...views.values()].some((v) => v.view.loading === true);\n /** Effects running now: while one runs, the view is not settled even when no view is loading */\n let inFlight = 0;\n const busy = () => inFlight > 0 || loading();\n\n /** What goes out in `view_report`; the app id stands in when no view is known, since the report needs one. */\n function report(): AppViewReport {\n const view = currentView();\n return view ? { viewId: view.id, title: view.title, state: view.state } : { viewId: options.appId };\n }\n\n // The SDK keeps the last report and phase while disconnected and replays them on every bind, so they are sent\n // whether or not a session is bound: what the platform sees after a reconnect is then what is true now.\n let lastReport = \"\";\n const unserialisableLogged = new Set<string>();\n let sentLoading = false;\n /**\n * Reports the view when it changed (always with `force`), and says `loading` when the app becomes busy and `settled`\n * when it stops (with `force`, whenever it is not busy).\n */\n function reportIfChanged(force = false): void {\n if (!app) return;\n let next = report();\n let key: string;\n try {\n key = JSON.stringify(next);\n } catch (error) {\n // a BigInt or a cycle in the view's state: report the view without it, and say why (once per view)\n if (!unserialisableLogged.has(next.viewId)) {\n unserialisableLogged.add(next.viewId);\n logger.error(`skailify: the state of view ${next.viewId} is not JSON-serialisable`, { message: describe(error) });\n }\n next = { viewId: next.viewId, title: next.title, state: NOT_SERIALISABLE };\n key = JSON.stringify(next);\n }\n if (force || key !== lastReport) {\n lastReport = key;\n try {\n app.reportView(next);\n } catch (error) {\n logger.error(\"skailify: could not report the view\", { message: describe(error) });\n }\n }\n const now = busy();\n if (now && !sentLoading) {\n sentLoading = true;\n app.loading(\"view loading\");\n } else if (!now && (sentLoading || force)) {\n sentLoading = false;\n app.settled();\n }\n }\n\n function settle(timeoutMs = settleTimeout): Promise<boolean> {\n const limit = Math.min(Math.max(timeoutMs, 0), MAX_WAIT_MS);\n return zone.outside(() => new Promise<boolean>((resolve) => {\n let finished = false;\n let rendered = false;\n const finish = (settled: boolean) => {\n if (finished) return;\n finished = true;\n clearTimeout(timer);\n viewListeners.delete(check);\n // The report may not have changed, but the agent waits for this settled. While the app is still busy (a view\n // loading at the timeout, another effect running) it is not sent: it goes out when the app stops being busy.\n reportIfChanged(true);\n resolve(settled);\n };\n const check = () => {\n if (rendered && !loading()) finish(true);\n };\n // the deadline covers the wait for the render too\n const timer = setTimeout(() => finish(!loading()), limit);\n viewListeners.add(check);\n void Promise.resolve()\n .then(() => options.rendered?.())\n .catch(() => undefined)\n .then(afterRender)\n .then(() => {\n rendered = true;\n check();\n });\n }));\n }\n\n // ── Capabilities ──────────────────────────────────────────────────────────\n let actionSeq = 0;\n /** Registered actions in order; a later one with the same name wins. */\n const actions = new Map<number, AgentAction>();\n const defined = new WeakMap<AgentAction, DefinedAppCapability | null>();\n let registered = new Map<string, DefinedAppCapability>();\n\n /** Wraps the handler: logs the call, and after an effect waits for the view to settle. */\n function define(action: AgentAction): DefinedAppCapability | null {\n if (defined.has(action)) return defined.get(action) ?? null;\n const name = fullName(action.name);\n const isEffect = (action.kind ?? \"effect\") === \"effect\";\n const settlesItself = (action as { [SETTLES_ITSELF]?: boolean })[SETTLES_ITSELF] === true;\n let capability: DefinedAppCapability | null;\n try {\n if (agentName(action.name).length > MAX_AGENT_NAME_CHARS) {\n throw new Error(`${agentName(action.name)} is longer than ${MAX_AGENT_NAME_CHARS} characters, the gateway would drop it`);\n }\n capability = defineAppCapability({\n ...action,\n name,\n handler: async (args: unknown, ctx: AppHandlerContext) => {\n log({ direction: \"in\", label: action.name, detail: summarize(args) });\n if (isEffect) {\n inFlight++;\n sentLoading = true;\n app?.loading(action.name);\n }\n try {\n const result = await zone.inside(() => action.handler(args, ctx));\n log({ direction: \"out\", label: action.name, detail: summarize(result) });\n return result;\n } catch (error) {\n log({ direction: \"out\", label: action.name, detail: describe(error), error: true });\n throw error;\n } finally {\n if (isEffect) {\n inFlight--;\n if (settlesItself) reportIfChanged(true);\n else await settle();\n }\n }\n },\n } as DefineAppCapabilityArgs<z.ZodTypeAny, z.ZodTypeAny | undefined>);\n } catch (error) {\n // the SDK refuses what the gateway would refuse (an effect class above routine without approval)\n logger.error(`skailify: ${name} not registered: ${describe(error)}`, { name });\n capability = null;\n }\n defined.set(action, capability);\n return capability;\n }\n\n const generic: AgentAction[] = [];\n\n function sync(): void {\n const now = new Map<string, DefinedAppCapability>();\n for (const action of [...generic, ...actions.values()]) {\n const capability = define(action);\n if (capability) now.set(capability.name, capability);\n }\n capabilityInfo = [...now.values()].map((c) => ({\n name: c.name,\n agentName: agentName(c.name.slice(4)),\n displayName: c.displayName,\n description: c.description,\n kind: c.kind,\n requiresApproval: c.requiresApproval,\n effectClass: c.effectClass,\n }));\n wanted = now;\n emit();\n // An action removed and re-added in one render (a double mount, a re-created component): send the difference once, after it\n if (wireQueued) return;\n wireQueued = true;\n queueMicrotask(flushWire);\n }\n\n let wanted = new Map<string, DefinedAppCapability>();\n let wireQueued = false;\n function flushWire(): void {\n wireQueued = false;\n if (!app) return;\n const before = registered;\n registered = wanted;\n for (const name of before.keys()) if (!wanted.has(name)) app.deregisterCapability(name);\n for (const [name, capability] of wanted) if (before.get(name) !== capability) app.registerCapability(capability);\n }\n\n // ── Connection ────────────────────────────────────────────────────────────\n async function connect(transport: AppTransport): Promise<void> {\n app = createSkaileApp({ appId: options.appId, transport, logger, reconnect: options.reconnect });\n handle.app = app;\n registered = new Map();\n sync();\n flushWire();\n reportIfChanged(true);\n app.onSessionChange((session: AppSession | null) => {\n if (session) {\n // the SDK replays the last report and phase on a bind; they are kept current while disconnected\n setStatus({ state: \"connected\", sessionId: session.sessionId, userId: session.userId });\n log({ direction: \"out\", label: \"connected\", detail: `session ${session.sessionId}` });\n } else if (!closed) {\n log({ direction: \"out\", label: \"disconnected\" });\n setStatus(options.reconnect === false ? { state: \"error\", message: \"connection lost\" } : { state: \"reconnecting\" });\n }\n });\n if (closed) {\n await app.close();\n return;\n }\n await app.connect();\n }\n\n async function run(): Promise<void> {\n if (closed) return;\n if (options.enabled === false) {\n setStatus({ state: \"standalone\" });\n return;\n }\n if (options.transport) {\n setStatus({ state: \"connecting\" });\n return connect(options.transport);\n }\n const parentOrigin = skaileParentOrigin(options.windowRef);\n if (!parentOrigin) {\n setStatus({ state: \"standalone\" });\n return;\n }\n hostOrigin = parentOrigin;\n const resolve =\n options.resolveParams ??\n ((appId: string, origin: string, presentation?: AppAssistantPresentation) =>\n resolveAppConnectionParams({ appId, parentOrigin: origin, ...(presentation ? { assistant: presentation } : {}) }));\n // Each ping carries the assistant hints; a change made while one was in flight is sent again once it is answered.\n const resolveParams = async (appId: string, origin: string): Promise<AppConnectionParams> => {\n const sent = assistant;\n const params = await resolve(appId, origin, sent);\n if (assistant !== sent && assistant && !closed) postAssistant(assistant);\n return params;\n };\n const createTransport =\n options.createTransport ?? ((url: string, sessionToken: SessionTokenProvider) => createWebSocketAppTransport({ url, sessionToken }));\n setStatus({ state: \"connecting\" });\n // The first token comes with the url; every reconnect asks the host for a fresh one: the gateway burns it at app_hello.\n let primed: AppConnectionParams | null = await resolveParams(options.appId, parentOrigin);\n if (closed) return;\n const transport = createTransport(primed.url, () => {\n if (primed) {\n const token = primed.token;\n primed = null;\n return token;\n }\n return resolveParams(options.appId, parentOrigin).then((params) => params.token);\n });\n return connect(transport);\n }\n\n function postAssistant(presentation: AppAssistantPresentation): void {\n if (!hostOrigin) return;\n try {\n (options.postAssistant ?? ((appId, parentOrigin, p) => setAssistantPresentation({ appId, parentOrigin, presentation: p })))(\n options.appId,\n hostOrigin,\n presentation,\n );\n } catch (error) {\n logger.warn(\"skailify: could not send the assistant hints\", { message: describe(error) });\n }\n }\n\n const handle: Skailify & { app: SkaileApp | null } = {\n appId: options.appId,\n app: null,\n start() {\n if (!started) {\n started = zone.outside(run).catch((error: unknown) => {\n if (closed) return;\n const message = describe(error);\n logger.error(\"skailify: could not connect to Skaile\", { message });\n setStatus({ state: \"error\", message });\n log({ direction: \"out\", label: \"connect failed\", detail: message, error: true });\n });\n }\n return started;\n },\n setAssistant(presentation) {\n assistant = presentation;\n if (started && !closed) postAssistant(presentation);\n },\n async close() {\n closed = true;\n await app?.close();\n setStatus({ state: \"closed\" });\n },\n registerAction(added) {\n const action = added as unknown as AgentAction;\n if (action.name.startsWith(\"app.\")) {\n throw new Error(`skailify: action names are relative, write \"${action.name.slice(4)}\" instead of \"${action.name}\"`);\n }\n // a later registration with the same name wins; when it is removed, the earlier one is offered again\n const key = ++actionSeq;\n actions.set(key, action);\n sync();\n return () => {\n if (actions.delete(key)) sync();\n };\n },\n viewOrder: () => ++viewSeq,\n registerView(view, order) {\n const key = ++viewSeq;\n const entry = { view, order: order ?? key };\n views.set(key, entry);\n viewChanged();\n return {\n update(next) {\n if (!views.has(key)) return;\n views.set(key, { view: next, order: entry.order });\n viewChanged();\n },\n remove() {\n if (views.delete(key)) viewChanged();\n },\n };\n },\n registerState(name, read) {\n const key = ++viewSeq;\n states.set(key, { name, read });\n return () => {\n states.delete(key);\n };\n },\n currentView,\n readState,\n agentName,\n loading,\n settle,\n fullName,\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n getSnapshot: () => snapshot,\n log,\n };\n\n generic.push(...genericCapabilities(handle, options.navigation));\n sync();\n return handle;\n}\n","// SPDX-License-Identifier: Apache-2.0\n\n/**\n * The generic capabilities every app gets: read what the user sees, and,\n * when the app hands in its navigation, list the views and show one. They are\n * router-agnostic: the app says what its views are and how to show one.\n */\nimport * as z from \"zod\";\nimport { type AgentAction, agentAction, jsonSafe, SETTLES_ITSELF, type Skailify } from \"./client.ts\";\n\n/** A view (page, screen) of the app, as the agent sees it in `list_views`. */\nexport interface ViewDescriptor {\n /** The id `navigate` takes */\n id: string;\n title?: string;\n /** false for views reached only from another view; default true */\n menu?: boolean;\n /** Parameters the view takes in `navigate`, e.g. `{ cardId: \"the card to open\" }` */\n params?: Record<string, string>;\n}\n\n/** How the agent finds and shows the app's views. Wire it to your router, or to whatever shows a view in the app. */\nexport interface Navigation {\n /** The app's views; called on every request, so it always answers the current set */\n views: () => ViewDescriptor[];\n /** Shows a view. May return before the view has rendered: the client waits for it to settle. */\n navigate: (viewId: string, params: Record<string, string>) => void | Promise<void>;\n /** The id of the view on screen, for apps whose views do not register themselves */\n current?: () => string | undefined;\n}\n\n/** What `get_view_state` and `navigate` answer. */\nexport interface ViewState {\n view: { id: string; title?: string; state?: unknown } | null;\n /** What the app exposes with `registerState`, by name */\n state: Record<string, unknown>;\n /** The actions available now, by the name the agent calls them (`app.<appId>.<name>`) */\n actions: string[];\n /** false when a view was still loading when the wait timed out: read again */\n settled: boolean;\n}\n\nexport function viewState(client: Skailify, settled: boolean): ViewState {\n const view = client.currentView();\n return {\n view: view ? { id: view.id, title: view.title, state: jsonSafe(view.state) } : null,\n state: client.readState(),\n actions: client.getSnapshot().capabilities.map((c) => c.agentName),\n settled: settled && !client.loading(),\n };\n}\n\nconst settledNote =\n \"When settled is false a view was still loading when the wait timed out: the state may be incomplete, so read it again with get_view_state.\";\n\nexport function genericCapabilities(client: Skailify, navigation: Navigation | undefined): AgentAction[] {\n const name = client.agentName;\n const generic: AgentAction[] = [\n agentAction({\n name: \"get_view_state\",\n displayName: \"Read what the user sees\",\n description:\n `Read the current state of the ${client.appId} app: the view on screen (id, title and a summary of what it shows), ` +\n \"the state the app exposes to agents, and the actions available now. Call this first, and again after acting. \" +\n `It waits until no view is loading. ${settledNote}`,\n kind: \"query\",\n input: z.object({\n timeoutMs: z.number().int().min(0).optional().describe(\"How long to wait at most for a loading view, in ms\"),\n }),\n handler: async ({ timeoutMs }) => viewState(client, await client.settle(timeoutMs)),\n }),\n ];\n if (!navigation) return generic;\n\n generic.push(\n agentAction({\n name: \"list_views\",\n displayName: \"List the views\",\n description:\n `List the views (pages) of the ${client.appId} app: id, title, whether it is in the menu, and the parameters it takes. ` +\n `Use the id with ${name(\"navigate\")}.`,\n kind: \"query\",\n input: z.object({}),\n handler: async () => ({ current: client.currentView()?.id ?? null, views: navigation.views() }),\n }),\n // navigate waits for the view itself, to answer the state after it; the wrapper must not wait a second time\n {\n ...agentAction({\n name: \"navigate\",\n displayName: \"Show a view\",\n description:\n `Show a view of the app, with the parameters it takes (see ${name(\"list_views\")}). ` +\n `Waits until the view has loaded, then returns the view state. ${settledNote}`,\n kind: \"effect\",\n input: z.object({\n view: z.string().describe(\"View id from list_views\"),\n params: z.record(z.string(), z.string()).optional().describe(\"Parameters of the view, by name\"),\n }),\n handler: async ({ view, params }) => {\n const views = navigation.views();\n if (!views.some((v) => v.id === view)) {\n throw new Error(`no view ${view}; views: ${views.map((v) => v.id).join(\", \") || \"none\"}`);\n }\n await navigation.navigate(view, params ?? {});\n return viewState(client, await client.settle());\n },\n }),\n [SETTLES_ITSELF]: true,\n },\n );\n return generic;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAqEA,SAAgB,YAAoF,QAAwC;CAC1I,OAAO;AACT;;AAoIA,MAAa,cAAc;;;;;AAM3B,SAAgB,mBAAmB,YAAoC,YAAoD;CACzH,IAAI,CAAC,WAAW,YAAY,CAAC,UAAU,UAAU,UAAU,WAAW,WAAW,OAAO;CACxF,MAAM,SAAS,IAAI,gBAAgB,UAAU,SAAS,MAAM,CAAC,CAAC,IAAI,yBAAyB;CAC3F,OAAO,UAAU,WAAW,OAAO,WAAW,SAAS,SAAS;AAClE;;;;;AAMA,SAAS,cAA6B;CACpC,OAAO,IAAI,SAAS,YAAY;EAC9B,MAAM,MAAO,WAAsE;EACnF,iBAAiB;GACf,IAAI,CAAC,KAAK,OAAO,QAAQ;GACzB,MAAM,WAAW,WAAW,SAAS,kBAAkB;GACvD,UAAU;IACR,aAAa,QAAQ;IACrB,QAAQ;GACV,CAAC;EACH,GAAG,CAAC;CACN,CAAC;AACH;;AAGA,MAAa,mBAAmB,EAAE,OAAO,iCAAiC;;AAG1E,SAAgB,SAAS,OAAyB;CAChD,IAAI;EACF,KAAK,UAAU,KAAK;EACpB,OAAO;CACT,QA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