@llmnative/runner 1.1.2 → 1.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.
- package/dist/client.js +2 -2
- package/dist/client.js.map +1 -1
- package/dist/client.mjs +37 -23
- package/dist/client.mjs.map +1 -1
- package/dist/setup-app/assets/{NetworkCanvasImpl-DIYuzg6x-1-PFOsG-.js → NetworkCanvasImpl-DIYuzg6x-Cvx1IqQZ.js} +1 -1
- package/dist/setup-app/assets/{index-BRawUfMd.js → index-Ce40a4eE.js} +3 -3
- package/dist/setup-app/assets/{index.es-CmHxhQwy.js → index.es-9Zr7VidY.js} +1 -1
- package/dist/setup-app/assets/{lucide-react-DItA0m8e.js → lucide-react-2gg5h5-W.js} +1 -1
- package/dist/setup-app/index.html +1 -1
- package/dist/setup.js +1 -1
- package/dist/setup.js.map +1 -1
- package/dist/setup.mjs +1 -1
- package/dist/setup.mjs.map +1 -1
- package/dist/steps.js +1 -1
- package/dist/steps.mjs +2 -2
- package/dist/types/client/index.d.ts +20 -7
- package/dist/types/setup/index.d.ts +2 -1
- package/dist/types/ui/RunnerAccounts.d.ts +4 -2
- package/dist/types/ui/texts.d.ts +36 -0
- package/dist/ui.js +3 -3
- package/dist/ui.js.map +1 -1
- package/dist/ui.mjs +567 -429
- package/dist/ui.mjs.map +1 -1
- package/install/coolify.yaml +2 -2
- package/install/install.sh +1 -1
- package/openapi/v1.yaml +16 -7
- package/package.json +1 -1
package/dist/client.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=class extends Error{status;code;until;detail;constructor(e,t,n={}){super(t),this.name=`RunnerError`,this.status=e,this.code=t,n.until&&(this.until=n.until),n.detail&&(this.detail=n.detail)}},
|
|
2
|
-
`);s=e?``:n.pop()??``;for(let e of n){if(!e.trim())continue;let t;try{t=JSON.parse(e)}catch{continue}t.type!==`ping`&&(yield t)}if(e)return}}},
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=[`anthropic`,`openai`,`gemini`,`mistral`,`deepseek`,`openrouter`],t=class extends Error{status;code;until;detail;constructor(e,t,n={}){super(t),this.name=`RunnerError`,this.status=e,this.code=t,n.until&&(this.until=n.until),n.detail&&(this.detail=n.detail)}},n=e=>e.type===`error`&&e.message.startsWith(`no-credit:`)?e.message.slice(10):void 0,r=class e{options;constructor(e){this.options={...e,url:e.url.replace(/\/+$/,``)}}as(t){return new e({...this.options,...t})}async headers(e){let{key:t,tenant:n,user:r,headers:i}=this.options;return{...e?{"content-type":`application/json`}:{},...t?{authorization:`Bearer ${t}`}:{},...n?{"x-runner-tenant":n}:{},...r?{"x-runner-user":r}:{},...await i?.()}}async request(e,n,r){let i=await(this.options.fetch??fetch)(`${this.options.url}${n}`,{method:e,headers:await this.headers(r!==void 0),...r===void 0?{}:{body:JSON.stringify(r)}}),a=await i.text(),o={};try{o=a?JSON.parse(a):{}}catch{}if(!i.ok)throw new t(i.status,typeof o.error==`string`?o.error:`http-${i.status}`,{...typeof o.until==`string`?{until:o.until}:{},...typeof o.detail==`string`?{detail:o.detail}:{}});return o}health(){return this.request(`GET`,`/health`)}pair(e,t,n){return this.request(`POST`,`/v1/pair`,{code:e,...t?{name:t}:{},...n?{project:n}:{}})}requestPairing(e,t){return this.request(`POST`,`/v1/pair/requests`,{name:e,...t?{project:t}:{}})}pollPairing(e){return this.request(`POST`,`/v1/pair/requests/poll`,{request:e})}info(){return this.request(`GET`,`/v1/info`)}createPairing(){return this.request(`POST`,`/v1/admin/pairing`)}async pairingRequests(){return(await this.request(`GET`,`/v1/admin/pairing/requests`)).requests}async answerPairing(e,t){return(await this.request(`POST`,`/v1/admin/pairing/requests/${encodeURIComponent(e)}/${t?`approve`:`deny`}`)).request}async setKeyProject(e,t){return(await this.request(`PUT`,`/v1/admin/keys/${encodeURIComponent(e)}/project`,{project:t})).record}platform={status:()=>this.request(`GET`,`/v1/platform/status`),tenants:async()=>(await this.request(`GET`,`/v1/platform/tenants`)).tenants,createTenant:(e,t={})=>this.request(`POST`,`/v1/platform/tenants`,{id:e,...t}),removeTenant:async e=>(await this.request(`DELETE`,`/v1/platform/tenants/${encodeURIComponent(e)}`)).removed,keys:async e=>(await this.request(`GET`,`/v1/platform/tenants/${encodeURIComponent(e)}/keys`)).keys,createKey:(e,t={})=>this.request(`POST`,`/v1/platform/tenants/${encodeURIComponent(e)}/keys`,t),revokeKey:async(e,t)=>(await this.request(`DELETE`,`/v1/platform/tenants/${encodeURIComponent(e)}/keys/${encodeURIComponent(t)}`)).removed,platformKeys:async()=>(await this.request(`GET`,`/v1/platform/keys`)).keys,revokePlatformKey:async e=>(await this.request(`DELETE`,`/v1/platform/keys/${encodeURIComponent(e)}`)).removed};accounts={list:async()=>this.request(`GET`,`/v1/accounts`),startClaudeLogin:()=>this.request(`POST`,`/v1/accounts/claude-code/login`),finishClaudeLogin:async(e,t)=>(await this.request(`POST`,`/v1/accounts/claude-code/login/code`,{code:e,...t?{label:t}:{}})).account,addClaudeToken:async(e,t)=>(await this.request(`POST`,`/v1/accounts/claude-code`,{token:e,...t?{label:t}:{}})).account,addKey:async(e,t,n)=>(await this.request(`POST`,`/v1/accounts/${e}`,{key:t,...n?{label:n}:{}})).account,remove:async(e,t)=>(await this.request(`DELETE`,`/v1/accounts/${e}/${encodeURIComponent(t)}`)).removed,order:async(e,t)=>(await this.request(`PUT`,`/v1/accounts/order`,{provider:e,ids:t})).accounts};models(){return this.request(`GET`,`/v1/models`)}complete(e){return this.request(`POST`,`/v1/complete`,e)}chats={start:(e,t)=>this.request(`POST`,`/v1/chats`,{id:e,...t?{tools:t}:{}}),send:(e,t,n)=>this.stream(`/v1/chats/${encodeURIComponent(e)}/messages`,t,n),answerCall:async(e,t,n)=>(await this.request(`POST`,`/v1/chats/${encodeURIComponent(e)}/calls/${encodeURIComponent(t)}`,n)).answered,stop:async e=>(await this.request(`POST`,`/v1/chats/${encodeURIComponent(e)}/stop`)).stopped,close:async e=>(await this.request(`DELETE`,`/v1/chats/${encodeURIComponent(e)}`)).closed};async*stream(e,n,r){let i=await(this.options.fetch??fetch)(`${this.options.url}${e}`,{method:`POST`,headers:await this.headers(!0),body:JSON.stringify(n),...r?{signal:r}:{}});if(!i.ok||!i.body){let e=`http-${i.status}`;try{let t=await i.json();t.error&&(e=t.error)}catch{}throw new t(i.status,e)}let a=i.body.getReader(),o=new TextDecoder,s=``;for(;;){let{done:e,value:t}=await a.read();s+=o.decode(t??new Uint8Array,{stream:!e});let n=s.split(`
|
|
2
|
+
`);s=e?``:n.pop()??``;for(let e of n){if(!e.trim())continue;let t;try{t=JSON.parse(e)}catch{continue}t.type!==`ping`&&(yield t)}if(e)return}}},i=/^\/v1\/(info|models|complete|accounts(\/[A-Za-z0-9_.:-]+){0,3}|chats(\/[a-f0-9]{8}(\/(messages|stop|calls\/[a-f0-9]{12}))?)?)$/;async function a(e,t,n,r=fetch){if(!i.test(t)||![`GET`,`POST`,`PUT`,`DELETE`].includes(e.method))return new Response(JSON.stringify({error:`not found`}),{status:404,headers:{"content-type":`application/json`}});let a={authorization:`Bearer ${n.key}`,"x-runner-user":n.user,...n.tenant?{"x-runner-tenant":n.tenant}:{}},o=e.headers.get(`content-type`);o&&(a[`content-type`]=o);let s=e.method===`GET`||e.method===`DELETE`?void 0:await e.arrayBuffer(),c=new URL(e.url),l=await r(`${n.url.replace(/\/+$/,``)}${t}${c.search}`,{method:e.method,headers:a,...s?{body:s}:{},signal:e.signal});return new Response(l.body,{status:l.status,headers:{"content-type":l.headers.get(`content-type`)??`application/json`,"cache-control":`no-store`,"x-accel-buffering":`no`}})}exports.RUNNER_KEY_PROVIDERS=e,exports.RunnerClient=r,exports.RunnerError=t,exports.forwardToRunner=a,exports.noCreditUntil=n;
|
|
3
3
|
//# sourceMappingURL=client.js.map
|
package/dist/client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","names":["RunnerError","code","status","extra","noCreditUntil","event","RunnerClient","options","scope","json","key","tenant","user","headers","response","path","body","text","data","name","approve","id","input","label","provider","request","tools","message","signal","callId","answer","reader","decoder","buffer","value","done","lines","line","PERSON_ROUTES","forwardToRunner","target","type","url","fetchImpl"],"sources":["../src/client/index.ts"],"sourcesContent":["// @llmnative/runner/client — the client of the API v1 of the LLMNative Runner, for the browser and for Node.\n//\n// A key never belongs in the browser of the people of a tenant: a host app talks to the runner from its backend\n// (`createRunnerProxy` forwards the requests of its signed-in people, adding the key, the tenant and the person),\n// and its pages use `RunnerClient` against that backend. The console of the runner and a personal app with a key of\n// its own use `RunnerClient` directly.\n\nexport type RunnerProvider = 'claude-code' | 'opencode-go' | 'opencode';\nexport type RunnerPermission = 'complete' | 'chat' | 'chat:tools' | 'accounts' | 'accounts:tenant' | 'act-as-user' | 'keys';\n\nexport type RunnerAccount = {\n provider: RunnerProvider;\n id: string;\n label?: string;\n /** When it was connected. */\n at: string;\n scope: 'user' | 'tenant';\n /** Out of credit until then (the limit of a subscription); absent when it has credit. */\n noCreditUntil?: string;\n};\n\nexport type RunnerModels = {\n providers: Array<{ id: 'claude-code' | 'opencode-go'; models: string[]; accounts: number; available: number; yours: number; tenant: number }>;\n};\n\nexport type RunnerTenant = { id: string; name: string; createdAt: string; usersWithAccounts?: number };\nexport type RunnerKey = { id: string; kind: 'platform' | 'project'; tenant?: string; name: string; permissions: RunnerPermission[]; createdAt: string; expiresAt: string | null };\n\nexport type RunnerStatus = {\n version: string;\n agentImage: string;\n url?: string;\n load: { chats: number; answering: number; completions: number; maxChats: number };\n machine: { totalBytes: number; availableBytes: number; cpus: number };\n tenants: RunnerTenant[];\n};\n\n/** A pairing request made by a platform: `request` is its secret (keep it in the backend), `code` is shown on both sides. */\nexport type RunnerPairingRequest = { request: string; code: string; approveUrl: string; expiresAt: string; interval: number };\nexport type RunnerPairingPoll = { status: 'pending' | 'denied' | 'expired' } | { status: 'approved'; key: string; record: RunnerKey; version: string };\nexport type RunnerPairingRequestView = { code: string; name: string; from?: string; createdAt: string; expiresAt: string };\nexport type RunnerHealth = { ok: boolean; version: string; chats: number; answering: number; completions: number; maxChats: number };\n\nexport type RunnerCompletionRequest = { provider: 'claude-code' | 'opencode-go'; model: string; prompt: string; effort?: 'low' | 'medium' | 'high' | 'xhigh' | 'max' };\nexport type RunnerCompletion = { text: string; usage?: { inputTokens: number; outputTokens: number } };\n\nexport type RunnerChatTool = { name: string; description: string; inputSchema: Record<string, unknown>; endsTurn?: boolean };\nexport type RunnerChatModel = { provider: string; model: string; variant?: string; name?: string; effort?: string };\nexport type RunnerChatEvent =\n | { type: 'text'; text: string }\n | { type: 'reasoning'; text: string }\n | { type: 'step'; id: string; label: string; status: 'running' | 'done' }\n | { type: 'tool-call'; id: string; name: string; input: Record<string, unknown> }\n | { type: 'done' }\n | { type: 'error'; message: string };\n\n/** An error of the runner: its status and code (`no-credit`, `busy`…), and for `no-credit` until when. */\nexport class RunnerError extends Error {\n readonly status: number;\n readonly code: string;\n readonly until?: string;\n readonly detail?: string;\n\n constructor(status: number, code: string, extra: { until?: string; detail?: string } = {}) {\n super(code);\n this.name = 'RunnerError';\n this.status = status;\n this.code = code;\n if (extra.until) this.until = extra.until;\n if (extra.detail) this.detail = extra.detail;\n }\n}\n\n/** When a chat event says the accounts ran out of credit: until when (`no-credit:<iso>`). */\nexport const noCreditUntil = (event: RunnerChatEvent): string | undefined =>\n event.type === 'error' && event.message.startsWith('no-credit:') ? event.message.slice('no-credit:'.length) : undefined;\n\nexport type RunnerClientOptions = {\n /** The address of the runner (`https://runner.example.com`), or of the backend of the host that forwards to it. */\n url: string;\n /** A key of the runner (or the admin token in the console); none when the backend of the host adds it. */\n key?: string;\n /** With a platform key or the admin token: the tenant the requests are for. */\n tenant?: string;\n /** The person the requests are for (needs `act-as-user` with a project key). */\n user?: string;\n fetch?: typeof fetch;\n /** More headers for each request (the session of the host, for its backend). */\n headers?: () => Record<string, string> | Promise<Record<string, string>>;\n};\n\nexport class RunnerClient {\n readonly options: RunnerClientOptions;\n\n constructor(options: RunnerClientOptions) {\n this.options = { ...options, url: options.url.replace(/\\/+$/, '') };\n }\n\n /** The same runner for another tenant or person. */\n as(scope: { tenant?: string; user?: string }): RunnerClient {\n return new RunnerClient({ ...this.options, ...scope });\n }\n\n private async headers(json: boolean): Promise<Record<string, string>> {\n const { key, tenant, user, headers } = this.options;\n return {\n ...(json ? { 'content-type': 'application/json' } : {}),\n ...(key ? { authorization: `Bearer ${key}` } : {}),\n ...(tenant ? { 'x-runner-tenant': tenant } : {}),\n ...(user ? { 'x-runner-user': user } : {}),\n ...(await headers?.()),\n };\n }\n\n /** One request; its JSON, or a RunnerError. */\n async request<T>(method: string, path: string, body?: unknown): Promise<T> {\n const response = await (this.options.fetch ?? fetch)(`${this.options.url}${path}`, {\n method,\n headers: await this.headers(body !== undefined),\n ...(body !== undefined ? { body: JSON.stringify(body) } : {}),\n });\n const text = await response.text();\n let data: Record<string, unknown> = {};\n try {\n data = text ? JSON.parse(text) as Record<string, unknown> : {};\n } catch {\n // Not JSON (a proxy in between): said by its status.\n }\n if (!response.ok) {\n throw new RunnerError(response.status, typeof data.error === 'string' ? data.error : `http-${response.status}`, {\n ...(typeof data.until === 'string' ? { until: data.until } : {}),\n ...(typeof data.detail === 'string' ? { detail: data.detail } : {}),\n });\n }\n return data as T;\n }\n\n // ── Public ──────────────────────────────────────────────────────────────────────────────────────────────\n health(): Promise<RunnerHealth> {\n return this.request('GET', '/health');\n }\n\n /** A pairing code (printed by the installer) → a platform key, seen once. */\n pair(code: string, name?: string): Promise<{ key: string; record: RunnerKey; version: string }> {\n return this.request('POST', '/v1/pair', { code, ...(name ? { name } : {}) });\n }\n\n /**\n * Asks to connect (device flow): the admin of the runner approves it in the console at `approveUrl`, where the\n * same `code` is shown; meanwhile `pollPairing(request)` every `interval` seconds, until it gives the key.\n */\n requestPairing(name: string): Promise<RunnerPairingRequest> {\n return this.request('POST', '/v1/pair/requests', { name });\n }\n\n pollPairing(request: string): Promise<RunnerPairingPoll> {\n return this.request('POST', '/v1/pair/requests/poll', { request });\n }\n\n info(): Promise<{ version: string; harnesses: string[]; capabilities: Record<string, boolean>; permissions: RunnerPermission[]; tenant?: string }> {\n return this.request('GET', '/v1/info');\n }\n\n // ── Admin token ─────────────────────────────────────────────────────────────────────────────────────────\n createPairing(): Promise<{ code: string; expiresAt: string }> {\n return this.request('POST', '/v1/admin/pairing');\n }\n\n async pairingRequests(): Promise<RunnerPairingRequestView[]> {\n return (await this.request<{ requests: RunnerPairingRequestView[] }>('GET', '/v1/admin/pairing/requests')).requests;\n }\n\n async answerPairing(code: string, approve: boolean): Promise<RunnerPairingRequestView> {\n return (await this.request<{ request: RunnerPairingRequestView }>('POST', `/v1/admin/pairing/requests/${encodeURIComponent(code)}/${approve ? 'approve' : 'deny'}`)).request;\n }\n\n // ── Platform key ────────────────────────────────────────────────────────────────────────────────────────\n readonly platform = {\n status: (): Promise<RunnerStatus> => this.request('GET', '/v1/platform/status'),\n tenants: async (): Promise<RunnerTenant[]> => (await this.request<{ tenants: RunnerTenant[] }>('GET', '/v1/platform/tenants')).tenants,\n /** A tenant, with its first project key unless `key: false` (seen once: keep it in the backend). */\n createTenant: (id: string, options: { name?: string; key?: boolean; keyPermissions?: RunnerPermission[] } = {}): Promise<{ tenant: RunnerTenant; key?: string; keyRecord?: RunnerKey }> =>\n this.request('POST', '/v1/platform/tenants', { id, ...options }),\n removeTenant: async (id: string): Promise<boolean> => (await this.request<{ removed: boolean }>('DELETE', `/v1/platform/tenants/${encodeURIComponent(id)}`)).removed,\n keys: async (tenant: string): Promise<RunnerKey[]> => (await this.request<{ keys: RunnerKey[] }>('GET', `/v1/platform/tenants/${encodeURIComponent(tenant)}/keys`)).keys,\n createKey: (tenant: string, input: { name?: string; permissions?: RunnerPermission[]; expiresAt?: string | null } = {}): Promise<{ key: string; record: RunnerKey }> =>\n this.request('POST', `/v1/platform/tenants/${encodeURIComponent(tenant)}/keys`, input),\n revokeKey: async (tenant: string, id: string): Promise<boolean> => (await this.request<{ removed: boolean }>('DELETE', `/v1/platform/tenants/${encodeURIComponent(tenant)}/keys/${encodeURIComponent(id)}`)).removed,\n platformKeys: async (): Promise<RunnerKey[]> => (await this.request<{ keys: RunnerKey[] }>('GET', '/v1/platform/keys')).keys,\n revokePlatformKey: async (id: string): Promise<boolean> => (await this.request<{ removed: boolean }>('DELETE', `/v1/platform/keys/${encodeURIComponent(id)}`)).removed,\n };\n\n // ── Accounts of the person (or of the tenant) ───────────────────────────────────────────────────────────\n readonly accounts = {\n list: async (): Promise<{ scope: 'user' | 'tenant'; accounts: RunnerAccount[] }> => this.request('GET', '/v1/accounts'),\n /** The sign-in of a Claude subscription: open `url`, then give the code Anthropic shows to `finishClaudeLogin`. */\n startClaudeLogin: (): Promise<{ url: string }> => this.request('POST', '/v1/accounts/claude-code/login'),\n finishClaudeLogin: async (code: string, label?: string): Promise<RunnerAccount> =>\n (await this.request<{ account: RunnerAccount }>('POST', '/v1/accounts/claude-code/login/code', { code, ...(label ? { label } : {}) })).account,\n /** A token made elsewhere with `claude setup-token`. */\n addClaudeToken: async (token: string, label?: string): Promise<RunnerAccount> =>\n (await this.request<{ account: RunnerAccount }>('POST', '/v1/accounts/claude-code', { token, ...(label ? { label } : {}) })).account,\n addKey: async (provider: 'opencode-go' | 'opencode', key: string, label?: string): Promise<RunnerAccount> =>\n (await this.request<{ account: RunnerAccount }>('POST', `/v1/accounts/${provider}`, { key, ...(label ? { label } : {}) })).account,\n remove: async (provider: RunnerProvider, id: string): Promise<boolean> =>\n (await this.request<{ removed: boolean }>('DELETE', `/v1/accounts/${provider}/${encodeURIComponent(id)}`)).removed,\n order: async (provider: RunnerProvider, ids: string[]): Promise<RunnerAccount[]> =>\n (await this.request<{ accounts: RunnerAccount[] }>('PUT', '/v1/accounts/order', { provider, ids })).accounts,\n };\n\n models(): Promise<RunnerModels> {\n return this.request('GET', '/v1/models');\n }\n\n complete(request: RunnerCompletionRequest): Promise<RunnerCompletion> {\n return this.request('POST', '/v1/complete', request);\n }\n\n // ── Chats ───────────────────────────────────────────────────────────────────────────────────────────────\n readonly chats = {\n /** A chat (id: 8 hex characters, chosen by the client), with the tools the harness may call. */\n start: (id: string, tools?: RunnerChatTool[]): Promise<{ id: string }> => this.request('POST', '/v1/chats', { id, ...(tools ? { tools } : {}) }),\n /** A message: its events as they come. Aborting the signal stops the harness. */\n send: (id: string, message: { text: string; model: RunnerChatModel; attachments?: Array<{ name: string; mimeType: string; base64: string }> }, signal?: AbortSignal): AsyncIterable<RunnerChatEvent> =>\n this.stream(`/v1/chats/${encodeURIComponent(id)}/messages`, message, signal),\n answerCall: async (id: string, callId: string, answer: { result?: unknown; isError?: boolean }): Promise<boolean> =>\n (await this.request<{ answered: boolean }>('POST', `/v1/chats/${encodeURIComponent(id)}/calls/${encodeURIComponent(callId)}`, answer)).answered,\n stop: async (id: string): Promise<boolean> => (await this.request<{ stopped: boolean }>('POST', `/v1/chats/${encodeURIComponent(id)}/stop`)).stopped,\n close: async (id: string): Promise<boolean> => (await this.request<{ closed: boolean }>('DELETE', `/v1/chats/${encodeURIComponent(id)}`)).closed,\n };\n\n private async *stream(path: string, body: unknown, signal?: AbortSignal): AsyncIterable<RunnerChatEvent> {\n const response = await (this.options.fetch ?? fetch)(`${this.options.url}${path}`, { method: 'POST', headers: await this.headers(true), body: JSON.stringify(body), ...(signal ? { signal } : {}) });\n if (!response.ok || !response.body) {\n let code = `http-${response.status}`;\n try {\n const data = await response.json() as { error?: string };\n if (data.error) code = data.error;\n } catch {\n // Said by its status.\n }\n throw new RunnerError(response.status, code);\n }\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n for (;;) {\n const { done, value } = await reader.read();\n buffer += decoder.decode(value ?? new Uint8Array(), { stream: !done });\n const lines = buffer.split('\\n');\n buffer = done ? '' : lines.pop() ?? '';\n for (const line of lines) {\n if (!line.trim()) continue;\n let event: RunnerChatEvent | { type: 'ping' };\n try {\n event = JSON.parse(line) as RunnerChatEvent | { type: 'ping' };\n } catch {\n continue;\n }\n if (event.type !== 'ping') yield event;\n }\n if (done) return;\n }\n }\n}\n\n// ── For the backend of a host ───────────────────────────────────────────────────────────────────────────────\n\n/** The routes the people of a tenant may reach through the backend of the host: never the platform ones. */\nconst PERSON_ROUTES = /^\\/v1\\/(info|models|complete|accounts(\\/[A-Za-z0-9_.:-]+){0,3}|chats(\\/[a-f0-9]{8}(\\/(messages|stop|calls\\/[a-f0-9]{12}))?)?)$/;\n\nexport type RunnerProxyTarget = {\n /** The address of the runner of this tenant. */\n url: string;\n /** A project key of the tenant (with `act-as-user`), or a platform key with `tenant`. */\n key: string;\n tenant?: string;\n /** The signed-in person, verified by the host. */\n user: string;\n};\n\n/**\n * Forwards a request of a signed-in person to their runner: only the routes of a person, with the key, tenant and\n * person added by the host (whatever the browser sent for them is dropped). Streams answers (chat replies) as they\n * come. `path` is the path of the runner, e.g. `/v1/models` (the host strips its own prefix).\n */\nexport async function forwardToRunner(request: Request, path: string, target: RunnerProxyTarget, fetchImpl: typeof fetch = fetch): Promise<Response> {\n if (!PERSON_ROUTES.test(path)) return new Response(JSON.stringify({ error: 'not found' }), { status: 404, headers: { 'content-type': 'application/json' } });\n if (!['GET', 'POST', 'PUT', 'DELETE'].includes(request.method)) return new Response(JSON.stringify({ error: 'not found' }), { status: 404, headers: { 'content-type': 'application/json' } });\n const headers: Record<string, string> = {\n authorization: `Bearer ${target.key}`,\n 'x-runner-user': target.user,\n ...(target.tenant ? { 'x-runner-tenant': target.tenant } : {}),\n };\n const type = request.headers.get('content-type');\n if (type) headers['content-type'] = type;\n const body = request.method === 'GET' || request.method === 'DELETE' ? undefined : await request.arrayBuffer();\n const url = new URL(request.url);\n const answer = await fetchImpl(`${target.url.replace(/\\/+$/, '')}${path}${url.search}`, {\n method: request.method,\n headers,\n ...(body ? { body } : {}),\n signal: request.signal,\n });\n return new Response(answer.body, {\n status: answer.status,\n headers: {\n 'content-type': answer.headers.get('content-type') ?? 'application/json',\n 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AAmBA,EAAO,MAAO,EAAI,CAAC,CAChE,EACMC,EAAOhB,EAAQ,QAAQ,IAAI,cAAc,EAC3CgB,IAAM,EAAQ,gBAAkBA,GACpC,IAAMzB,EAAOS,EAAQ,SAAW,OAASA,EAAQ,SAAW,SAAW,IAAA,GAAY,MAAMA,EAAQ,YAAY,EACvGiB,EAAM,IAAI,IAAIjB,EAAQ,GAAG,EACzBK,EAAS,MAAMa,EAAU,GAAGH,EAAO,IAAI,QAAQ,OAAQ,EAAE,IAAIzB,IAAO2B,EAAI,SAAU,CACpF,OAAQjB,EAAQ,OAChB,UACA,GAAIT,EAAO,CAAE,MAAK,EAAI,CAAC,EACvB,OAAQS,EAAQ,MACpB,CAAC,EACD,OAAO,IAAI,SAASK,EAAO,KAAM,CAC7B,OAAQA,EAAO,OACf,QAAS,CACL,eAAgBA,EAAO,QAAQ,IAAI,cAAc,GAAK,mBACtD,gBAAiB,WACjB,oBAAqB,IACzB,CACJ,CAAC,CACL,C"}
|
|
1
|
+
{"version":3,"file":"client.js","names":["RUNNER_KEY_PROVIDERS","RunnerError","code","status","extra","noCreditUntil","event","RunnerClient","options","scope","json","key","tenant","user","headers","response","path","body","text","data","name","project","approve","id","input","label","provider","request","tools","message","signal","callId","answer","reader","decoder","buffer","value","done","lines","line","PERSON_ROUTES","forwardToRunner","target","type","url","fetchImpl"],"sources":["../src/client/index.ts"],"sourcesContent":["// @llmnative/runner/client — the client of the API v1 of the LLMNative Runner, for the browser and for Node.\n//\n// A key never belongs in the browser of the people of a tenant: a host app talks to the runner from its backend\n// (`createRunnerProxy` forwards the requests of its signed-in people, adding the key, the tenant and the person),\n// and its pages use `RunnerClient` against that backend. The console of the runner and a personal app with a key of\n// its own use `RunnerClient` directly.\n\n/** The providers paid by use whose API key the runner keeps and opencode runs (ids of @llmnative/react). */\nexport const RUNNER_KEY_PROVIDERS = ['anthropic', 'openai', 'gemini', 'mistral', 'deepseek', 'openrouter'] as const;\nexport type RunnerKeyProvider = (typeof RUNNER_KEY_PROVIDERS)[number];\nexport type RunnerProvider = 'claude-code' | 'opencode-go' | 'opencode' | RunnerKeyProvider;\nexport type RunnerPermission = 'complete' | 'chat' | 'chat:tools' | 'accounts' | 'accounts:tenant' | 'act-as-user' | 'keys';\n\nexport type RunnerAccount = {\n provider: RunnerProvider;\n id: string;\n label?: string;\n /** When it was connected. */\n at: string;\n scope: 'user' | 'tenant';\n /** Out of credit until then (the limit of a subscription); absent when it has credit. */\n noCreditUntil?: string;\n};\n\nexport type RunnerModels = {\n /** `models`: the list a subscription serves; empty for a provider by use, which runs any model the client names. */\n providers: Array<{ id: RunnerProvider; kind: 'subscription' | 'usage'; models: string[]; accounts: number; available: number; yours: number; tenant: number }>;\n};\n\nexport type RunnerTenant = { id: string; name: string; createdAt: string; usersWithAccounts?: number };\nexport type RunnerKey = { id: string; kind: 'platform' | 'project'; tenant?: string; /** Platform keys: the project whose tenants (`<project>`, `<project>-…`) it owns. */ project?: string; name: string; permissions: RunnerPermission[]; createdAt: string; expiresAt: string | null };\n\nexport type RunnerStatus = {\n version: string;\n agentImage: string;\n url?: string;\n /** The project of the platform key asking: the tenants listed are its own only. */\n project?: string;\n load: { chats: number; answering: number; completions: number; maxChats: number };\n machine: { totalBytes: number; availableBytes: number; cpus: number };\n tenants: RunnerTenant[];\n};\n\n/** A pairing request made by a platform: `request` is its secret (keep it in the backend), `code` is shown on both sides. */\nexport type RunnerPairingRequest = { request: string; code: string; approveUrl: string; expiresAt: string; interval: number };\nexport type RunnerPairingPoll = { status: 'pending' | 'denied' | 'expired' } | { status: 'approved'; key: string; record: RunnerKey; version: string };\nexport type RunnerPairingRequestView = { code: string; name: string; project?: string; from?: string; createdAt: string; expiresAt: string };\nexport type RunnerHealth = { ok: boolean; version: string; chats: number; answering: number; completions: number; maxChats: number };\n\nexport type RunnerCompletionRequest = { provider: RunnerProvider; model: string; prompt: string; effort?: 'low' | 'medium' | 'high' | 'xhigh' | 'max' };\nexport type RunnerCompletion = { text: string; usage?: { inputTokens: number; outputTokens: number } };\n\nexport type RunnerChatTool = { name: string; description: string; inputSchema: Record<string, unknown>; endsTurn?: boolean };\nexport type RunnerChatModel = { provider: string; model: string; variant?: string; name?: string; effort?: string };\nexport type RunnerChatEvent =\n | { type: 'text'; text: string }\n | { type: 'reasoning'; text: string }\n | { type: 'step'; id: string; label: string; status: 'running' | 'done' }\n | { type: 'tool-call'; id: string; name: string; input: Record<string, unknown> }\n | { type: 'done' }\n | { type: 'error'; message: string };\n\n/** An error of the runner: its status and code (`no-credit`, `busy`…), and for `no-credit` until when. */\nexport class RunnerError extends Error {\n readonly status: number;\n readonly code: string;\n readonly until?: string;\n readonly detail?: string;\n\n constructor(status: number, code: string, extra: { until?: string; detail?: string } = {}) {\n super(code);\n this.name = 'RunnerError';\n this.status = status;\n this.code = code;\n if (extra.until) this.until = extra.until;\n if (extra.detail) this.detail = extra.detail;\n }\n}\n\n/** When a chat event says the accounts ran out of credit: until when (`no-credit:<iso>`). */\nexport const noCreditUntil = (event: RunnerChatEvent): string | undefined =>\n event.type === 'error' && event.message.startsWith('no-credit:') ? event.message.slice('no-credit:'.length) : undefined;\n\nexport type RunnerClientOptions = {\n /** The address of the runner (`https://runner.example.com`), or of the backend of the host that forwards to it. */\n url: string;\n /** A key of the runner (or the admin token in the console); none when the backend of the host adds it. */\n key?: string;\n /** With a platform key or the admin token: the tenant the requests are for. */\n tenant?: string;\n /** The person the requests are for (needs `act-as-user` with a project key). */\n user?: string;\n fetch?: typeof fetch;\n /** More headers for each request (the session of the host, for its backend). */\n headers?: () => Record<string, string> | Promise<Record<string, string>>;\n};\n\nexport class RunnerClient {\n readonly options: RunnerClientOptions;\n\n constructor(options: RunnerClientOptions) {\n this.options = { ...options, url: options.url.replace(/\\/+$/, '') };\n }\n\n /** The same runner for another tenant or person. */\n as(scope: { tenant?: string; user?: string }): RunnerClient {\n return new RunnerClient({ ...this.options, ...scope });\n }\n\n private async headers(json: boolean): Promise<Record<string, string>> {\n const { key, tenant, user, headers } = this.options;\n return {\n ...(json ? { 'content-type': 'application/json' } : {}),\n ...(key ? { authorization: `Bearer ${key}` } : {}),\n ...(tenant ? { 'x-runner-tenant': tenant } : {}),\n ...(user ? { 'x-runner-user': user } : {}),\n ...(await headers?.()),\n };\n }\n\n /** One request; its JSON, or a RunnerError. */\n async request<T>(method: string, path: string, body?: unknown): Promise<T> {\n const response = await (this.options.fetch ?? fetch)(`${this.options.url}${path}`, {\n method,\n headers: await this.headers(body !== undefined),\n ...(body !== undefined ? { body: JSON.stringify(body) } : {}),\n });\n const text = await response.text();\n let data: Record<string, unknown> = {};\n try {\n data = text ? JSON.parse(text) as Record<string, unknown> : {};\n } catch {\n // Not JSON (a proxy in between): said by its status.\n }\n if (!response.ok) {\n throw new RunnerError(response.status, typeof data.error === 'string' ? data.error : `http-${response.status}`, {\n ...(typeof data.until === 'string' ? { until: data.until } : {}),\n ...(typeof data.detail === 'string' ? { detail: data.detail } : {}),\n });\n }\n return data as T;\n }\n\n // ── Public ──────────────────────────────────────────────────────────────────────────────────────────────\n health(): Promise<RunnerHealth> {\n return this.request('GET', '/health');\n }\n\n /** A pairing code (printed by the installer) → a platform key, seen once. */\n /** `project`: the platform key owns only the tenants of that project (`<project>`, `<project>-…`). */\n pair(code: string, name?: string, project?: string): Promise<{ key: string; record: RunnerKey; version: string }> {\n return this.request('POST', '/v1/pair', { code, ...(name ? { name } : {}), ...(project ? { project } : {}) });\n }\n\n /**\n * Asks to connect (device flow): the admin of the runner approves it in the console at `approveUrl`, where the\n * same `code` is shown; meanwhile `pollPairing(request)` every `interval` seconds, until it gives the key.\n */\n requestPairing(name: string, project?: string): Promise<RunnerPairingRequest> {\n return this.request('POST', '/v1/pair/requests', { name, ...(project ? { project } : {}) });\n }\n\n pollPairing(request: string): Promise<RunnerPairingPoll> {\n return this.request('POST', '/v1/pair/requests/poll', { request });\n }\n\n info(): Promise<{ version: string; harnesses: string[]; capabilities: Record<string, boolean>; permissions: RunnerPermission[]; tenant?: string }> {\n return this.request('GET', '/v1/info');\n }\n\n // ── Admin token ─────────────────────────────────────────────────────────────────────────────────────────\n createPairing(): Promise<{ code: string; expiresAt: string }> {\n return this.request('POST', '/v1/admin/pairing');\n }\n\n async pairingRequests(): Promise<RunnerPairingRequestView[]> {\n return (await this.request<{ requests: RunnerPairingRequestView[] }>('GET', '/v1/admin/pairing/requests')).requests;\n }\n\n async answerPairing(code: string, approve: boolean): Promise<RunnerPairingRequestView> {\n return (await this.request<{ request: RunnerPairingRequestView }>('POST', `/v1/admin/pairing/requests/${encodeURIComponent(code)}/${approve ? 'approve' : 'deny'}`)).request;\n }\n\n /** The project of a platform key (null: every tenant, as keys made before 1.2). */\n async setKeyProject(id: string, project: string | null): Promise<RunnerKey> {\n return (await this.request<{ record: RunnerKey }>('PUT', `/v1/admin/keys/${encodeURIComponent(id)}/project`, { project })).record;\n }\n\n // ── Platform key ────────────────────────────────────────────────────────────────────────────────────────\n readonly platform = {\n status: (): Promise<RunnerStatus> => this.request('GET', '/v1/platform/status'),\n tenants: async (): Promise<RunnerTenant[]> => (await this.request<{ tenants: RunnerTenant[] }>('GET', '/v1/platform/tenants')).tenants,\n /** A tenant, with its first project key unless `key: false` (seen once: keep it in the backend). */\n createTenant: (id: string, options: { name?: string; key?: boolean; keyPermissions?: RunnerPermission[] } = {}): Promise<{ tenant: RunnerTenant; key?: string; keyRecord?: RunnerKey }> =>\n this.request('POST', '/v1/platform/tenants', { id, ...options }),\n removeTenant: async (id: string): Promise<boolean> => (await this.request<{ removed: boolean }>('DELETE', `/v1/platform/tenants/${encodeURIComponent(id)}`)).removed,\n keys: async (tenant: string): Promise<RunnerKey[]> => (await this.request<{ keys: RunnerKey[] }>('GET', `/v1/platform/tenants/${encodeURIComponent(tenant)}/keys`)).keys,\n createKey: (tenant: string, input: { name?: string; permissions?: RunnerPermission[]; expiresAt?: string | null } = {}): Promise<{ key: string; record: RunnerKey }> =>\n this.request('POST', `/v1/platform/tenants/${encodeURIComponent(tenant)}/keys`, input),\n revokeKey: async (tenant: string, id: string): Promise<boolean> => (await this.request<{ removed: boolean }>('DELETE', `/v1/platform/tenants/${encodeURIComponent(tenant)}/keys/${encodeURIComponent(id)}`)).removed,\n platformKeys: async (): Promise<RunnerKey[]> => (await this.request<{ keys: RunnerKey[] }>('GET', '/v1/platform/keys')).keys,\n revokePlatformKey: async (id: string): Promise<boolean> => (await this.request<{ removed: boolean }>('DELETE', `/v1/platform/keys/${encodeURIComponent(id)}`)).removed,\n };\n\n // ── Accounts of the person (or of the tenant) ───────────────────────────────────────────────────────────\n readonly accounts = {\n list: async (): Promise<{ scope: 'user' | 'tenant'; accounts: RunnerAccount[] }> => this.request('GET', '/v1/accounts'),\n /** The sign-in of a Claude subscription: open `url`, then give the code Anthropic shows to `finishClaudeLogin`. */\n startClaudeLogin: (): Promise<{ url: string }> => this.request('POST', '/v1/accounts/claude-code/login'),\n finishClaudeLogin: async (code: string, label?: string): Promise<RunnerAccount> =>\n (await this.request<{ account: RunnerAccount }>('POST', '/v1/accounts/claude-code/login/code', { code, ...(label ? { label } : {}) })).account,\n /** A token made elsewhere with `claude setup-token`. */\n addClaudeToken: async (token: string, label?: string): Promise<RunnerAccount> =>\n (await this.request<{ account: RunnerAccount }>('POST', '/v1/accounts/claude-code', { token, ...(label ? { label } : {}) })).account,\n /** A key: OpenCode Go/Zen, or the API key of a provider by use the runner keeps (opencode runs it). */\n addKey: async (provider: Exclude<RunnerProvider, 'claude-code'>, key: string, label?: string): Promise<RunnerAccount> =>\n (await this.request<{ account: RunnerAccount }>('POST', `/v1/accounts/${provider}`, { key, ...(label ? { label } : {}) })).account,\n remove: async (provider: RunnerProvider, id: string): Promise<boolean> =>\n (await this.request<{ removed: boolean }>('DELETE', `/v1/accounts/${provider}/${encodeURIComponent(id)}`)).removed,\n order: async (provider: RunnerProvider, ids: string[]): Promise<RunnerAccount[]> =>\n (await this.request<{ accounts: RunnerAccount[] }>('PUT', '/v1/accounts/order', { provider, ids })).accounts,\n };\n\n models(): Promise<RunnerModels> {\n return this.request('GET', '/v1/models');\n }\n\n complete(request: RunnerCompletionRequest): Promise<RunnerCompletion> {\n return this.request('POST', '/v1/complete', request);\n }\n\n // ── Chats ───────────────────────────────────────────────────────────────────────────────────────────────\n readonly chats = {\n /** A chat (id: 8 hex characters, chosen by the client), with the tools the harness may call. */\n start: (id: string, tools?: RunnerChatTool[]): Promise<{ id: string }> => this.request('POST', '/v1/chats', { id, ...(tools ? { tools } : {}) }),\n /** A message: its events as they come. Aborting the signal stops the harness. */\n send: (id: string, message: { text: string; model: RunnerChatModel; attachments?: Array<{ name: string; mimeType: string; base64: string }> }, signal?: AbortSignal): AsyncIterable<RunnerChatEvent> =>\n this.stream(`/v1/chats/${encodeURIComponent(id)}/messages`, message, signal),\n answerCall: async (id: string, callId: string, answer: { result?: unknown; isError?: boolean }): Promise<boolean> =>\n (await this.request<{ answered: boolean }>('POST', `/v1/chats/${encodeURIComponent(id)}/calls/${encodeURIComponent(callId)}`, answer)).answered,\n stop: async (id: string): Promise<boolean> => (await this.request<{ stopped: boolean }>('POST', `/v1/chats/${encodeURIComponent(id)}/stop`)).stopped,\n close: async (id: string): Promise<boolean> => (await this.request<{ closed: boolean }>('DELETE', `/v1/chats/${encodeURIComponent(id)}`)).closed,\n };\n\n private async *stream(path: string, body: unknown, signal?: AbortSignal): AsyncIterable<RunnerChatEvent> {\n const response = await (this.options.fetch ?? fetch)(`${this.options.url}${path}`, { method: 'POST', headers: await this.headers(true), body: JSON.stringify(body), ...(signal ? { signal } : {}) });\n if (!response.ok || !response.body) {\n let code = `http-${response.status}`;\n try {\n const data = await response.json() as { error?: string };\n if (data.error) code = data.error;\n } catch {\n // Said by its status.\n }\n throw new RunnerError(response.status, code);\n }\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n for (;;) {\n const { done, value } = await reader.read();\n buffer += decoder.decode(value ?? new Uint8Array(), { stream: !done });\n const lines = buffer.split('\\n');\n buffer = done ? '' : lines.pop() ?? '';\n for (const line of lines) {\n if (!line.trim()) continue;\n let event: RunnerChatEvent | { type: 'ping' };\n try {\n event = JSON.parse(line) as RunnerChatEvent | { type: 'ping' };\n } catch {\n continue;\n }\n if (event.type !== 'ping') yield event;\n }\n if (done) return;\n }\n }\n}\n\n// ── For the backend of a host ───────────────────────────────────────────────────────────────────────────────\n\n/** The routes the people of a tenant may reach through the backend of the host: never the platform ones. */\nconst PERSON_ROUTES = /^\\/v1\\/(info|models|complete|accounts(\\/[A-Za-z0-9_.:-]+){0,3}|chats(\\/[a-f0-9]{8}(\\/(messages|stop|calls\\/[a-f0-9]{12}))?)?)$/;\n\nexport type RunnerProxyTarget = {\n /** The address of the runner of this tenant. */\n url: string;\n /** A project key of the tenant (with `act-as-user`), or a platform key with `tenant`. */\n key: string;\n tenant?: string;\n /** The signed-in person, verified by the host. */\n user: string;\n};\n\n/**\n * Forwards a request of a signed-in person to their runner: only the routes of a person, with the key, tenant and\n * person added by the host (whatever the browser sent for them is dropped). Streams answers (chat replies) as they\n * come. `path` is the path of the runner, e.g. `/v1/models` (the host strips its own prefix).\n */\nexport async function forwardToRunner(request: Request, path: string, target: RunnerProxyTarget, fetchImpl: typeof fetch = fetch): Promise<Response> {\n if (!PERSON_ROUTES.test(path)) return new Response(JSON.stringify({ error: 'not found' }), { status: 404, headers: { 'content-type': 'application/json' } });\n if (!['GET', 'POST', 'PUT', 'DELETE'].includes(request.method)) return new Response(JSON.stringify({ error: 'not found' }), { status: 404, headers: { 'content-type': 'application/json' } });\n const headers: Record<string, string> = {\n authorization: `Bearer ${target.key}`,\n 'x-runner-user': target.user,\n ...(target.tenant ? { 'x-runner-tenant': target.tenant } : {}),\n };\n const type = request.headers.get('content-type');\n if (type) headers['content-type'] = type;\n const body = request.method === 'GET' || request.method === 'DELETE' ? undefined : await request.arrayBuffer();\n const url = new URL(request.url);\n const answer = await fetchImpl(`${target.url.replace(/\\/+$/, '')}${path}${url.search}`, {\n method: request.method,\n headers,\n ...(body ? { body } : {}),\n signal: request.signal,\n });\n return new Response(answer.body, {\n status: answer.status,\n headers: {\n 'content-type': answer.headers.get('content-type') ?? 'application/json',\n 'cache-control': 'no-store',\n 'x-accel-buffering': 'no',\n },\n });\n}\n"],"mappings":"A,mEAQA,IAAaA,EAAuB,CAAC,YAAa,SAAU,SAAU,UAAW,WAAY,YAAY,EAuD5FC,EAAb,cAAiC,KAAM,CACnC,OACA,KACA,MACA,OAEA,YAAY,EAAgB,EAAc,EAA6C,CAAC,EAAG,CACvF,MAAMC,CAAI,EACV,KAAK,KAAO,cACZ,KAAK,OAASC,EACd,KAAK,KAAOD,EACRE,EAAM,QAAO,KAAK,MAAQA,EAAM,OAChCA,EAAM,SAAQ,KAAK,OAASA,EAAM,OAC1C,CACJ,EAGaC,EAAiB,GAC1BC,EAAM,OAAS,SAAWA,EAAM,QAAQ,WAAW,YAAY,EAAIA,EAAM,QAAQ,MAAM,EAAmB,EAAI,IAAA,GAgBrGC,EAAb,MAAaA,CAAa,CACtB,QAEA,YAAY,EAA8B,CACtC,KAAK,QAAU,CAAE,GAAGC,EAAS,IAAKA,EAAQ,IAAI,QAAQ,OAAQ,EAAE,CAAE,CACtE,CAGA,GAAG,EAAyD,CACxD,OAAO,IAAID,EAAa,CAAE,GAAG,KAAK,QAAS,GAAGE,CAAM,CAAC,CACzD,CAEA,MAAc,QAAQ,EAAgD,CAClE,GAAM,CAAE,MAAK,SAAQ,OAAM,WAAY,KAAK,QAC5C,MAAO,CACH,GAAIC,EAAO,CAAE,eAAgB,kBAAmB,EAAI,CAAC,EACrD,GAAIC,EAAM,CAAE,cAAe,UAAUA,GAAM,EAAI,CAAC,EAChD,GAAIC,EAAS,CAAE,kBAAmBA,CAAO,EAAI,CAAC,EAC9C,GAAIC,EAAO,CAAE,gBAAiBA,CAAK,EAAI,CAAC,EACxC,GAAI,MAAMC,IAAU,CACxB,CACJ,CAGA,MAAM,QAAW,EAAgB,EAAc,EAA4B,CACvE,IAAMC,EAAW,MAAO,KAAK,QAAQ,OA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], t = class extends Error {
|
|
3
10
|
status;
|
|
4
11
|
code;
|
|
5
12
|
until;
|
|
@@ -7,7 +14,7 @@ var e = class extends Error {
|
|
|
7
14
|
constructor(e, t, n = {}) {
|
|
8
15
|
super(t), this.name = "RunnerError", this.status = e, this.code = t, n.until && (this.until = n.until), n.detail && (this.detail = n.detail);
|
|
9
16
|
}
|
|
10
|
-
},
|
|
17
|
+
}, n = (e) => e.type === "error" && e.message.startsWith("no-credit:") ? e.message.slice(10) : void 0, r = class e {
|
|
11
18
|
options;
|
|
12
19
|
constructor(e) {
|
|
13
20
|
this.options = {
|
|
@@ -15,10 +22,10 @@ var e = class extends Error {
|
|
|
15
22
|
url: e.url.replace(/\/+$/, "")
|
|
16
23
|
};
|
|
17
24
|
}
|
|
18
|
-
as(
|
|
19
|
-
return new
|
|
25
|
+
as(t) {
|
|
26
|
+
return new e({
|
|
20
27
|
...this.options,
|
|
21
|
-
...
|
|
28
|
+
...t
|
|
22
29
|
});
|
|
23
30
|
}
|
|
24
31
|
async headers(e) {
|
|
@@ -31,16 +38,16 @@ var e = class extends Error {
|
|
|
31
38
|
...await i?.()
|
|
32
39
|
};
|
|
33
40
|
}
|
|
34
|
-
async request(
|
|
41
|
+
async request(e, n, r) {
|
|
35
42
|
let i = await (this.options.fetch ?? fetch)(`${this.options.url}${n}`, {
|
|
36
|
-
method:
|
|
43
|
+
method: e,
|
|
37
44
|
headers: await this.headers(r !== void 0),
|
|
38
45
|
...r === void 0 ? {} : { body: JSON.stringify(r) }
|
|
39
46
|
}), a = await i.text(), o = {};
|
|
40
47
|
try {
|
|
41
48
|
o = a ? JSON.parse(a) : {};
|
|
42
49
|
} catch {}
|
|
43
|
-
if (!i.ok) throw new
|
|
50
|
+
if (!i.ok) throw new t(i.status, typeof o.error == "string" ? o.error : `http-${i.status}`, {
|
|
44
51
|
...typeof o.until == "string" ? { until: o.until } : {},
|
|
45
52
|
...typeof o.detail == "string" ? { detail: o.detail } : {}
|
|
46
53
|
});
|
|
@@ -49,14 +56,18 @@ var e = class extends Error {
|
|
|
49
56
|
health() {
|
|
50
57
|
return this.request("GET", "/health");
|
|
51
58
|
}
|
|
52
|
-
pair(e, t) {
|
|
59
|
+
pair(e, t, n) {
|
|
53
60
|
return this.request("POST", "/v1/pair", {
|
|
54
61
|
code: e,
|
|
55
|
-
...t ? { name: t } : {}
|
|
62
|
+
...t ? { name: t } : {},
|
|
63
|
+
...n ? { project: n } : {}
|
|
56
64
|
});
|
|
57
65
|
}
|
|
58
|
-
requestPairing(e) {
|
|
59
|
-
return this.request("POST", "/v1/pair/requests", {
|
|
66
|
+
requestPairing(e, t) {
|
|
67
|
+
return this.request("POST", "/v1/pair/requests", {
|
|
68
|
+
name: e,
|
|
69
|
+
...t ? { project: t } : {}
|
|
70
|
+
});
|
|
60
71
|
}
|
|
61
72
|
pollPairing(e) {
|
|
62
73
|
return this.request("POST", "/v1/pair/requests/poll", { request: e });
|
|
@@ -73,6 +84,9 @@ var e = class extends Error {
|
|
|
73
84
|
async answerPairing(e, t) {
|
|
74
85
|
return (await this.request("POST", `/v1/admin/pairing/requests/${encodeURIComponent(e)}/${t ? "approve" : "deny"}`)).request;
|
|
75
86
|
}
|
|
87
|
+
async setKeyProject(e, t) {
|
|
88
|
+
return (await this.request("PUT", `/v1/admin/keys/${encodeURIComponent(e)}/project`, { project: t })).record;
|
|
89
|
+
}
|
|
76
90
|
platform = {
|
|
77
91
|
status: () => this.request("GET", "/v1/platform/status"),
|
|
78
92
|
tenants: async () => (await this.request("GET", "/v1/platform/tenants")).tenants,
|
|
@@ -124,20 +138,20 @@ var e = class extends Error {
|
|
|
124
138
|
stop: async (e) => (await this.request("POST", `/v1/chats/${encodeURIComponent(e)}/stop`)).stopped,
|
|
125
139
|
close: async (e) => (await this.request("DELETE", `/v1/chats/${encodeURIComponent(e)}`)).closed
|
|
126
140
|
};
|
|
127
|
-
async *stream(
|
|
128
|
-
let i = await (this.options.fetch ?? fetch)(`${this.options.url}${
|
|
141
|
+
async *stream(e, n, r) {
|
|
142
|
+
let i = await (this.options.fetch ?? fetch)(`${this.options.url}${e}`, {
|
|
129
143
|
method: "POST",
|
|
130
144
|
headers: await this.headers(!0),
|
|
131
145
|
body: JSON.stringify(n),
|
|
132
146
|
...r ? { signal: r } : {}
|
|
133
147
|
});
|
|
134
148
|
if (!i.ok || !i.body) {
|
|
135
|
-
let
|
|
149
|
+
let e = `http-${i.status}`;
|
|
136
150
|
try {
|
|
137
|
-
let
|
|
138
|
-
|
|
151
|
+
let t = await i.json();
|
|
152
|
+
t.error && (e = t.error);
|
|
139
153
|
} catch {}
|
|
140
|
-
throw new
|
|
154
|
+
throw new t(i.status, e);
|
|
141
155
|
}
|
|
142
156
|
let a = i.body.getReader(), o = new TextDecoder(), s = "";
|
|
143
157
|
for (;;) {
|
|
@@ -158,9 +172,9 @@ var e = class extends Error {
|
|
|
158
172
|
if (e) return;
|
|
159
173
|
}
|
|
160
174
|
}
|
|
161
|
-
},
|
|
162
|
-
async function
|
|
163
|
-
if (!
|
|
175
|
+
}, i = /^\/v1\/(info|models|complete|accounts(\/[A-Za-z0-9_.:-]+){0,3}|chats(\/[a-f0-9]{8}(\/(messages|stop|calls\/[a-f0-9]{12}))?)?)$/;
|
|
176
|
+
async function a(e, t, n, r = fetch) {
|
|
177
|
+
if (!i.test(t) || ![
|
|
164
178
|
"GET",
|
|
165
179
|
"POST",
|
|
166
180
|
"PUT",
|
|
@@ -175,7 +189,7 @@ async function i(e, t, n, i = fetch) {
|
|
|
175
189
|
...n.tenant ? { "x-runner-tenant": n.tenant } : {}
|
|
176
190
|
}, o = e.headers.get("content-type");
|
|
177
191
|
o && (a["content-type"] = o);
|
|
178
|
-
let s = e.method === "GET" || e.method === "DELETE" ? void 0 : await e.arrayBuffer(), c = new URL(e.url), l = await
|
|
192
|
+
let s = e.method === "GET" || e.method === "DELETE" ? void 0 : await e.arrayBuffer(), c = new URL(e.url), l = await r(`${n.url.replace(/\/+$/, "")}${t}${c.search}`, {
|
|
179
193
|
method: e.method,
|
|
180
194
|
headers: a,
|
|
181
195
|
...s ? { body: s } : {},
|
|
@@ -190,6 +204,6 @@ async function i(e, t, n, i = fetch) {
|
|
|
190
204
|
}
|
|
191
205
|
});
|
|
192
206
|
}
|
|
193
|
-
export {
|
|
207
|
+
export { e as RUNNER_KEY_PROVIDERS, r as RunnerClient, t as RunnerError, a as forwardToRunner, n as noCreditUntil };
|
|
194
208
|
|
|
195
209
|
//# sourceMappingURL=client.mjs.map
|
package/dist/client.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.mjs","names":["RunnerError","code","status","extra","noCreditUntil","event","RunnerClient","options","scope","json","key","tenant","user","headers","response","path","body","text","data","name","approve","id","input","label","provider","request","tools","message","signal","callId","answer","reader","decoder","buffer","value","done","lines","line","PERSON_ROUTES","forwardToRunner","target","type","url","fetchImpl"],"sources":["../src/client/index.ts"],"sourcesContent":["// @llmnative/runner/client — the client of the API v1 of the LLMNative Runner, for the browser and for Node.\n//\n// A key never belongs in the browser of the people of a tenant: a host app talks to the runner from its backend\n// (`createRunnerProxy` forwards the requests of its signed-in people, adding the key, the tenant and the person),\n// and its pages use `RunnerClient` against that backend. The console of the runner and a personal app with a key of\n// its own use `RunnerClient` directly.\n\nexport type RunnerProvider = 'claude-code' | 'opencode-go' | 'opencode';\nexport type RunnerPermission = 'complete' | 'chat' | 'chat:tools' | 'accounts' | 'accounts:tenant' | 'act-as-user' | 'keys';\n\nexport type RunnerAccount = {\n provider: RunnerProvider;\n id: string;\n label?: string;\n /** When it was connected. */\n at: string;\n scope: 'user' | 'tenant';\n /** Out of credit until then (the limit of a subscription); absent when it has credit. */\n noCreditUntil?: string;\n};\n\nexport type RunnerModels = {\n providers: Array<{ id: 'claude-code' | 'opencode-go'; models: string[]; accounts: number; available: number; yours: number; tenant: number }>;\n};\n\nexport type RunnerTenant = { id: string; name: string; createdAt: string; usersWithAccounts?: number };\nexport type RunnerKey = { id: string; kind: 'platform' | 'project'; tenant?: string; name: string; permissions: RunnerPermission[]; createdAt: string; expiresAt: string | null };\n\nexport type RunnerStatus = {\n version: string;\n agentImage: string;\n url?: string;\n load: { chats: number; answering: number; completions: number; maxChats: number };\n machine: { totalBytes: number; availableBytes: number; cpus: number };\n tenants: RunnerTenant[];\n};\n\n/** A pairing request made by a platform: `request` is its secret (keep it in the backend), `code` is shown on both sides. */\nexport type RunnerPairingRequest = { request: string; code: string; approveUrl: string; expiresAt: string; interval: number };\nexport type RunnerPairingPoll = { status: 'pending' | 'denied' | 'expired' } | { status: 'approved'; key: string; record: RunnerKey; version: string };\nexport type RunnerPairingRequestView = { code: string; name: string; from?: string; createdAt: string; expiresAt: string };\nexport type RunnerHealth = { ok: boolean; version: string; chats: number; answering: number; completions: number; maxChats: number };\n\nexport type RunnerCompletionRequest = { provider: 'claude-code' | 'opencode-go'; model: string; prompt: string; effort?: 'low' | 'medium' | 'high' | 'xhigh' | 'max' };\nexport type RunnerCompletion = { text: string; usage?: { inputTokens: number; outputTokens: number } };\n\nexport type RunnerChatTool = { name: string; description: string; inputSchema: Record<string, unknown>; endsTurn?: boolean };\nexport type RunnerChatModel = { provider: string; model: string; variant?: string; name?: string; effort?: string };\nexport type RunnerChatEvent =\n | { type: 'text'; text: string }\n | { type: 'reasoning'; text: string }\n | { type: 'step'; id: string; label: string; status: 'running' | 'done' }\n | { type: 'tool-call'; id: string; name: string; input: Record<string, unknown> }\n | { type: 'done' }\n | { type: 'error'; message: string };\n\n/** An error of the runner: its status and code (`no-credit`, `busy`…), and for `no-credit` until when. */\nexport class RunnerError extends Error {\n readonly status: number;\n readonly code: string;\n readonly until?: string;\n readonly detail?: string;\n\n constructor(status: number, code: string, extra: { until?: string; detail?: string } = {}) {\n super(code);\n this.name = 'RunnerError';\n this.status = status;\n this.code = code;\n if (extra.until) this.until = extra.until;\n if (extra.detail) this.detail = extra.detail;\n }\n}\n\n/** When a chat event says the accounts ran out of credit: until when (`no-credit:<iso>`). */\nexport const noCreditUntil = (event: RunnerChatEvent): string | undefined =>\n event.type === 'error' && event.message.startsWith('no-credit:') ? event.message.slice('no-credit:'.length) : undefined;\n\nexport type RunnerClientOptions = {\n /** The address of the runner (`https://runner.example.com`), or of the backend of the host that forwards to it. */\n url: string;\n /** A key of the runner (or the admin token in the console); none when the backend of the host adds it. */\n key?: string;\n /** With a platform key or the admin token: the tenant the requests are for. */\n tenant?: string;\n /** The person the requests are for (needs `act-as-user` with a project key). */\n user?: string;\n fetch?: typeof fetch;\n /** More headers for each request (the session of the host, for its backend). */\n headers?: () => Record<string, string> | Promise<Record<string, string>>;\n};\n\nexport class RunnerClient {\n readonly options: RunnerClientOptions;\n\n constructor(options: RunnerClientOptions) {\n this.options = { ...options, url: options.url.replace(/\\/+$/, '') };\n }\n\n /** The same runner for another tenant or person. */\n as(scope: { tenant?: string; user?: string }): RunnerClient {\n return new RunnerClient({ ...this.options, ...scope });\n }\n\n private async headers(json: boolean): Promise<Record<string, string>> {\n const { key, tenant, user, headers } = this.options;\n return {\n ...(json ? { 'content-type': 'application/json' } : {}),\n ...(key ? { authorization: `Bearer ${key}` } : {}),\n ...(tenant ? { 'x-runner-tenant': tenant } : {}),\n ...(user ? { 'x-runner-user': user } : {}),\n ...(await headers?.()),\n };\n }\n\n /** One request; its JSON, or a RunnerError. */\n async request<T>(method: string, path: string, body?: unknown): Promise<T> {\n const response = await (this.options.fetch ?? fetch)(`${this.options.url}${path}`, {\n method,\n headers: await this.headers(body !== undefined),\n ...(body !== undefined ? { body: JSON.stringify(body) } : {}),\n });\n const text = await response.text();\n let data: Record<string, unknown> = {};\n try {\n data = text ? JSON.parse(text) as Record<string, unknown> : {};\n } catch {\n // Not JSON (a proxy in between): said by its status.\n }\n if (!response.ok) {\n throw new RunnerError(response.status, typeof data.error === 'string' ? data.error : `http-${response.status}`, {\n ...(typeof data.until === 'string' ? { until: data.until } : {}),\n ...(typeof data.detail === 'string' ? { detail: data.detail } : {}),\n });\n }\n return data as T;\n }\n\n // ── Public ──────────────────────────────────────────────────────────────────────────────────────────────\n health(): Promise<RunnerHealth> {\n return this.request('GET', '/health');\n }\n\n /** A pairing code (printed by the installer) → a platform key, seen once. */\n pair(code: string, name?: string): Promise<{ key: string; record: RunnerKey; version: string }> {\n return this.request('POST', '/v1/pair', { code, ...(name ? { name } : {}) });\n }\n\n /**\n * Asks to connect (device flow): the admin of the runner approves it in the console at `approveUrl`, where the\n * same `code` is shown; meanwhile `pollPairing(request)` every `interval` seconds, until it gives the key.\n */\n requestPairing(name: string): Promise<RunnerPairingRequest> {\n return this.request('POST', '/v1/pair/requests', { name });\n }\n\n pollPairing(request: string): Promise<RunnerPairingPoll> {\n return this.request('POST', '/v1/pair/requests/poll', { request });\n }\n\n info(): Promise<{ version: string; harnesses: string[]; capabilities: Record<string, boolean>; permissions: RunnerPermission[]; tenant?: string }> {\n return this.request('GET', '/v1/info');\n }\n\n // ── Admin token ─────────────────────────────────────────────────────────────────────────────────────────\n createPairing(): Promise<{ code: string; expiresAt: string }> {\n return this.request('POST', '/v1/admin/pairing');\n }\n\n async pairingRequests(): Promise<RunnerPairingRequestView[]> {\n return (await this.request<{ requests: RunnerPairingRequestView[] }>('GET', '/v1/admin/pairing/requests')).requests;\n }\n\n async answerPairing(code: string, approve: boolean): Promise<RunnerPairingRequestView> {\n return (await this.request<{ request: RunnerPairingRequestView }>('POST', `/v1/admin/pairing/requests/${encodeURIComponent(code)}/${approve ? 'approve' : 'deny'}`)).request;\n }\n\n // ── Platform key ────────────────────────────────────────────────────────────────────────────────────────\n readonly platform = {\n status: (): Promise<RunnerStatus> => this.request('GET', '/v1/platform/status'),\n tenants: async (): Promise<RunnerTenant[]> => (await this.request<{ tenants: RunnerTenant[] }>('GET', '/v1/platform/tenants')).tenants,\n /** A tenant, with its first project key unless `key: false` (seen once: keep it in the backend). */\n createTenant: (id: string, options: { name?: string; key?: boolean; keyPermissions?: RunnerPermission[] } = {}): Promise<{ tenant: RunnerTenant; key?: string; keyRecord?: RunnerKey }> =>\n this.request('POST', '/v1/platform/tenants', { id, ...options }),\n removeTenant: async (id: string): Promise<boolean> => (await this.request<{ removed: boolean }>('DELETE', `/v1/platform/tenants/${encodeURIComponent(id)}`)).removed,\n keys: async (tenant: string): Promise<RunnerKey[]> => (await this.request<{ keys: RunnerKey[] }>('GET', `/v1/platform/tenants/${encodeURIComponent(tenant)}/keys`)).keys,\n createKey: (tenant: string, input: { name?: string; permissions?: RunnerPermission[]; expiresAt?: string | null } = {}): Promise<{ key: string; record: RunnerKey }> =>\n this.request('POST', `/v1/platform/tenants/${encodeURIComponent(tenant)}/keys`, input),\n revokeKey: async (tenant: string, id: string): Promise<boolean> => (await this.request<{ removed: boolean }>('DELETE', `/v1/platform/tenants/${encodeURIComponent(tenant)}/keys/${encodeURIComponent(id)}`)).removed,\n platformKeys: async (): Promise<RunnerKey[]> => (await this.request<{ keys: RunnerKey[] }>('GET', '/v1/platform/keys')).keys,\n revokePlatformKey: async (id: string): Promise<boolean> => (await this.request<{ removed: boolean }>('DELETE', `/v1/platform/keys/${encodeURIComponent(id)}`)).removed,\n };\n\n // ── Accounts of the person (or of the tenant) ───────────────────────────────────────────────────────────\n readonly accounts = {\n list: async (): Promise<{ scope: 'user' | 'tenant'; accounts: RunnerAccount[] }> => this.request('GET', '/v1/accounts'),\n /** The sign-in of a Claude subscription: open `url`, then give the code Anthropic shows to `finishClaudeLogin`. */\n startClaudeLogin: (): Promise<{ url: string }> => this.request('POST', '/v1/accounts/claude-code/login'),\n finishClaudeLogin: async (code: string, label?: string): Promise<RunnerAccount> =>\n (await this.request<{ account: RunnerAccount }>('POST', '/v1/accounts/claude-code/login/code', { code, ...(label ? { label } : {}) })).account,\n /** A token made elsewhere with `claude setup-token`. */\n addClaudeToken: async (token: string, label?: string): Promise<RunnerAccount> =>\n (await this.request<{ account: RunnerAccount }>('POST', '/v1/accounts/claude-code', { token, ...(label ? { label } : {}) })).account,\n addKey: async (provider: 'opencode-go' | 'opencode', key: string, label?: string): Promise<RunnerAccount> =>\n (await this.request<{ account: RunnerAccount }>('POST', `/v1/accounts/${provider}`, { key, ...(label ? { label } : {}) })).account,\n remove: async (provider: RunnerProvider, id: string): Promise<boolean> =>\n (await this.request<{ removed: boolean }>('DELETE', `/v1/accounts/${provider}/${encodeURIComponent(id)}`)).removed,\n order: async (provider: RunnerProvider, ids: string[]): Promise<RunnerAccount[]> =>\n (await this.request<{ accounts: RunnerAccount[] }>('PUT', '/v1/accounts/order', { provider, ids })).accounts,\n };\n\n models(): Promise<RunnerModels> {\n return this.request('GET', '/v1/models');\n }\n\n complete(request: RunnerCompletionRequest): Promise<RunnerCompletion> {\n return this.request('POST', '/v1/complete', request);\n }\n\n // ── Chats ───────────────────────────────────────────────────────────────────────────────────────────────\n readonly chats = {\n /** A chat (id: 8 hex characters, chosen by the client), with the tools the harness may call. */\n start: (id: string, tools?: RunnerChatTool[]): Promise<{ id: string }> => this.request('POST', '/v1/chats', { id, ...(tools ? { tools } : {}) }),\n /** A message: its events as they come. Aborting the signal stops the harness. */\n send: (id: string, message: { text: string; model: RunnerChatModel; attachments?: Array<{ name: string; mimeType: string; base64: string }> }, signal?: AbortSignal): AsyncIterable<RunnerChatEvent> =>\n this.stream(`/v1/chats/${encodeURIComponent(id)}/messages`, message, signal),\n answerCall: async (id: string, callId: string, answer: { result?: unknown; isError?: boolean }): Promise<boolean> =>\n (await this.request<{ answered: boolean }>('POST', `/v1/chats/${encodeURIComponent(id)}/calls/${encodeURIComponent(callId)}`, answer)).answered,\n stop: async (id: string): Promise<boolean> => (await this.request<{ stopped: boolean }>('POST', `/v1/chats/${encodeURIComponent(id)}/stop`)).stopped,\n close: async (id: string): Promise<boolean> => (await this.request<{ closed: boolean }>('DELETE', `/v1/chats/${encodeURIComponent(id)}`)).closed,\n };\n\n private async *stream(path: string, body: unknown, signal?: AbortSignal): AsyncIterable<RunnerChatEvent> {\n const response = await (this.options.fetch ?? fetch)(`${this.options.url}${path}`, { method: 'POST', headers: await this.headers(true), body: JSON.stringify(body), ...(signal ? { signal } : {}) });\n if (!response.ok || !response.body) {\n let code = `http-${response.status}`;\n try {\n const data = await response.json() as { error?: string };\n if (data.error) code = data.error;\n } catch {\n // Said by its status.\n }\n throw new RunnerError(response.status, code);\n }\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n for (;;) {\n const { done, value } = await reader.read();\n buffer += decoder.decode(value ?? new Uint8Array(), { stream: !done });\n const lines = buffer.split('\\n');\n buffer = done ? '' : lines.pop() ?? '';\n for (const line of lines) {\n if (!line.trim()) continue;\n let event: RunnerChatEvent | { type: 'ping' };\n try {\n event = JSON.parse(line) as RunnerChatEvent | { type: 'ping' };\n } catch {\n continue;\n }\n if (event.type !== 'ping') yield event;\n }\n if (done) return;\n }\n }\n}\n\n// ── For the backend of a host ───────────────────────────────────────────────────────────────────────────────\n\n/** The routes the people of a tenant may reach through the backend of the host: never the platform ones. */\nconst PERSON_ROUTES = /^\\/v1\\/(info|models|complete|accounts(\\/[A-Za-z0-9_.:-]+){0,3}|chats(\\/[a-f0-9]{8}(\\/(messages|stop|calls\\/[a-f0-9]{12}))?)?)$/;\n\nexport type RunnerProxyTarget = {\n /** The address of the runner of this tenant. */\n url: string;\n /** A project key of the tenant (with `act-as-user`), or a platform key with `tenant`. */\n key: string;\n tenant?: string;\n /** The signed-in person, verified by the host. */\n user: string;\n};\n\n/**\n * Forwards a request of a signed-in person to their runner: only the routes of a person, with the key, tenant and\n * person added by the host (whatever the browser sent for them is dropped). Streams answers (chat replies) as they\n * come. `path` is the path of the runner, e.g. `/v1/models` (the host strips its own prefix).\n */\nexport async function forwardToRunner(request: Request, path: string, target: RunnerProxyTarget, fetchImpl: typeof fetch = fetch): Promise<Response> {\n if (!PERSON_ROUTES.test(path)) return new Response(JSON.stringify({ error: 'not found' }), { status: 404, headers: { 'content-type': 'application/json' } });\n if (!['GET', 'POST', 'PUT', 'DELETE'].includes(request.method)) return new Response(JSON.stringify({ error: 'not found' }), { status: 404, headers: { 'content-type': 'application/json' } });\n const headers: Record<string, string> = {\n authorization: `Bearer ${target.key}`,\n 'x-runner-user': target.user,\n ...(target.tenant ? { 'x-runner-tenant': target.tenant } : {}),\n };\n const type = request.headers.get('content-type');\n if (type) headers['content-type'] = type;\n const body = request.method === 'GET' || request.method === 'DELETE' ? undefined : await request.arrayBuffer();\n const url = new URL(request.url);\n const answer = await fetchImpl(`${target.url.replace(/\\/+$/, '')}${path}${url.search}`, {\n method: request.method,\n headers,\n ...(body ? { body } : {}),\n signal: request.signal,\n });\n return new Response(answer.body, {\n status: answer.status,\n headers: {\n 'content-type': answer.headers.get('content-type') ?? 'application/json',\n 'cache-control': 'no-store',\n 'x-accel-buffering': 'no',\n },\n });\n}\n"],"mappings":";AAyDA,IAAaA,IAAb,cAAiC,MAAM;CACnC;CACA;CACA;CACA;CAEA,YAAY,GAAgB,GAAc,IAA6C,CAAC,GAAG;EAMvF,AALA,MAAMC,CAAI,GACV,KAAK,OAAO,eACZ,KAAK,SAASC,GACd,KAAK,OAAOD,GACRE,EAAM,UAAO,KAAK,QAAQA,EAAM,QAChCA,EAAM,WAAQ,KAAK,SAASA,EAAM;CAC1C;AACJ,GAGaC,KAAiB,MAC1BC,EAAM,SAAS,WAAWA,EAAM,QAAQ,WAAW,YAAY,IAAIA,EAAM,QAAQ,MAAM,EAAmB,IAAI,KAAA,GAgBrGC,IAAb,MAAaA,EAAa;CACtB;CAEA,YAAY,GAA8B;EACtC,KAAK,UAAU;GAAE,GAAGC;GAAS,KAAKA,EAAQ,IAAI,QAAQ,QAAQ,EAAE;EAAE;CACtE;CAGA,GAAG,GAAyD;EACxD,OAAO,IAAID,EAAa;GAAE,GAAG,KAAK;GAAS,GAAGE;EAAM,CAAC;CACzD;CAEA,MAAc,QAAQ,GAAgD;EAClE,IAAM,EAAE,QAAK,WAAQ,SAAM,eAAY,KAAK;EAC5C,OAAO;GACH,GAAIC,IAAO,EAAE,gBAAgB,mBAAmB,IAAI,CAAC;GACrD,GAAIC,IAAM,EA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AACJ,GAKMG,IAAgB;AAiBtB,eAAsBC,EAAgB,GAAkB,GAAc,GAA2B,IAA0B,OAA0B;CAEjJ,IADI,CAACD,EAAc,KAAKvB,CAAI,KACxB,CAAC;EAAC;EAAO;EAAQ;EAAO;CAAQ,CAAC,CAAC,SAASU,EAAQ,MAAM,GAAG,OAAO,IAAI,SAAS,KAAK,UAAU,EAAE,OAAO,YAAY,CAAC,GAAG;EAAE,QAAQ;EAAK,SAAS,EAAE,gBAAgB,mBAAmB;CAAE,CAAC;CAC5L,IAAMZ,IAAkC;EACpC,eAAe,UAAU2B,EAAO;EAChC,iBAAiBA,EAAO;EACxB,GAAIA,EAAO,SAAS,EAAE,mBAAmBA,EAAO,OAAO,IAAI,CAAC;CAChE,GACMC,IAAOhB,EAAQ,QAAQ,IAAI,cAAc;CAC/C,AAAIgB,MAAM,EAAQ,kBAAkBA;CACpC,IAAMzB,IAAOS,EAAQ,WAAW,SAASA,EAAQ,WAAW,WAAW,KAAA,IAAY,MAAMA,EAAQ,YAAY,GACvGiB,IAAM,IAAI,IAAIjB,EAAQ,GAAG,GACzBK,IAAS,MAAMa,EAAU,GAAGH,EAAO,IAAI,QAAQ,QAAQ,EAAE,IAAIzB,IAAO2B,EAAI,UAAU;EACpF,QAAQjB,EAAQ;EAChB;EACA,GAAIT,IAAO,EAAE,QAAK,IAAI,CAAC;EACvB,QAAQS,EAAQ;CACpB,CAAC;CACD,OAAO,IAAI,SAASK,EAAO,MAAM;EAC7B,QAAQA,EAAO;EACf,SAAS;GACL,gBAAgBA,EAAO,QAAQ,IAAI,cAAc,KAAK;GACtD,iBAAiB;GACjB,qBAAqB;EACzB;CACJ,CAAC;AACL"}
|
|
1
|
+
{"version":3,"file":"client.mjs","names":["RUNNER_KEY_PROVIDERS","RunnerError","code","status","extra","noCreditUntil","event","RunnerClient","options","scope","json","key","tenant","user","headers","response","path","body","text","data","name","project","approve","id","input","label","provider","request","tools","message","signal","callId","answer","reader","decoder","buffer","value","done","lines","line","PERSON_ROUTES","forwardToRunner","target","type","url","fetchImpl"],"sources":["../src/client/index.ts"],"sourcesContent":["// @llmnative/runner/client — the client of the API v1 of the LLMNative Runner, for the browser and for Node.\n//\n// A key never belongs in the browser of the people of a tenant: a host app talks to the runner from its backend\n// (`createRunnerProxy` forwards the requests of its signed-in people, adding the key, the tenant and the person),\n// and its pages use `RunnerClient` against that backend. The console of the runner and a personal app with a key of\n// its own use `RunnerClient` directly.\n\n/** The providers paid by use whose API key the runner keeps and opencode runs (ids of @llmnative/react). */\nexport const RUNNER_KEY_PROVIDERS = ['anthropic', 'openai', 'gemini', 'mistral', 'deepseek', 'openrouter'] as const;\nexport type RunnerKeyProvider = (typeof RUNNER_KEY_PROVIDERS)[number];\nexport type RunnerProvider = 'claude-code' | 'opencode-go' | 'opencode' | RunnerKeyProvider;\nexport type RunnerPermission = 'complete' | 'chat' | 'chat:tools' | 'accounts' | 'accounts:tenant' | 'act-as-user' | 'keys';\n\nexport type RunnerAccount = {\n provider: RunnerProvider;\n id: string;\n label?: string;\n /** When it was connected. */\n at: string;\n scope: 'user' | 'tenant';\n /** Out of credit until then (the limit of a subscription); absent when it has credit. */\n noCreditUntil?: string;\n};\n\nexport type RunnerModels = {\n /** `models`: the list a subscription serves; empty for a provider by use, which runs any model the client names. */\n providers: Array<{ id: RunnerProvider; kind: 'subscription' | 'usage'; models: string[]; accounts: number; available: number; yours: number; tenant: number }>;\n};\n\nexport type RunnerTenant = { id: string; name: string; createdAt: string; usersWithAccounts?: number };\nexport type RunnerKey = { id: string; kind: 'platform' | 'project'; tenant?: string; /** Platform keys: the project whose tenants (`<project>`, `<project>-…`) it owns. */ project?: string; name: string; permissions: RunnerPermission[]; createdAt: string; expiresAt: string | null };\n\nexport type RunnerStatus = {\n version: string;\n agentImage: string;\n url?: string;\n /** The project of the platform key asking: the tenants listed are its own only. */\n project?: string;\n load: { chats: number; answering: number; completions: number; maxChats: number };\n machine: { totalBytes: number; availableBytes: number; cpus: number };\n tenants: RunnerTenant[];\n};\n\n/** A pairing request made by a platform: `request` is its secret (keep it in the backend), `code` is shown on both sides. */\nexport type RunnerPairingRequest = { request: string; code: string; approveUrl: string; expiresAt: string; interval: number };\nexport type RunnerPairingPoll = { status: 'pending' | 'denied' | 'expired' } | { status: 'approved'; key: string; record: RunnerKey; version: string };\nexport type RunnerPairingRequestView = { code: string; name: string; project?: string; from?: string; createdAt: string; expiresAt: string };\nexport type RunnerHealth = { ok: boolean; version: string; chats: number; answering: number; completions: number; maxChats: number };\n\nexport type RunnerCompletionRequest = { provider: RunnerProvider; model: string; prompt: string; effort?: 'low' | 'medium' | 'high' | 'xhigh' | 'max' };\nexport type RunnerCompletion = { text: string; usage?: { inputTokens: number; outputTokens: number } };\n\nexport type RunnerChatTool = { name: string; description: string; inputSchema: Record<string, unknown>; endsTurn?: boolean };\nexport type RunnerChatModel = { provider: string; model: string; variant?: string; name?: string; effort?: string };\nexport type RunnerChatEvent =\n | { type: 'text'; text: string }\n | { type: 'reasoning'; text: string }\n | { type: 'step'; id: string; label: string; status: 'running' | 'done' }\n | { type: 'tool-call'; id: string; name: string; input: Record<string, unknown> }\n | { type: 'done' }\n | { type: 'error'; message: string };\n\n/** An error of the runner: its status and code (`no-credit`, `busy`…), and for `no-credit` until when. */\nexport class RunnerError extends Error {\n readonly status: number;\n readonly code: string;\n readonly until?: string;\n readonly detail?: string;\n\n constructor(status: number, code: string, extra: { until?: string; detail?: string } = {}) {\n super(code);\n this.name = 'RunnerError';\n this.status = status;\n this.code = code;\n if (extra.until) this.until = extra.until;\n if (extra.detail) this.detail = extra.detail;\n }\n}\n\n/** When a chat event says the accounts ran out of credit: until when (`no-credit:<iso>`). */\nexport const noCreditUntil = (event: RunnerChatEvent): string | undefined =>\n event.type === 'error' && event.message.startsWith('no-credit:') ? event.message.slice('no-credit:'.length) : undefined;\n\nexport type RunnerClientOptions = {\n /** The address of the runner (`https://runner.example.com`), or of the backend of the host that forwards to it. */\n url: string;\n /** A key of the runner (or the admin token in the console); none when the backend of the host adds it. */\n key?: string;\n /** With a platform key or the admin token: the tenant the requests are for. */\n tenant?: string;\n /** The person the requests are for (needs `act-as-user` with a project key). */\n user?: string;\n fetch?: typeof fetch;\n /** More headers for each request (the session of the host, for its backend). */\n headers?: () => Record<string, string> | Promise<Record<string, string>>;\n};\n\nexport class RunnerClient {\n readonly options: RunnerClientOptions;\n\n constructor(options: RunnerClientOptions) {\n this.options = { ...options, url: options.url.replace(/\\/+$/, '') };\n }\n\n /** The same runner for another tenant or person. */\n as(scope: { tenant?: string; user?: string }): RunnerClient {\n return new RunnerClient({ ...this.options, ...scope });\n }\n\n private async headers(json: boolean): Promise<Record<string, string>> {\n const { key, tenant, user, headers } = this.options;\n return {\n ...(json ? { 'content-type': 'application/json' } : {}),\n ...(key ? { authorization: `Bearer ${key}` } : {}),\n ...(tenant ? { 'x-runner-tenant': tenant } : {}),\n ...(user ? { 'x-runner-user': user } : {}),\n ...(await headers?.()),\n };\n }\n\n /** One request; its JSON, or a RunnerError. */\n async request<T>(method: string, path: string, body?: unknown): Promise<T> {\n const response = await (this.options.fetch ?? fetch)(`${this.options.url}${path}`, {\n method,\n headers: await this.headers(body !== undefined),\n ...(body !== undefined ? { body: JSON.stringify(body) } : {}),\n });\n const text = await response.text();\n let data: Record<string, unknown> = {};\n try {\n data = text ? JSON.parse(text) as Record<string, unknown> : {};\n } catch {\n // Not JSON (a proxy in between): said by its status.\n }\n if (!response.ok) {\n throw new RunnerError(response.status, typeof data.error === 'string' ? data.error : `http-${response.status}`, {\n ...(typeof data.until === 'string' ? { until: data.until } : {}),\n ...(typeof data.detail === 'string' ? { detail: data.detail } : {}),\n });\n }\n return data as T;\n }\n\n // ── Public ──────────────────────────────────────────────────────────────────────────────────────────────\n health(): Promise<RunnerHealth> {\n return this.request('GET', '/health');\n }\n\n /** A pairing code (printed by the installer) → a platform key, seen once. */\n /** `project`: the platform key owns only the tenants of that project (`<project>`, `<project>-…`). */\n pair(code: string, name?: string, project?: string): Promise<{ key: string; record: RunnerKey; version: string }> {\n return this.request('POST', '/v1/pair', { code, ...(name ? { name } : {}), ...(project ? { project } : {}) });\n }\n\n /**\n * Asks to connect (device flow): the admin of the runner approves it in the console at `approveUrl`, where the\n * same `code` is shown; meanwhile `pollPairing(request)` every `interval` seconds, until it gives the key.\n */\n requestPairing(name: string, project?: string): Promise<RunnerPairingRequest> {\n return this.request('POST', '/v1/pair/requests', { name, ...(project ? { project } : {}) });\n }\n\n pollPairing(request: string): Promise<RunnerPairingPoll> {\n return this.request('POST', '/v1/pair/requests/poll', { request });\n }\n\n info(): Promise<{ version: string; harnesses: string[]; capabilities: Record<string, boolean>; permissions: RunnerPermission[]; tenant?: string }> {\n return this.request('GET', '/v1/info');\n }\n\n // ── Admin token ─────────────────────────────────────────────────────────────────────────────────────────\n createPairing(): Promise<{ code: string; expiresAt: string }> {\n return this.request('POST', '/v1/admin/pairing');\n }\n\n async pairingRequests(): Promise<RunnerPairingRequestView[]> {\n return (await this.request<{ requests: RunnerPairingRequestView[] }>('GET', '/v1/admin/pairing/requests')).requests;\n }\n\n async answerPairing(code: string, approve: boolean): Promise<RunnerPairingRequestView> {\n return (await this.request<{ request: RunnerPairingRequestView }>('POST', `/v1/admin/pairing/requests/${encodeURIComponent(code)}/${approve ? 'approve' : 'deny'}`)).request;\n }\n\n /** The project of a platform key (null: every tenant, as keys made before 1.2). */\n async setKeyProject(id: string, project: string | null): Promise<RunnerKey> {\n return (await this.request<{ record: RunnerKey }>('PUT', `/v1/admin/keys/${encodeURIComponent(id)}/project`, { project })).record;\n }\n\n // ── Platform key ────────────────────────────────────────────────────────────────────────────────────────\n readonly platform = {\n status: (): Promise<RunnerStatus> => this.request('GET', '/v1/platform/status'),\n tenants: async (): Promise<RunnerTenant[]> => (await this.request<{ tenants: RunnerTenant[] }>('GET', '/v1/platform/tenants')).tenants,\n /** A tenant, with its first project key unless `key: false` (seen once: keep it in the backend). */\n createTenant: (id: string, options: { name?: string; key?: boolean; keyPermissions?: RunnerPermission[] } = {}): Promise<{ tenant: RunnerTenant; key?: string; keyRecord?: RunnerKey }> =>\n this.request('POST', '/v1/platform/tenants', { id, ...options }),\n removeTenant: async (id: string): Promise<boolean> => (await this.request<{ removed: boolean }>('DELETE', `/v1/platform/tenants/${encodeURIComponent(id)}`)).removed,\n keys: async (tenant: string): Promise<RunnerKey[]> => (await this.request<{ keys: RunnerKey[] }>('GET', `/v1/platform/tenants/${encodeURIComponent(tenant)}/keys`)).keys,\n createKey: (tenant: string, input: { name?: string; permissions?: RunnerPermission[]; expiresAt?: string | null } = {}): Promise<{ key: string; record: RunnerKey }> =>\n this.request('POST', `/v1/platform/tenants/${encodeURIComponent(tenant)}/keys`, input),\n revokeKey: async (tenant: string, id: string): Promise<boolean> => (await this.request<{ removed: boolean }>('DELETE', `/v1/platform/tenants/${encodeURIComponent(tenant)}/keys/${encodeURIComponent(id)}`)).removed,\n platformKeys: async (): Promise<RunnerKey[]> => (await this.request<{ keys: RunnerKey[] }>('GET', '/v1/platform/keys')).keys,\n revokePlatformKey: async (id: string): Promise<boolean> => (await this.request<{ removed: boolean }>('DELETE', `/v1/platform/keys/${encodeURIComponent(id)}`)).removed,\n };\n\n // ── Accounts of the person (or of the tenant) ───────────────────────────────────────────────────────────\n readonly accounts = {\n list: async (): Promise<{ scope: 'user' | 'tenant'; accounts: RunnerAccount[] }> => this.request('GET', '/v1/accounts'),\n /** The sign-in of a Claude subscription: open `url`, then give the code Anthropic shows to `finishClaudeLogin`. */\n startClaudeLogin: (): Promise<{ url: string }> => this.request('POST', '/v1/accounts/claude-code/login'),\n finishClaudeLogin: async (code: string, label?: string): Promise<RunnerAccount> =>\n (await this.request<{ account: RunnerAccount }>('POST', '/v1/accounts/claude-code/login/code', { code, ...(label ? { label } : {}) })).account,\n /** A token made elsewhere with `claude setup-token`. */\n addClaudeToken: async (token: string, label?: string): Promise<RunnerAccount> =>\n (await this.request<{ account: RunnerAccount }>('POST', '/v1/accounts/claude-code', { token, ...(label ? { label } : {}) })).account,\n /** A key: OpenCode Go/Zen, or the API key of a provider by use the runner keeps (opencode runs it). */\n addKey: async (provider: Exclude<RunnerProvider, 'claude-code'>, key: string, label?: string): Promise<RunnerAccount> =>\n (await this.request<{ account: RunnerAccount }>('POST', `/v1/accounts/${provider}`, { key, ...(label ? { label } : {}) })).account,\n remove: async (provider: RunnerProvider, id: string): Promise<boolean> =>\n (await this.request<{ removed: boolean }>('DELETE', `/v1/accounts/${provider}/${encodeURIComponent(id)}`)).removed,\n order: async (provider: RunnerProvider, ids: string[]): Promise<RunnerAccount[]> =>\n (await this.request<{ accounts: RunnerAccount[] }>('PUT', '/v1/accounts/order', { provider, ids })).accounts,\n };\n\n models(): Promise<RunnerModels> {\n return this.request('GET', '/v1/models');\n }\n\n complete(request: RunnerCompletionRequest): Promise<RunnerCompletion> {\n return this.request('POST', '/v1/complete', request);\n }\n\n // ── Chats ───────────────────────────────────────────────────────────────────────────────────────────────\n readonly chats = {\n /** A chat (id: 8 hex characters, chosen by the client), with the tools the harness may call. */\n start: (id: string, tools?: RunnerChatTool[]): Promise<{ id: string }> => this.request('POST', '/v1/chats', { id, ...(tools ? { tools } : {}) }),\n /** A message: its events as they come. Aborting the signal stops the harness. */\n send: (id: string, message: { text: string; model: RunnerChatModel; attachments?: Array<{ name: string; mimeType: string; base64: string }> }, signal?: AbortSignal): AsyncIterable<RunnerChatEvent> =>\n this.stream(`/v1/chats/${encodeURIComponent(id)}/messages`, message, signal),\n answerCall: async (id: string, callId: string, answer: { result?: unknown; isError?: boolean }): Promise<boolean> =>\n (await this.request<{ answered: boolean }>('POST', `/v1/chats/${encodeURIComponent(id)}/calls/${encodeURIComponent(callId)}`, answer)).answered,\n stop: async (id: string): Promise<boolean> => (await this.request<{ stopped: boolean }>('POST', `/v1/chats/${encodeURIComponent(id)}/stop`)).stopped,\n close: async (id: string): Promise<boolean> => (await this.request<{ closed: boolean }>('DELETE', `/v1/chats/${encodeURIComponent(id)}`)).closed,\n };\n\n private async *stream(path: string, body: unknown, signal?: AbortSignal): AsyncIterable<RunnerChatEvent> {\n const response = await (this.options.fetch ?? fetch)(`${this.options.url}${path}`, { method: 'POST', headers: await this.headers(true), body: JSON.stringify(body), ...(signal ? { signal } : {}) });\n if (!response.ok || !response.body) {\n let code = `http-${response.status}`;\n try {\n const data = await response.json() as { error?: string };\n if (data.error) code = data.error;\n } catch {\n // Said by its status.\n }\n throw new RunnerError(response.status, code);\n }\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n for (;;) {\n const { done, value } = await reader.read();\n buffer += decoder.decode(value ?? new Uint8Array(), { stream: !done });\n const lines = buffer.split('\\n');\n buffer = done ? '' : lines.pop() ?? '';\n for (const line of lines) {\n if (!line.trim()) continue;\n let event: RunnerChatEvent | { type: 'ping' };\n try {\n event = JSON.parse(line) as RunnerChatEvent | { type: 'ping' };\n } catch {\n continue;\n }\n if (event.type !== 'ping') yield event;\n }\n if (done) return;\n }\n }\n}\n\n// ── For the backend of a host ───────────────────────────────────────────────────────────────────────────────\n\n/** The routes the people of a tenant may reach through the backend of the host: never the platform ones. */\nconst PERSON_ROUTES = /^\\/v1\\/(info|models|complete|accounts(\\/[A-Za-z0-9_.:-]+){0,3}|chats(\\/[a-f0-9]{8}(\\/(messages|stop|calls\\/[a-f0-9]{12}))?)?)$/;\n\nexport type RunnerProxyTarget = {\n /** The address of the runner of this tenant. */\n url: string;\n /** A project key of the tenant (with `act-as-user`), or a platform key with `tenant`. */\n key: string;\n tenant?: string;\n /** The signed-in person, verified by the host. */\n user: string;\n};\n\n/**\n * Forwards a request of a signed-in person to their runner: only the routes of a person, with the key, tenant and\n * person added by the host (whatever the browser sent for them is dropped). Streams answers (chat replies) as they\n * come. `path` is the path of the runner, e.g. `/v1/models` (the host strips its own prefix).\n */\nexport async function forwardToRunner(request: Request, path: string, target: RunnerProxyTarget, fetchImpl: typeof fetch = fetch): Promise<Response> {\n if (!PERSON_ROUTES.test(path)) return new Response(JSON.stringify({ error: 'not found' }), { status: 404, headers: { 'content-type': 'application/json' } });\n if (!['GET', 'POST', 'PUT', 'DELETE'].includes(request.method)) return new Response(JSON.stringify({ error: 'not found' }), { status: 404, headers: { 'content-type': 'application/json' } });\n const headers: Record<string, string> = {\n authorization: `Bearer ${target.key}`,\n 'x-runner-user': target.user,\n ...(target.tenant ? { 'x-runner-tenant': target.tenant } : {}),\n };\n const type = request.headers.get('content-type');\n if (type) headers['content-type'] = type;\n const body = request.method === 'GET' || request.method === 'DELETE' ? undefined : await request.arrayBuffer();\n const url = new URL(request.url);\n const answer = await fetchImpl(`${target.url.replace(/\\/+$/, '')}${path}${url.search}`, {\n method: request.method,\n headers,\n ...(body ? { body } : {}),\n signal: request.signal,\n });\n return new Response(answer.body, {\n status: answer.status,\n headers: {\n 'content-type': answer.headers.get('content-type') ?? 'application/json',\n 'cache-control': 'no-store',\n 'x-accel-buffering': 'no',\n },\n });\n}\n"],"mappings":";AAQA,IAAaA,IAAuB;CAAC;CAAa;CAAU;CAAU;CAAW;CAAY;AAAY,GAuD5FC,IAAb,cAAiC,MAAM;CACnC;CACA;CACA;CACA;CAEA,YAAY,GAAgB,GAAc,IAA6C,CAAC,GAAG;EAMvF,AALA,MAAMC,CAAI,GACV,KAAK,OAAO,eACZ,KAAK,SAASC,GACd,KAAK,OAAOD,GACRE,EAAM,UAAO,KAAK,QAAQA,EAAM,QAChCA,EAAM,WAAQ,KAAK,SAASA,EAAM;CAC1C;AACJ,GAGaC,KAAiB,MAC1BC,EAAM,SAAS,WAAWA,EAAM,QAAQ,WAAW,YAAY,IAAIA,EAAM,QAAQ,MAAM,EAAmB,IAAI,KAAA,GAgBrGC,IAAb,MAAaA,EAAa;CACtB;CAEA,YAAY,GAA8B;EACtC,KAAK,UAAU;GAAE,GAAGC;GAAS,KAAKA,EAAQ,IAAI,QAAQ,QAAQ,EAAE;EAAE;CACtE;CAGA,GAAG,GAAyD;EACxD,OAAO,IAAID,EAAa;GAAE,GAAG,KAAK;GAAS,GAAGE;EAAM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