@supersolutions/super-chat-client 0.0.0 → 0.2.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,"sources":["../src/client.ts","../src/store.ts"],"sourcesContent":["// AgentClient — the framework-agnostic controller the React hooks wrap.\n//\n// It owns: the thread, the current run, pending user decisions, and background\n// jobs. Kept outside React so the same object can be driven from a test, a CLI,\n// or a non-React host — the hooks are a thin `useSyncExternalStore` over it.\n\nimport {\n initialRunState,\n reduceRunEvent,\n runAgent,\n resumeJobs,\n type Card,\n type CardAction,\n type ContentPart,\n type ContextBuilder,\n type JobStore,\n type Message,\n type Provider,\n type RunConfig,\n type RunEvent,\n type RunMode,\n type RunState,\n type StoredJob,\n type ThreadMeta,\n type ThreadStore,\n type ToolCallRequest,\n type ToolRegistry,\n type ToolResolution,\n assistantMessage,\n latestLeaf,\n linkLinear,\n nextId,\n pathTo,\n siblingsOf,\n threadSnapshot,\n userMessage,\n withQuotes,\n formatQuotes,\n checkQuoteDrift,\n QUOTES_METADATA_KEY,\n type DocumentQuoteRef,\n type DocumentStore,\n type CardRegistry,\n type SurfaceAction,\n type SurfaceActivity,\n type SurfaceActivityState,\n type SurfaceCardAnswer,\n type SurfaceCatalogue,\n type SurfaceComponent,\n type SurfaceEventRecord,\n type SurfaceSpec,\n SURFACE_EVENT_METADATA_KEY,\n SURFACE_LIMITS,\n SurfaceLedger,\n authorizeSurfaceTool,\n evaluateSurfaceCondition,\n foldSurfaces,\n getAt,\n isSurfaceSpec,\n resolveSurfaceAction,\n runSurfaceToolAction,\n setAt,\n stripCardPayload,\n surfaceCardId,\n} from \"@supersolutions/super-chat-core\";\nimport { Store } from \"./store.js\";\n\nexport type ThreadState = {\n id: string;\n /**\n * The ACTIVE PATH — root to head — which is what the UI renders and a run\n * consumes. Always derived from `tree` + `headId`; treat as read-only.\n */\n messages: Message[];\n /**\n * Every message ever sent in this thread, abandoned branches included.\n * Replaced on every change, never mutated in place — `useBranches` caches\n * its sibling index per array. Treat as read-only.\n */\n tree: Message[];\n /** Leaf of the active branch. */\n headId: string | null;\n run: RunState;\n /** Cards from the CURRENT run; committed to messages when the run finishes. */\n cards: Card[];\n jobs: StoredJob[];\n /** Parts staged for the NEXT send (file/image attachments). Thread-scoped. */\n attachments: ContentPart[];\n status: RunState[\"status\"];\n error?: unknown;\n /**\n * A stop was requested but the run has not unwound yet.\n *\n * Needed because `stop()` only aborts a signal — a tool that ignores its\n * signal keeps running, and without this the UI cannot distinguish \"stopping\"\n * from \"the button did nothing\".\n */\n stopping?: boolean;\n /** Current state of each surface on the active path, the person's edits included. */\n surfaces: Record<string, SurfaceSpec>;\n /** What became of the last action pressed on each surface. */\n surfaceActivity: Record<string, SurfaceActivity>;\n};\n\n/** What a finished turn cost, attached to the committed message. */\nexport type TurnMeta = {\n model: string;\n ms: number;\n usage?: RunState[\"usage\"];\n steps?: number;\n /** Set when a person's button press produced this turn rather than a model. */\n origin?: \"surface-action\";\n};\n\nexport type AgentClientConfig = {\n provider: Provider;\n model: string;\n contextBuilder: ContextBuilder;\n tools: ToolRegistry;\n toolResolution: ToolResolution;\n mode?: RunMode;\n maxSteps?: number;\n vars?: Record<string, unknown>;\n temperature?: number;\n maxOutputTokens?: number;\n reasoning?: RunConfig[\"reasoning\"];\n // Full RunConfig surface — a React host must not get LESS control than a\n // direct runAgent caller.\n stopWhen?: RunConfig[\"stopWhen\"];\n toolTimeoutMs?: number;\n useServerHistory?: boolean;\n toolChoice?: RunConfig[\"toolChoice\"];\n providerTools?: RunConfig[\"providerTools\"];\n responseFormat?: RunConfig[\"responseFormat\"];\n topP?: number;\n stopSequences?: string[];\n store?: boolean;\n metadata?: Record<string, string>;\n providerOptions?: RunConfig[\"providerOptions\"];\n meter?: RunConfig[\"meter\"];\n meteringMetadata?: RunConfig[\"meteringMetadata\"];\n jobStore?: JobStore;\n /** When set, the thread is saved after each user and assistant turn. */\n threadStore?: ThreadStore;\n onHostTool?: (call: ToolCallRequest) => Promise<unknown>;\n /** Persisted thread to hydrate from (linear list or a parentId tree). */\n initialMessages?: Message[];\n /** Active-branch leaf when `initialMessages` is a tree. Default: last message. */\n initialHeadId?: string | null;\n threadId?: string;\n /**\n * Where quoted documents can be looked up at send time, to catch a quote\n * taken from a revision the document has since moved past. Only `get` is\n * used; a host whose store lives on a server can pass a fetch-backed one.\n * Unset, quotes are sent as taken.\n */\n documentStore?: Pick<DocumentStore, \"get\">;\n /** The card registry in use, so the UI can ask it which kinds are interactive. */\n cards?: CardRegistry;\n /** The surface catalogue in use, so the renderer validates against what the tools accept. */\n surfaceCatalogue?: SurfaceCatalogue;\n};\n\n/** How long local edits gather before they are written into the thread and saved. */\nconst SURFACE_SAVE_DELAY_MS = 300;\nconst SURFACE_QUEUE_LIMIT = 8;\nconst SURFACE_CONTEXT_CHARS = 4_000;\n\ntype QueuedSurfaceAction = { spec: SurfaceSpec; component: SurfaceComponent; action: Exclude<SurfaceAction, { type: \"set\" }> };\n\n/** A card waiting on the user, with the resolver that unblocks the run. */\ntype PendingDecision = { card: Card; resolve: (action: CardAction) => void };\n\nexport class AgentClient {\n readonly store: Store<ThreadState>;\n private config: AgentClientConfig;\n private controller: AbortController | null = null;\n private pending = new Map<string, PendingDecision>();\n /** Meta of the last snapshot saved, so createdAt/title survive re-saves. */\n private threadMeta: ThreadMeta | undefined;\n /**\n * Bumped by every thread switch. A run captures the value it started under\n * and stops writing to the store the moment they diverge — so a run dying\n * from `openThread()`'s stop() cannot leak its error/status/commit into the\n * thread the user just opened.\n */\n private generation = 0;\n /** Wall-clock start of the current turn, for the committed TurnMeta. */\n private turnStartedAt = 0;\n /** The current run's view of the surfaces, kept level with the person's edits. */\n private surfaceLedger: SurfaceLedger | null = null;\n private dirtySurfaces = new Set<string>();\n private surfaceSaveTimer: ReturnType<typeof setTimeout> | null = null;\n /** Actions pressed while a run was busy. One run at a time, so they wait their turn. */\n private surfaceQueue: QueuedSurfaceAction[] = [];\n\n constructor(config: AgentClientConfig) {\n this.config = config;\n // `initialMessages` may be a plain linear list (pre-branching hosts) or a\n // tree with parentIds (a v2 snapshot); linkLinear handles both.\n const tree = linkLinear(config.initialMessages ?? []);\n const headId = config.initialHeadId ?? tree.at(-1)?.id ?? null;\n const messages = pathTo(tree, headId);\n this.store = new Store<ThreadState>({\n id: config.threadId ?? nextId(\"thread\"),\n messages,\n tree,\n headId,\n run: initialRunState(\"\", config.mode ?? \"stream\"),\n cards: [],\n jobs: [],\n attachments: [],\n status: \"idle\",\n surfaces: foldSurfaces(messages),\n surfaceActivity: {},\n });\n }\n\n /**\n * Append under `parent` (default: the current head) and move the head there.\n *\n * `extra` merges into the SAME `store.set()` — e.g. clearing `attachments`\n * alongside the append — so a caller touching both fields does not force two\n * notifications for one logical change.\n */\n private appendMessage(message: Message, parent?: string | null, extra?: Partial<ThreadState>): void {\n this.store.set((s) => {\n const parentId = parent !== undefined ? parent : s.headId;\n const linked: Message = { ...message, parentId };\n const tree = [...s.tree, linked];\n return { ...s, tree, headId: linked.id, messages: pathTo(tree, linked.id), ...extra };\n });\n }\n\n /**\n * Stage a part (a file/image the host uploaded) for the next send. The\n * Composer only carries text; this is how binary content joins the turn.\n */\n attach(part: ContentPart): void {\n this.store.set((s) => ({ ...s, attachments: [...s.attachments, part] }));\n }\n\n removeAttachment(index: number): void {\n this.store.set((s) => ({ ...s, attachments: s.attachments.filter((_, i) => i !== index) }));\n }\n\n clearAttachments(): void {\n this.store.set((s) => (s.attachments.length ? { ...s, attachments: [] } : s));\n }\n\n /** Update config in place (model switch, preset toggle) without losing the thread. */\n configure(patch: Partial<AgentClientConfig>): void {\n this.config = { ...this.config, ...patch };\n }\n\n getConfig(): AgentClientConfig {\n return this.config;\n }\n\n get isRunning(): boolean {\n const { status } = this.store.get();\n return status === \"running\" || status === \"awaiting-user\";\n }\n\n /**\n * Append a user message (plus any staged attachments) and run a turn.\n *\n * `quotes` are spans the user highlighted in a document artifact. They are\n * flattened into the message's own text rather than injected as context, and\n * the reasoning is in content/quotes.ts: a quote is part of what the user\n * SAID, so it must not go stale between turns and must not be droppable\n * under budget pressure. The structured form rides on `metadata`, which never\n * reaches a provider, so the chips can be re-rendered from history.\n *\n * With a `documentStore` configured, each quote is first checked against the\n * document as it is now, and a quote taken from an older revision goes out\n * with its drift — in the text, so the model re-reads, and in the metadata,\n * so the UI can say so.\n */\n async send(\n input: string | ContentPart[],\n opts: { forceSkillIds?: string[]; quotes?: readonly DocumentQuoteRef[] } = {},\n ): Promise<void> {\n if (this.isRunning) throw new Error(\"A run is already in progress. Call stop() first.\");\n const { documentStore } = this.config;\n const gen = this.generation;\n const quotes =\n opts.quotes?.length && documentStore ? await checkQuoteDrift(opts.quotes, documentStore) : (opts.quotes ?? []);\n // The drift lookup is an await, and a second send could have started in it.\n if (this.isRunning) throw new Error(\"A run is already in progress. Call stop() first.\");\n // The user opened or started another thread while the drift lookup was out: the text they\n // typed belongs to the thread they left, and appending it to this one would be worse than\n // dropping it.\n if (gen !== this.generation) return;\n const staged = this.store.get().attachments;\n const quoted: string | ContentPart[] =\n quotes.length === 0\n ? input\n : typeof input === \"string\"\n ? withQuotes(input, quotes)\n : [{ type: \"text\", text: formatQuotes(quotes) } as ContentPart, ...input];\n const parts: ContentPart[] = typeof quoted === \"string\" ? [{ type: \"text\", text: quoted }] : [...quoted];\n const base = userMessage(staged.length ? [...parts, ...staged] : quoted);\n const message: Message = quotes.length\n ? { ...base, metadata: { ...base.metadata, [QUOTES_METADATA_KEY]: quotes } }\n : base;\n this.appendMessage(message, undefined, { attachments: [] });\n // Persist the user turn before running — a reload mid-run keeps it.\n this.persist();\n await this.run([...this.store.get().messages], opts);\n }\n\n /**\n * Re-run from the last user message. A FORK, not a rewrite: the head moves\n * back to that user message and the new answer grows as a sibling of the\n * old one, which stays switchable via `switchBranch`.\n */\n async regenerate(opts: { forceSkillIds?: string[] } = {}): Promise<void> {\n if (this.isRunning) throw new Error(\"A run is already in progress.\");\n const { messages } = this.store.get();\n for (let i = messages.length - 1; i >= 0; i -= 1) {\n const m = messages[i]!;\n if (m.role === \"user\") {\n this.flushSurfaceWrites();\n this.store.set((s) => onPath({ ...s, headId: m.id, messages: pathTo(s.tree, m.id) }));\n await this.run([...this.store.get().messages], opts);\n return;\n }\n }\n }\n\n /**\n * Edit a user message: a SIBLING fork under the same parent, preserving the\n * original and everything under it. The edited branch runs immediately.\n */\n async editMessage(messageId: string, input: string | ContentPart[], opts: { forceSkillIds?: string[] } = {}): Promise<void> {\n if (this.isRunning) throw new Error(\"A run is already in progress.\");\n const original = this.store.get().tree.find((m) => m.id === messageId);\n if (!original || original.role !== \"user\") return;\n this.flushSurfaceWrites();\n this.appendMessage(userMessage(input), original.parentId ?? null);\n this.store.set(onPath);\n this.persist();\n await this.run([...this.store.get().messages], opts);\n }\n\n /**\n * Move the active branch to a SIBLING of `messageId` (delta −1/+1 in\n * insertion order), resuming at that branch's latest leaf.\n */\n switchBranch(messageId: string, delta: number): void {\n if (this.isRunning) return; // switching under a live run would cross-write threads of the same id\n const s = this.store.get();\n const siblings = siblingsOf(s.tree, messageId);\n if (siblings.length < 2) return;\n const index = siblings.findIndex((m) => m.id === messageId);\n const next = siblings[(index + delta + siblings.length) % siblings.length]!;\n const headId = latestLeaf(s.tree, next.id);\n this.flushSurfaceWrites();\n this.store.set((prev) => onPath({ ...prev, headId, messages: pathTo(prev.tree, headId) }));\n this.persist();\n }\n\n private async run(messages: Message[], opts: { forceSkillIds?: string[] }): Promise<void> {\n const gen = this.generation;\n this.flushSurfaceWrites();\n const surfaces = new SurfaceLedger(this.store.get().surfaces);\n this.surfaceLedger = surfaces;\n this.controller = new AbortController();\n const mode = this.config.mode ?? \"stream\";\n this.turnStartedAt = Date.now();\n this.store.set((s) => ({\n ...s,\n run: initialRunState(nextId(\"run\"), mode),\n cards: [],\n status: \"running\",\n error: undefined,\n stopping: false,\n }));\n\n const runConfig: RunConfig = {\n provider: this.config.provider,\n model: this.config.model,\n contextBuilder: this.config.contextBuilder,\n tools: this.config.tools,\n toolResolution: this.config.toolResolution,\n mode,\n maxSteps: this.config.maxSteps,\n vars: this.config.vars,\n temperature: this.config.temperature,\n maxOutputTokens: this.config.maxOutputTokens,\n reasoning: this.config.reasoning,\n stopWhen: this.config.stopWhen,\n toolTimeoutMs: this.config.toolTimeoutMs,\n useServerHistory: this.config.useServerHistory,\n toolChoice: this.config.toolChoice,\n providerTools: this.config.providerTools,\n responseFormat: this.config.responseFormat,\n topP: this.config.topP,\n stopSequences: this.config.stopSequences,\n store: this.config.store,\n metadata: this.config.metadata,\n providerOptions: this.config.providerOptions,\n meter: this.config.meter,\n meteringMetadata: this.config.meteringMetadata,\n signal: this.controller.signal,\n forceSkillIds: opts.forceSkillIds,\n onHostTool: this.config.onHostTool,\n surfaces,\n // Suspend the run on an interactive card; `respond()` resolves it.\n onUserDecision: this.awaitDecision,\n };\n\n try {\n for await (const event of runAgent(messages, runConfig)) {\n if (gen !== this.generation) return; // thread switched under us — drop the rest\n this.apply(event);\n }\n } catch (e) {\n if (gen === this.generation) this.store.set((s) => ({ ...s, status: \"error\", error: e }));\n } finally {\n this.controller = null;\n this.surfaceLedger = null;\n if (gen === this.generation) {\n this.commitRun();\n this.drainSurfaceQueue();\n }\n }\n }\n\n private awaitDecision = (callId: string, card: Card): Promise<CardAction> =>\n new Promise<CardAction>((resolve) => {\n this.pending.set(callId, { card, resolve });\n });\n\n private apply(event: RunEvent): void {\n this.store.set((s) => {\n const run = reduceRunEvent(s.run, event);\n const next: ThreadState = { ...s, run, status: run.status, cards: run.cards };\n if (event.type === \"job-started\" && this.config.jobStore) {\n const job: StoredJob = {\n handle: event.handle,\n status: \"queued\",\n threadId: s.id,\n createdAt: Date.now(),\n updatedAt: Date.now(),\n };\n // Fire and forget: persistence must not stall the run.\n void this.config.jobStore.put(job);\n next.jobs = [job, ...s.jobs];\n }\n if (event.type === \"job-status\") {\n next.jobs = s.jobs.map((j) => (j.handle.id === event.handle.id ? { ...j, status: event.status, updatedAt: Date.now() } : j));\n }\n if (event.type === \"error\") next.error = event.error;\n if (event.type === \"card\" && isSurfaceSpec(event.card.spec)) {\n next.surfaces = { ...s.surfaces, [event.card.spec.surfaceId]: event.card.spec };\n }\n return next;\n });\n }\n\n /**\n * Fold the finished run's parts into the thread as one assistant message.\n *\n * Cards are attached as artifact parts so a reloaded thread still renders\n * them — the ContextBuilder strips artifacts before they reach a provider,\n * so this costs nothing at request time.\n */\n private commitRun(origin?: TurnMeta[\"origin\"]): void {\n // Edits still gathering belong to this turn's snapshot of the surface.\n this.flushSurfaceWrites(true);\n this.store.set((s) => {\n // run.status reflects only what the agent loop itself saw, never a\n // throw caught in run()'s catch block — so a caught error must win\n // over it here, or the catch's \"error\" status gets overwritten back\n // to whatever the loop last reduced to (e.g. \"running\").\n const status = s.status === \"error\" ? \"error\" : s.run.status;\n // Streaming-argument previews are live-only. run-finish already clears\n // them; a run that died by throwing never sent one, so clear them here\n // too rather than leave a half-drawn card on an errored turn.\n const run = s.run.partialTools && Object.keys(s.run.partialTools).length ? { ...s.run, partialTools: {} } : s.run;\n const parts = run.parts;\n if (!parts.length && !run.cards.length) return { ...s, run, status };\n\n // `data` carries the answer alongside the spec: an answered card that\n // re-renders from history has to show what the user actually chose, and\n // the renderer's own state is gone by then.\n const cardParts: ContentPart[] = s.run.cards.map((c) => ({\n type: \"artifact\",\n id: c.id,\n kind: `card:${(c.spec as { kind?: string }).kind ?? \"unknown\"}`,\n data: c.spec,\n ...(c.action ? { action: c.action } : {}),\n // Where the card belongs among the turn's text.\n ...(c.callId ? { callId: c.callId } : {}),\n }));\n\n // What the turn cost, recorded on the message. The UI has no other way to\n // show it after the fact: run state is reset by the next turn.\n const meta: TurnMeta = {\n model: this.config.model,\n ms: this.turnStartedAt ? Date.now() - this.turnStartedAt : 0,\n ...(s.run.usage && Object.keys(s.run.usage).length ? { usage: s.run.usage } : {}),\n ...(s.run.steps ? { steps: s.run.steps } : {}),\n ...(origin ? { origin } : {}),\n };\n\n const linked: Message = {\n ...assistantMessage([...toolResultsInCallOrder(parts), ...cardParts]),\n parentId: s.headId,\n metadata: { turn: meta },\n };\n const tree = [...s.tree, linked];\n return {\n ...s,\n run,\n tree,\n headId: linked.id,\n messages: pathTo(tree, linked.id),\n status: s.run.status,\n stopping: false,\n };\n });\n this.persist();\n }\n\n /**\n * Fire-and-forget save, the same posture as the job store put: persistence\n * must not stall the run, and a failed save degrades to \"not saved\", never\n * to a broken thread.\n */\n private persist(): void {\n const store = this.config.threadStore;\n if (!store) return;\n const s = this.store.get();\n if (this.threadMeta && this.threadMeta.id !== s.id) this.threadMeta = undefined;\n void (async () => {\n // A client hydrated via config (threadId/initialMessages) has no meta in\n // hand; read the stored one so createdAt and title survive the reload.\n const prior = this.threadMeta ?? (await store.load(s.id))?.meta;\n // The TREE persists — abandoned branches included — plus the active head.\n const snapshot = threadSnapshot(s.id, s.tree, prior, s.headId);\n this.threadMeta = snapshot.meta;\n await store.save(snapshot);\n })().catch(() => {\n // Fire-and-forget: a failed save degrades to \"not saved\", never a crash.\n });\n }\n\n /**\n * Load a stored thread and replace the current one. Returns false when the\n * id is unknown (the current thread is left untouched).\n */\n async openThread(id: string): Promise<boolean> {\n const store = this.config.threadStore;\n if (!store) return false;\n const stored = await store.load(id);\n if (!stored) return false;\n this.saveSurfacesNow();\n this.generation += 1; // invalidate any in-flight run before replacing state\n this.stop();\n this.surfaceQueue = [];\n this.threadMeta = stored.meta;\n const tree = linkLinear(stored.messages);\n const headId = stored.headId ?? tree.at(-1)?.id ?? null;\n this.store.set((s) => onPath({\n ...s,\n id: stored.meta.id,\n tree,\n headId,\n messages: pathTo(tree, headId),\n cards: [],\n attachments: [],\n run: initialRunState(\"\", this.config.mode ?? \"stream\"),\n status: \"idle\",\n error: undefined,\n surfaceActivity: {},\n }));\n return true;\n }\n\n /** Start a fresh thread under a new id (`clear()` keeps the id; this doesn't). */\n newThread(): void {\n this.saveSurfacesNow();\n this.generation += 1;\n this.stop();\n this.surfaceQueue = [];\n this.threadMeta = undefined;\n this.store.set((s) => ({\n ...s,\n id: nextId(\"thread\"),\n messages: [],\n tree: [],\n headId: null,\n cards: [],\n attachments: [],\n run: initialRunState(\"\", this.config.mode ?? \"stream\"),\n status: \"idle\",\n error: undefined,\n surfaces: {},\n surfaceActivity: {},\n }));\n }\n\n /** Answer an interactive card. Unblocks the suspended tool. */\n respond(action: CardAction): void {\n const entry = this.pending.get(action.callId ?? \"\");\n if (!entry) return;\n this.pending.delete(action.callId ?? \"\");\n entry.resolve(action);\n }\n\n /** The card currently blocking the run, if any. */\n pendingCard(): Card | undefined {\n return this.store.get().run.pendingCard;\n }\n\n stop(): void {\n if (!this.isRunning) return;\n // Mark the request immediately. Aborting is not the same as having stopped:\n // a tool that ignores its signal runs to completion, and the UI has to be\n // able to say \"stopping\" instead of looking inert.\n this.store.set((s) => ({ ...s, stopping: true }));\n this.controller?.abort();\n // A background job keeps running (and billing) server-side after a local\n // abort — cancel it there too, best-effort.\n const job = this.store.get().run.job;\n if (job && this.config.provider.cancelJob && ![\"completed\", \"failed\", \"cancelled\"].includes(job.status)) {\n void this.config.provider.cancelJob(job.handle).catch(() => {});\n void this.config.jobStore?.remove(job.handle.id);\n }\n // Release any suspended tool so the run can unwind instead of hanging.\n for (const [callId, entry] of this.pending) {\n entry.resolve({ cardId: entry.card.id, callId, kind: \"cancel\", type: \"cancel\", at: Date.now() });\n }\n this.pending.clear();\n // Stop means stop: what was waiting behind this run does not start after it.\n for (const queued of this.surfaceQueue.splice(0)) {\n this.noteSurfaceActivity(queued.spec.surfaceId, queued.component.id, \"cancelled\", \"Cancelled.\");\n }\n }\n\n // ── surfaces ──────────────────────────────────────────────────────────────\n\n /**\n * Write one value into a surface's data model. Neighbours bound to it update at\n * once and no model is called. The thread is rewritten shortly after, not per\n * keystroke, so typing does not re-render every message.\n */\n setSurfaceData(surfaceId: string, path: string, value: unknown): boolean {\n const current = this.store.get().surfaces[surfaceId];\n if (!current || current.deleted || current.expired) return false;\n const data = setAt(current.data, path, value);\n if (!data || JSON.stringify(data).length > SURFACE_LIMITS.dataChars) return false;\n this.putSurface({ ...current, data, revision: current.revision + 1 });\n return true;\n }\n\n private putSurface(spec: SurfaceSpec): void {\n this.surfaceLedger?.put(spec);\n this.store.set((s) => ({ ...s, surfaces: { ...s.surfaces, [spec.surfaceId]: spec } }));\n this.dirtySurfaces.add(spec.surfaceId);\n if (this.surfaceSaveTimer) return;\n this.surfaceSaveTimer = setTimeout(() => this.saveSurfacesNow(), SURFACE_SAVE_DELAY_MS);\n }\n\n private saveSurfacesNow(): void {\n if (this.surfaceSaveTimer) clearTimeout(this.surfaceSaveTimer);\n this.surfaceSaveTimer = null;\n if (!this.dirtySurfaces.size) return;\n this.flushSurfaceWrites();\n this.persist();\n }\n\n /**\n * Fold pending edits into the newest snapshot of each surface: the live card, or\n * the stored one. A finished run's cards stay in `run` until the next one starts,\n * so they only count as the newest copy while that run has yet to commit.\n */\n private flushSurfaceWrites(uncommittedRun = this.isRunning): void {\n if (this.surfaceSaveTimer) clearTimeout(this.surfaceSaveTimer);\n this.surfaceSaveTimer = null;\n if (!this.dirtySurfaces.size) return;\n const ids = [...this.dirtySurfaces];\n this.dirtySurfaces.clear();\n this.store.set((s) => {\n let { run, tree } = s;\n for (const id of ids) {\n const spec = s.surfaces[id];\n if (!spec) continue;\n const cardId = surfaceCardId(id);\n if (uncommittedRun && run.cards.some((c) => c.id === cardId)) {\n run = { ...run, cards: run.cards.map((c) => (c.id === cardId ? { ...c, spec } : c)) };\n continue;\n }\n const holder = [...s.messages].reverse().find((m) => m.parts.some((p) => p.type === \"artifact\" && p.id === cardId));\n if (!holder) continue;\n tree = tree.map((m) =>\n m.id === holder.id\n ? { ...m, parts: m.parts.map((p) => (p.type === \"artifact\" && p.id === cardId ? { ...p, data: spec } : p)) }\n : m,\n );\n }\n if (run === s.run && tree === s.tree) return s;\n return { ...s, run, cards: run.cards, tree, messages: tree === s.tree ? s.messages : pathTo(tree, s.headId) };\n });\n }\n\n private noteSurfaceActivity(surfaceId: string, componentId: string, state: SurfaceActivityState, message?: string): SurfaceActivityState {\n this.store.set((s) => ({\n ...s,\n surfaceActivity: { ...s.surfaceActivity, [surfaceId]: { componentId, state, ...(message ? { message } : {}), at: Date.now() } },\n }));\n return state;\n }\n\n /**\n * Run the action of a control the person pressed.\n *\n * Takes the component's id rather than an action: what runs is read from the\n * validated spec here, so nothing in the page can substitute a different one.\n */\n async dispatchSurfaceAction(\n surfaceId: string,\n componentId: string,\n scope: { item?: unknown; index?: number } = {},\n ): Promise<SurfaceActivityState> {\n const spec = this.store.get().surfaces[surfaceId];\n const component = spec?.components.find((c) => c.id === componentId);\n const action = component?.[\"action\"] as SurfaceAction | undefined;\n if (!spec || spec.deleted || spec.expired || !component || !action) {\n return this.noteSurfaceActivity(surfaceId, componentId, \"refused\", \"This control is no longer available.\");\n }\n const binding = { data: spec.data, ...scope };\n const disabledWhen = component[\"disabledWhen\"] as Parameters<typeof evaluateSurfaceCondition>[0];\n if (disabledWhen && evaluateSurfaceCondition(disabledWhen, binding)) {\n return this.noteSurfaceActivity(surfaceId, componentId, \"refused\", \"This control is unavailable right now.\");\n }\n\n const resolved = resolveSurfaceAction(action, binding);\n if (resolved.type === \"set\") {\n let data: Record<string, unknown> | undefined = spec.data;\n for (const update of resolved.updates) data = data && setAt(data, update.path, update.value);\n if (!data) return this.noteSurfaceActivity(surfaceId, componentId, \"failed\", \"That change could not be applied.\");\n this.putSurface({ ...spec, data, revision: spec.revision + 1 });\n return this.noteSurfaceActivity(surfaceId, componentId, \"done\");\n }\n\n if (resolved.type === \"tool\") {\n const verdict = authorizeSurfaceTool(resolved.tool, resolved.args, this.config.tools, this.config.toolResolution);\n if (!verdict.ok) return this.noteSurfaceActivity(surfaceId, componentId, \"refused\", verdict.reason);\n }\n\n const queued: QueuedSurfaceAction = { spec, component, action: resolved };\n if (this.isRunning) {\n if (this.surfaceQueue.length >= SURFACE_QUEUE_LIMIT) {\n return this.noteSurfaceActivity(surfaceId, componentId, \"refused\", \"Too many actions are waiting. Try again shortly.\");\n }\n this.surfaceQueue.push(queued);\n return this.noteSurfaceActivity(surfaceId, componentId, \"queued\", \"Waiting for the agent to finish.\");\n }\n return this.startSurfaceAction(queued);\n }\n\n /** Record the answer to an interactive card inside a surface, then run its action if it has one. */\n async respondToSurfaceCard(surfaceId: string, componentId: string, answer: Omit<SurfaceCardAnswer, \"at\">): Promise<SurfaceActivityState> {\n const spec = this.store.get().surfaces[surfaceId];\n const component = spec?.components.find((c) => c.id === componentId);\n const bind = component?.[\"bind\"];\n if (!spec || !component || typeof bind !== \"string\" || getAt(spec.data, bind) !== undefined) {\n return this.noteSurfaceActivity(surfaceId, componentId, \"refused\", \"This question has already been answered.\");\n }\n if (!this.setSurfaceData(surfaceId, bind, { ...answer, at: Date.now() })) {\n return this.noteSurfaceActivity(surfaceId, componentId, \"failed\", \"The answer could not be saved.\");\n }\n return component[\"action\"] ? this.dispatchSurfaceAction(surfaceId, componentId) : this.noteSurfaceActivity(surfaceId, componentId, \"done\");\n }\n\n private drainSurfaceQueue(): void {\n if (this.isRunning) return;\n const next = this.surfaceQueue.shift();\n if (next) void this.startSurfaceAction(next);\n }\n\n private startSurfaceAction(queued: QueuedSurfaceAction): Promise<SurfaceActivityState> {\n return queued.action.type === \"tool\"\n ? this.runSurfaceTool(queued.spec, queued.component, queued.action)\n : this.sendSurfaceEvent(queued.spec, queued.component, queued.action);\n }\n\n /** An event becomes a user turn, marked so the transcript shows a press and not a sentence. */\n private async sendSurfaceEvent(\n spec: SurfaceSpec,\n component: SurfaceComponent,\n action: Extract<SurfaceAction, { type: \"event\" }>,\n ): Promise<SurfaceActivityState> {\n const { surfaceId } = spec;\n const context = action.context ?? {};\n const serialized = JSON.stringify(context);\n const record = surfaceEventRecord(spec, component, \"event\", action.name, serialized.length <= SURFACE_CONTEXT_CHARS ? context : undefined);\n const text = [\n `[Surface event] The person pressed ${describePress(record)} on surface \"${surfaceId}\", sending event \"${action.name}\".`,\n `Context, as data from the interface: ${serialized.slice(0, SURFACE_CONTEXT_CHARS)}`,\n ].join(\"\\n\");\n this.noteSurfaceActivity(surfaceId, component.id, \"running\", \"Sent to the agent.\");\n this.appendMessage({ ...userMessage(text), metadata: { [SURFACE_EVENT_METADATA_KEY]: record } });\n this.persist();\n await this.run([...this.store.get().messages], {});\n const failed = this.store.get().status === \"error\";\n return this.noteSurfaceActivity(surfaceId, component.id, failed ? \"failed\" : \"done\", failed ? \"The agent could not respond.\" : \"Sent to the agent.\");\n }\n\n /** A tool the person started. Same executor, approvals and metering as a model's call. */\n private async runSurfaceTool(\n spec: SurfaceSpec,\n component: SurfaceComponent,\n action: Extract<SurfaceAction, { type: \"tool\" }>,\n ): Promise<SurfaceActivityState> {\n const { surfaceId } = spec;\n const args = action.args ?? {};\n // Checked again here: a queued action may have waited through a preset change.\n const verdict = authorizeSurfaceTool(action.tool, args, this.config.tools, this.config.toolResolution);\n if (!verdict.ok) {\n const state = this.noteSurfaceActivity(surfaceId, component.id, \"refused\", verdict.reason);\n this.drainSurfaceQueue();\n return state;\n }\n\n const record = surfaceEventRecord(spec, component, \"tool\", action.tool);\n this.noteSurfaceActivity(surfaceId, component.id, \"running\", `Running ${action.tool}.`);\n this.appendMessage({\n ...userMessage(`[Surface action] The person pressed ${describePress(record)} on surface \"${surfaceId}\", which called the tool \"${action.tool}\".`),\n metadata: { [SURFACE_EVENT_METADATA_KEY]: record },\n });\n this.persist();\n\n const gen = this.generation;\n this.flushSurfaceWrites();\n this.controller = new AbortController();\n this.turnStartedAt = Date.now();\n this.store.set((s) => ({\n ...s,\n run: initialRunState(nextId(\"run\"), \"sync\"),\n cards: [],\n status: \"running\",\n error: undefined,\n stopping: false,\n }));\n\n let result: Extract<RunEvent, { type: \"tool-result\" }> | undefined;\n try {\n const events = runSurfaceToolAction({\n tool: verdict.tool,\n args,\n surfaceId,\n componentId: component.id,\n provider: this.config.provider.id,\n model: this.config.model,\n vars: this.config.vars,\n signal: this.controller.signal,\n toolTimeoutMs: this.config.toolTimeoutMs,\n meter: this.config.meter,\n meteringMetadata: this.config.meteringMetadata,\n onUserDecision: this.awaitDecision,\n onHostTool: this.config.onHostTool,\n });\n for await (const event of events) {\n if (gen !== this.generation) return \"cancelled\";\n if (event.type === \"tool-result\") result = event;\n this.apply(event);\n }\n } catch (e) {\n if (gen === this.generation) this.store.set((s) => ({ ...s, status: \"error\", error: e }));\n } finally {\n this.controller = null;\n }\n if (gen !== this.generation) return \"cancelled\";\n\n let state: SurfaceActivityState;\n let message: string | undefined;\n if (!result || (result.failure && result.failure !== \"denied\")) {\n state = \"failed\";\n message = failureMessage(result?.output) ?? `${action.tool} failed.`;\n } else if (result.failure === \"denied\") {\n state = \"cancelled\";\n message = \"Cancelled.\";\n } else {\n state = \"done\";\n message = \"Done.\";\n if (action.resultPath && !this.setSurfaceData(surfaceId, action.resultPath, stripCardPayload(result.output))) {\n state = \"failed\";\n message = \"The result was too large to show here.\";\n }\n }\n this.commitRun(\"surface-action\");\n this.noteSurfaceActivity(surfaceId, component.id, state, message);\n this.drainSurfaceQueue();\n return state;\n }\n\n clear(): void {\n this.dirtySurfaces.clear();\n this.generation += 1;\n this.stop();\n this.surfaceQueue = [];\n this.store.set((s) => ({\n ...s,\n messages: [],\n tree: [],\n headId: null,\n cards: [],\n attachments: [],\n run: initialRunState(\"\", this.config.mode ?? \"stream\"),\n status: \"idle\",\n error: undefined,\n stopping: false,\n surfaces: {},\n surfaceActivity: {},\n }));\n // Without this, reload restores the conversation the user just cleared.\n this.persist();\n }\n\n /**\n * Re-poll background jobs from a previous session. Call on mount.\n *\n * Results are routed by `StoredJob.threadId`: the current thread gets its\n * results appended live; another thread's results are written into its\n * stored snapshot (when a ThreadStore is configured), so an answer to\n * thread A never gets pasted into thread B.\n */\n async resumeBackgroundJobs(): Promise<void> {\n const store = this.config.jobStore;\n if (!store) return;\n const results = await resumeJobs(store, { [this.config.provider.id]: this.config.provider });\n this.store.set((s) => ({ ...s, jobs: results.map((r) => r.job) }));\n\n const currentId = this.store.get().id;\n // Jobs landing in an AWAY thread are grouped by threadId: two jobs for the\n // SAME away thread read-modify-write that thread's one stored snapshot, so\n // they must land in order or the second save clobbers the first. Jobs for\n // DIFFERENT away threads touch different snapshots and have no ordering\n // dependency on each other, so those groups load/save concurrently.\n const away = new Map<string, ContentPart[][]>();\n\n for (const { job, snapshot } of results) {\n const parts: ContentPart[] | null =\n snapshot.status === \"completed\" && snapshot.result\n ? snapshot.result.parts\n : snapshot.status === \"failed\"\n ? [{ type: \"text\", text: `_${snapshot.error?.message ?? \"A background job failed.\"}_` }]\n : null;\n if (!parts) continue;\n\n if (!job.threadId || job.threadId === currentId) {\n this.appendMessage(assistantMessage(parts));\n if (job.threadId === currentId) this.persist();\n continue;\n }\n\n const bucket = away.get(job.threadId) ?? [];\n bucket.push(parts);\n away.set(job.threadId, bucket);\n }\n\n const threads = this.config.threadStore;\n if (!threads || !away.size) return; // nowhere to put it; the handle was already reaped\n\n await Promise.all(\n [...away].map(async ([threadId, partsList]) => {\n for (const parts of partsList) {\n const stored = await threads.load(threadId);\n if (!stored) continue;\n const awayHead = stored.headId ?? stored.messages.at(-1)?.id ?? null;\n const appended: Message = { ...assistantMessage(parts), parentId: awayHead };\n await threads.save(\n threadSnapshot(threadId, [...stored.messages, appended], stored.meta, appended.id),\n );\n }\n }),\n );\n }\n}\n\n/** Re-derive surfaces after the head moved: each branch shows them as it left them. */\nconst onPath = (s: ThreadState): ThreadState => ({ ...s, surfaces: foldSurfaces(s.messages) });\n\nfunction surfaceEventRecord(\n spec: SurfaceSpec,\n component: SurfaceComponent,\n type: SurfaceEventRecord[\"type\"],\n name: string,\n context?: Record<string, unknown>,\n): SurfaceEventRecord {\n const label = component[\"label\"];\n return {\n surfaceId: spec.surfaceId,\n componentId: component.id,\n ...(spec.title ? { title: spec.title } : {}),\n ...(typeof label === \"string\" ? { label } : {}),\n type,\n name,\n ...(context ? { context } : {}),\n };\n}\n\nconst describePress = (record: SurfaceEventRecord) => (record.label ? JSON.stringify(record.label) : `control \"${record.componentId}\"`);\n\nconst failureMessage = (output: unknown): string | undefined => {\n const error = (output as { error?: unknown } | null)?.error;\n return typeof error === \"string\" ? error.slice(0, 200) : undefined;\n};\n\n/**\n * Run state appends tool results as they finish; a committed turn keeps them in\n * the order they were called, the same order runAgent writes back to history.\n * Only results that sit next to each other move, and only among themselves.\n */\nfunction toolResultsInCallOrder(parts: readonly ContentPart[]): ContentPart[] {\n const callAt = new Map<string, number>();\n parts.forEach((p, i) => {\n if (p.type === \"tool-call\") callAt.set(p.callId, i);\n });\n const rank = (p: ContentPart) =>\n p.type === \"tool-result\" ? (callAt.get(p.callId) ?? Number.MAX_SAFE_INTEGER) : Number.MAX_SAFE_INTEGER;\n\n const out: ContentPart[] = [];\n let batch: ContentPart[] = [];\n const flush = () => {\n out.push(...batch.sort((a, b) => rank(a) - rank(b)));\n batch = [];\n };\n for (const p of parts) {\n if (p.type === \"tool-result\") batch.push(p);\n else {\n flush();\n out.push(p);\n }\n }\n flush();\n return out;\n}\n","// A tiny external store, consumed via useSyncExternalStore.\n//\n// Hand-rolled rather than pulling in zustand/valtio for two reasons: the state\n// shape is already defined by the core's `RunState` reducer, and a chat thread\n// under a streaming run notifies at token frequency — a store that allocates a\n// new subscriber array per notify shows up in a profile at 60+ notifies/sec.\n\nexport type Listener = () => void;\n\nexport class Store<T> {\n private state: T;\n private listeners = new Set<Listener>();\n\n constructor(initial: T) {\n this.state = initial;\n }\n\n get = (): T => this.state;\n\n set = (next: T | ((prev: T) => T)): void => {\n const value = typeof next === \"function\" ? (next as (prev: T) => T)(this.state) : next;\n // Reference equality guard: a reducer that returns the same object (a\n // no-op event) must not wake every subscriber.\n if (Object.is(value, this.state)) return;\n this.state = value;\n for (const listener of this.listeners) listener();\n };\n\n subscribe = (listener: Listener): (() => void) => {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n };\n}\n"],"mappings":";AAMA;AAAA,EACE;AAAA,EACA;A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AG,IAAI;AAC3D;AAOA,SAAS,uBAAuB,OAA8C;AAC5E,QAAM,SAAS,oBAAI,IAAoB;AACvC,QAAM,QAAQ,CAAC,GAAG,MAAM;AACtB,QAAI,EAAE,SAAS,YAAa,QAAO,IAAI,EAAE,QAAQ,CAAC;AAAA,EACpD,CAAC;AACD,QAAM,OAAO,CAAC,MACZ,EAAE,SAAS,gBAAiB,OAAO,IAAI,EAAE,MAAM,KAAK,OAAO,mBAAoB,OAAO;AAExF,QAAM,MAAqB,CAAC;AAC5B,MAAI,QAAuB,CAAC;AAC5B,QAAM,QAAQ,MAAM;AAClB,QAAI,KAAK,GAAG,MAAM,KAAK,CAAC,GAAG,MAAM,KAAK,CAAC,IAAI,KAAK,CAAC,CAAC,CAAC;AACnD,YAAQ,CAAC;AAAA,EACX;AACA,aAAW,KAAK,OAAO;AACrB,QAAI,EAAE,SAAS,cAAe,OAAM,KAAK,CAAC;AAAA,SACrC;AACH,YAAM;AACN,UAAI,KAAK,CAAC;AAAA,IACZ;AAAA,EACF;AACA,QAAM;AACN,SAAO;AACT;","names":["state"]}
package/package.json CHANGED
@@ -1,16 +1,56 @@
1
1
  {
2
2
  "name": "@supersolutions/super-chat-client",
3
- "version": "0.0.0",
4
- "description": "Placeholder; real releases come from GitHub Actions.",
3
+ "version": "0.2.0",
4
+ "description": "Framework-agnostic client for superchat: one AgentClient store per thread that drives the agent runtime. No UI framework dependency.",
5
5
  "license": "Apache-2.0",
6
- "repository": {
7
- "type": "git",
8
- "url": "git+https://github.com/Super-Solution/super-chat.git"
6
+ "author": "SUPER SOLUTION LABS INC",
7
+ "homepage": "https://github.com/Super-Solution/super-chat/tree/main/packages/client#readme",
8
+ "bugs": {
9
+ "url": "https://github.com/Super-Solution/super-chat/issues"
10
+ },
11
+ "keywords": [
12
+ "agent",
13
+ "llm",
14
+ "ai",
15
+ "chat",
16
+ "streaming",
17
+ "store",
18
+ "framework-agnostic"
19
+ ],
20
+ "type": "module",
21
+ "sideEffects": false,
22
+ "main": "./dist/index.js",
23
+ "module": "./dist/index.js",
24
+ "types": "./dist/index.d.ts",
25
+ "exports": {
26
+ ".": {
27
+ "types": "./dist/index.d.ts",
28
+ "import": "./dist/index.js",
29
+ "default": "./dist/index.js"
30
+ }
9
31
  },
10
32
  "files": [
11
- "README.md"
33
+ "dist",
34
+ "LICENSE",
35
+ "NOTICE"
12
36
  ],
37
+ "repository": {
38
+ "type": "git",
39
+ "url": "https://github.com/Super-Solution/super-chat.git",
40
+ "directory": "packages/client"
41
+ },
13
42
  "publishConfig": {
14
43
  "access": "public"
44
+ },
45
+ "dependencies": {
46
+ "@supersolutions/super-chat-core": "0.2.0"
47
+ },
48
+ "devDependencies": {
49
+ "tsup": "^8.3.5",
50
+ "typescript": "^5.7.2"
51
+ },
52
+ "scripts": {
53
+ "build": "tsup",
54
+ "typecheck": "tsc --noEmit"
15
55
  }
16
56
  }