import { parseSse } from "./sse.js"; import type { AskOptions, AskResponse, BridgesResponse, CorroboratedResponse, EntityResponse, IdeaAtom, LivingResponse, OpportunitiesResponse, PriorArtResponse, Stats, StreamEvent, } from "./types.js"; export const SDK_VERSION = "0.52.0"; export interface CommonsClientOptions { /** Base URL of `commons serve`, e.g. `http://localhost:8788`. */ baseUrl: string; /** Optional fetch override (tests / custom agents). */ fetch?: typeof fetch; } function flag(v: boolean | undefined): string | undefined { if (v === undefined) return undefined; return v ? "1" : "0"; } export class CommonsError extends Error { readonly status: number; readonly body: string; constructor(status: number, body: string) { super(`commons HTTP ${status}: ${body.slice(0, 200)}`); this.name = "CommonsError"; this.status = status; this.body = body; } } /** Typed client for the commons HTTP API (see `/openapi.yaml`). */ export class CommonsClient { readonly baseUrl: string; private readonly fetchImpl: typeof fetch; constructor(opts: CommonsClientOptions) { this.baseUrl = opts.baseUrl.replace(/\/+$/, ""); this.fetchImpl = opts.fetch ?? fetch; } /** Build a GET URL with query params (exported for unit tests). */ url(path: string, params: Record): string { const u = new URL(path, this.baseUrl.endsWith("/") ? this.baseUrl : this.baseUrl + "/"); // Absolute path on the server u.pathname = path.startsWith("/") ? path : `/${path}`; for (const [k, v] of Object.entries(params)) { if (v === undefined || v === "") continue; u.searchParams.set(k, String(v)); } return u.toString(); } private async getJson(path: string, params: Record, signal?: AbortSignal): Promise { const res = await this.fetchImpl(this.url(path, params), { signal }); const text = await res.text(); if (!res.ok) throw new CommonsError(res.status, text); return JSON.parse(text) as T; } private async postJson(path: string, body: unknown, signal?: AbortSignal): Promise { const res = await this.fetchImpl(this.url(path, {}), { method: "POST", headers: { "Content-Type": "application/json", Accept: "application/json" }, body: JSON.stringify(body), signal, }); const text = await res.text(); if (!res.ok) throw new CommonsError(res.status, text); return (text.trim() ? JSON.parse(text) : {}) as T; } stats(signal?: AbortSignal): Promise { return this.getJson("/api/stats", {}, signal); } /** * Ask the commons. **Streaming is the default** (`stream: true`): hits arrive * in the `meta` event and the answer is collected from `token` events. * Pass `{ stream: false }` for a single buffered `/api/ask` JSON response. */ async ask(query: string, opts: AskOptions = {}): Promise { const stream = opts.stream !== false; if (!stream) { return this.getJson( "/api/ask", { q: query, top: opts.top, mode: opts.mode, dense: flag(opts.dense), rerank: flag(opts.rerank), synth: flag(opts.synth), }, opts.signal, ); } const { meta, answer } = await this.askStreamCollect(query, opts); if (!meta) { return { mode: "SPECIFIC", mode_source: "default", query, hits: [], answer: answer || undefined, }; } if (answer && !meta.answer) meta.answer = answer; else if (answer && meta.answer !== answer) meta.answer = answer; return meta; } /** * SSE ask: yields `meta` (AskResponse), then `token` chunks, then `done`. * Buffers the full stream (commons serve is one-shot tiny_http), then yields. */ async *askStream(query: string, opts: AskOptions = {}): AsyncGenerator { const res = await this.fetchImpl( this.url("/api/ask/stream", { q: query, top: opts.top, mode: opts.mode, dense: flag(opts.dense), rerank: flag(opts.rerank), }), { signal: opts.signal, headers: { Accept: "text/event-stream" } }, ); const text = await res.text(); if (!res.ok) throw new CommonsError(res.status, text); yield* parseSse(text); } /** Collect tokens from {@link askStream} into one answer string (+ meta). */ async askStreamCollect( query: string, opts: AskOptions = {}, ): Promise<{ meta: AskResponse | null; answer: string }> { let meta: AskResponse | null = null; let answer = ""; for await (const ev of this.askStream(query, opts)) { if (ev.event === "meta") meta = ev.data as AskResponse; else if (ev.event === "token") { const t = (ev.data as { text?: string })?.text ?? ""; answer += t; } } return { meta, answer }; } corroborated(opts: { min?: number; n?: number; signal?: AbortSignal } = {}): Promise { return this.getJson( "/api/corroborated", { min: opts.min, n: opts.n }, opts.signal, ); } bridges(signal?: AbortSignal): Promise { return this.getJson("/api/bridges", {}, signal); } /** Browse one concept by stable `id` or surface `label`. Paged: follow `next_offset`. */ entity( opts: { id?: string; label?: string; offset?: number; limit?: number; signal?: AbortSignal }, ): Promise { return this.getJson( "/api/entity", { id: opts.id, label: opts.label, offset: opts.offset, limit: opts.limit }, opts.signal, ); } /** Every grounded idea for a concept, walking `next_offset` pages. */ async *entityIdeas( opts: { id?: string; label?: string; pageSize?: number; signal?: AbortSignal }, ): AsyncGenerator { let offset: number | null = 0; while (offset !== null) { const page: EntityResponse = await this.entity({ id: opts.id, label: opts.label, offset, limit: opts.pageSize ?? 100, signal: opts.signal, }); yield* page.ideas; offset = page.next_offset ?? null; } } /** When was an idea first disclosed publicly — chronological (`GET /api/prior-art`). */ priorArt( query: string, opts: { n?: number; signal?: AbortSignal } = {}, ): Promise { return this.getJson("/api/prior-art", { q: query, n: opts.n }, opts.signal); } /** Frontier concepts adjacent to a topic (contested / emerging / breadth). */ opportunities( query: string, opts: { n?: number; top?: number; signal?: AbortSignal } = {}, ): Promise { return this.getJson( "/api/opportunities", { q: query, n: opts.n, top: opts.top }, opts.signal, ); } /** One grounded idea — the encoding unit (`GET /api/idea`). */ idea(id: string, opts: { signal?: AbortSignal } = {}): Promise { return this.getJson("/api/idea", { id }, opts.signal); } /** Newest ideas in the commons (`GET /api/living`). */ living( opts: { n?: number; modality?: "spoken" | "written"; signal?: AbortSignal } = {}, ): Promise { return this.getJson( "/api/living", { n: opts.n, modality: opts.modality }, opts.signal, ); } /** Fetch the live OpenAPI document (`GET /openapi.yaml`). */ async openapiYaml(signal?: AbortSignal): Promise { const res = await this.fetchImpl(this.url("/openapi.yaml", {}), { signal }); const text = await res.text(); if (!res.ok) throw new CommonsError(res.status, text); return text; } /** Sub-ms shared L0 competence crystals & negative-space dead-end guardrails (`GET /api/ecosystem/agent-context`). */ l0Context(task: string, signal?: AbortSignal): Promise> { return this.getJson("/api/ecosystem/agent-context", { task }, signal); } /** Zero-rewrite OpenAI-compatible chat completion (`POST /v1/chat/completions`). */ chatCompletions( promptOrMessages: string | Array<{ role: string; content: string }>, opts: { model?: string; signal?: AbortSignal } = {}, ): Promise> { const messages = typeof promptOrMessages === "string" ? [{ role: "user", content: promptOrMessages }] : promptOrMessages; return this.postJson( "/v1/chat/completions", { model: opts.model ?? "scholar-grounded", messages, stream: false }, opts.signal, ); } /** Deterministic 384-D OpenAI-compatible embeddings (`POST /v1/embeddings`). */ embeddings( input: string | string[], opts: { model?: string; signal?: AbortSignal } = {}, ): Promise> { return this.postJson( "/v1/embeddings", { model: opts.model ?? "scholar-embed-384", input }, opts.signal, ); } /** Google / Linux Foundation A2A 1.0 task execution (`POST /a2a` `message/send`). */ a2aSend( text: string, opts: { skillId?: string; signal?: AbortSignal } = {}, ): Promise> { return this.postJson( "/a2a", { jsonrpc: "2.0", id: 1, method: "message/send", params: { skillId: opts.skillId ?? "commons_ask", message: { role: "user", parts: [{ kind: "text", text }] }, }, }, opts.signal, ); } /** Linux Foundation REST Agent Communication Protocol (`POST /acp/runs`). */ acpRun(prompt: string, signal?: AbortSignal): Promise> { return this.postJson( "/acp/runs", { agent_name: "commons-scholar", input: [{ role: "user", parts: [{ content_type: "text/plain", content: prompt }] }], }, signal, ); } /** Fetch ready-to-pass function-calling tool schemas (`openai` | `anthropic` | `gemini`). */ toolpack( provider: "openai" | "anthropic" | "gemini" = "openai", signal?: AbortSignal, ): Promise { return this.getJson(`/api/tools/${provider}.json`, {}, signal); } /** Direct REST webhook invocation of any of the 51 Scholar MCP tools (`POST /api/tools/invoke`). */ invokeTool( name: string, args: Record = {}, signal?: AbortSignal, ): Promise> { return this.postJson("/api/tools/invoke", { name, arguments: args }, signal); } /** Query or POST to any `/api/reference/` solver, forge, ontology, or multimodal video engine. */ reference>( slug: string, opts: { q?: string; body?: unknown; signal?: AbortSignal } = {}, ): Promise { const clean = slug.replace(/^\/+|\/+$/g, ""); if (opts.body !== undefined) { return this.postJson(`/api/reference/${clean}`, opts.body, opts.signal); } return this.getJson(`/api/reference/${clean}`, { q: opts.q }, opts.signal); } ontologySpine(q = "thermodynamic", body?: unknown): Promise> { return this.reference("ontology-spine", { q, body }); } cospanOde(q = "seihr", body?: unknown): Promise> { return this.reference("categorical-ode", { q, body }); } videoHubIngest(q = "", body?: unknown): Promise> { return this.reference("video-hub-ingest", { q, body }); } omniVideoAlign(q = "", body?: unknown): Promise> { return this.reference("omni-video-align", { q, body }); } c2paProvenance(q = "", body?: unknown): Promise> { return this.reference("c2pa-provenance", { q, body }); } videoMoatEconomics(q = "", body?: unknown): Promise> { return this.reference("video-moat-economics", { q, body }); } trainingCommons(q = "", body?: unknown): Promise> { return this.reference("training-commons", { q, body }); } scalingPruning(q = "", body?: unknown): Promise> { return this.reference("scaling-pruning", { q, body }); } federatedSuperlearner(q = "", body?: unknown): Promise> { return this.reference("federated-superlearner", { q, body }); } tufazipCodec(q = "", body?: unknown): Promise> { return this.reference("tufazip-codec", { q, body }); } compressionBenchmark(q = "", body?: unknown): Promise> { return this.reference("compression-benchmark", { q, body }); } wai1TufaArchive(q = "", body?: unknown): Promise> { return this.reference("wai1-tufa-archive", { q, body }); } multimodalMdlScheduler(q = "", body?: unknown): Promise> { return this.reference("multimodal-mdl-scheduler", { q, body }); } scholarBench(q = "", body?: unknown): Promise> { return this.reference("scholar-bench", { q, body }); } scholarBenchLeaderboard(q = ""): Promise> { return this.getJson("/api/reference/scholar-bench", { mode: "leaderboard", q }); } waldenLineage(q = "", body?: unknown): Promise> { return this.reference("walden-lineage", { q, body }); } sdkRegistry(signal?: AbortSignal): Promise> { return this.getJson("/api/reference/sdk-registry", {}, signal); } }