@llmnative/runner 1.4.0 → 2.0.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/README.md +10 -1
- package/dist/client.js +2 -2
- package/dist/client.js.map +1 -1
- package/dist/client.mjs +42 -23
- package/dist/client.mjs.map +1 -1
- package/dist/setup-app/assets/{NetworkCanvasImpl-DIYuzg6x-Be3lb8aE.js → NetworkCanvasImpl--7M6QHBl-BJlQ1Jxm.js} +1 -1
- package/dist/setup-app/assets/{index-C8qoeNuR.js → index-CdEnLJdB.js} +3 -3
- package/dist/setup-app/assets/{index.es-DuFO70Jd.js → index.es-CyY_APIX.js} +1 -1
- package/dist/setup-app/assets/{lucide-react-BhRrMOuZ.js → lucide-react-nUjfsPoS.js} +1 -1
- package/dist/setup-app/index.html +1 -1
- package/dist/steps.js +1 -1
- package/dist/steps.mjs +2 -2
- package/dist/types/client/index.d.ts +68 -7
- package/dist/types/ui/texts.d.ts +45 -0
- package/dist/ui.js +3 -3
- package/dist/ui.js.map +1 -1
- package/dist/ui.mjs +560 -475
- package/dist/ui.mjs.map +1 -1
- package/install/coolify.yaml +2 -2
- package/install/install.sh +1 -1
- package/llms.txt +1 -0
- package/openapi/v1.yaml +38 -9
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -49,9 +49,18 @@ checks that the code is the same and approves; the platform gets its platform ke
|
|
|
49
49
|
| Key | Who has it | What it does |
|
|
50
50
|
|---|---|---|
|
|
51
51
|
| admin token | the machine (`/data/admin-token`) | the console; pairing codes |
|
|
52
|
-
| platform key `rk_platform_…` | the backend of
|
|
52
|
+
| platform key `rk_platform_…` | the backend of an app, from a pairing code or an approved request | the tenants it made or was granted, and their keys; acts for them with `X-Runner-Tenant` |
|
|
53
53
|
| project key `rk_…` | the backend of a tenant | `complete`, `chat`, `chat:tools`, `accounts`, `accounts:tenant`, `act-as-user`, `keys` |
|
|
54
54
|
|
|
55
|
+
A tenant is an organization (2.0): the apps of a suite that work for the same organization share its tenant and its
|
|
56
|
+
accounts. A platform key is paired for an app (`client.pair(code, name, { app })`) and sees the organizations it makes;
|
|
57
|
+
one that another app made is granted by the admin in the console (a request appears there when the app asks for it).
|
|
58
|
+
Completions and chats carry the app and the project as a label of the log (`X-Runner-App`, `X-Runner-Project`).
|
|
59
|
+
|
|
60
|
+
From 1.x: `node src/cli.ts migrate-tenants` (a dry run) shows how the tenants `<app>-<org>` become `<org>`, with the
|
|
61
|
+
accounts of the same organization merged; `--apply` does it, `crm=consuletica` names the tenant of an app without
|
|
62
|
+
organizations.
|
|
63
|
+
|
|
55
64
|
Keys are kept as hashes. A host never puts a key in the browser of its people: its backend verifies the person and forwards with `X-Runner-User` (`forwardToRunner`).
|
|
56
65
|
|
|
57
66
|
## The package `@llmnative/runner`
|
package/dist/client.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
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)}},
|
|
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=e=>typeof e==`string`?{project:e}:{...e?.app?{app:e.app}:{},...e?.project?{project:e.project}:{}},n=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)}},r=e=>e.type===`error`&&e.message.startsWith(`no-credit:`)?e.message.slice(10):void 0,i=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,app:i,project:a,headers:o}=this.options;return{...e?{"content-type":`application/json`}:{},...t?{authorization:`Bearer ${t}`}:{},...n?{"x-runner-tenant":n}:{},...r?{"x-runner-user":r}:{},...i?{"x-runner-app":i}:{},...a?{"x-runner-project":a}:{},...await o?.()}}async request(e,t,r){let i=await(this.options.fetch??fetch)(`${this.options.url}${t}`,{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 n(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,n,r){return this.request(`POST`,`/v1/pair`,{code:e,...n?{name:n}:{},...t(r)})}requestPairing(e,n){return this.request(`POST`,`/v1/pair/requests`,{name:e,...t(n)})}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 grantRequests(){return(await this.request(`GET`,`/v1/admin/grants`)).grants}async answerGrant(e,t){return(await this.request(`POST`,`/v1/admin/grants/${encodeURIComponent(e)}/${t?`approve`:`deny`}`)).grant}async grantTenant(e,t,n=!0){return(await this.request(n?`PUT`:`DELETE`,`/v1/admin/tenants/${encodeURIComponent(e)}/platforms/${encodeURIComponent(t)}`)).tenant}migrateTenants(e={}){return this.request(`POST`,`/v1/admin/migrate-tenants`,e)}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,rename:async(e,t,n)=>(await this.request(`PATCH`,`/v1/accounts/${e}/${encodeURIComponent(t)}`,{label:n})).accounts,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,t,r){let i=await(this.options.fetch??fetch)(`${this.options.url}${e}`,{method:`POST`,headers:await this.headers(!0),body:JSON.stringify(t),...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 n(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}}},a=/^\/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 o(e,t,n,r=fetch){if(!a.test(t)||![`GET`,`POST`,`PUT`,`PATCH`,`DELETE`].includes(e.method))return new Response(JSON.stringify({error:`not found`}),{status:404,headers:{"content-type":`application/json`}});let i={authorization:`Bearer ${n.key}`,"x-runner-user":n.user,...n.tenant?{"x-runner-tenant":n.tenant}:{},...n.app?{"x-runner-app":n.app}:{},...n.project?{"x-runner-project":n.project}:{}},o=e.headers.get(`content-type`);o&&(i[`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:i,...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=i,exports.RunnerError=n,exports.forwardToRunner=o,exports.noCreditUntil=r;
|
|
3
3
|
//# sourceMappingURL=client.js.map
|
package/dist/client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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' | 'modules';\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>; modules?: string[]; 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 /** The name of an account (its email, say); empty: none. */\n rename: async (provider: RunnerProvider, id: string, label: string): Promise<RunnerAccount[]> =>\n (await this.request<{ accounts: RunnerAccount[] }>('PATCH', `/v1/accounts/${provider}/${encodeURIComponent(id)}`, { label })).accounts,\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', 'PATCH', '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,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AU,CAAE,MAAO,WAAY,CAAC,EAAG,CAAE,OAAQ,IAAK,QAAS,CAAE,eAAgB,kBAAmB,CAAE,CAAC,EACrM,IAAMb,EAAkC,CACpC,cAAe,UAAU4B,EAAO,MAChC,gBAAiBA,EAAO,KACxB,GAAIA,EAAO,OAAS,CAAE,kBAAmBA,EAAO,MAAO,EAAI,CAAC,CAChE,EACMC,EAAOhB,EAAQ,QAAQ,IAAI,cAAc,EAC3CgB,IAAM,EAAQ,gBAAkBA,GACpC,IAAM1B,EAAOU,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,IAAI1B,IAAO4B,EAAI,SAAU,CACpF,OAAQjB,EAAQ,OAChB,UACA,GAAIV,EAAO,CAAE,MAAK,EAAI,CAAC,EACvB,OAAQU,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","scopeOf","scope","RunnerError","code","status","extra","noCreditUntil","event","RunnerClient","options","json","key","tenant","user","app","project","headers","response","path","body","text","data","name","approve","id","allow","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' | 'modules';\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\n/** A tenant: an organization (2.0), shared by the apps that work for it. `platforms`: the platform keys that see it. */\nexport type RunnerTenant = { id: string; name: string; createdAt: string; usersWithAccounts?: number; platforms?: string[] };\nexport type RunnerKey = {\n id: string;\n kind: 'platform' | 'project';\n tenant?: string;\n /** Platform keys (2.0): the app that connected with it; it sees the tenants it made and those granted to it. */\n app?: string;\n /** Platform keys before 2.0: the project whose tenants (`<project>`, `<project>-…`) it owns. */\n project?: string;\n name: string;\n permissions: RunnerPermission[];\n createdAt: string;\n expiresAt: string | null;\n};\n/** An app asked for an organization another app made: the admin grants it in the console, or not. */\nexport type RunnerGrantRequest = { id: string; tenant: string; key: string; keyName: string; app?: string; createdAt: string };\n/** The 2.0 migration of the tenants: what moves (`<app>-<org>` → `<org>`), what stays and why. */\nexport type RunnerTenantMigration = {\n applied: boolean;\n moves: Array<{ from: string; to: string; merge: boolean; platforms: string[] }>;\n skipped: Array<{ tenant: string; reason: 'needs-name' | 'invalid' | 'same' }>;\n keys: string[];\n};\n/** Who a platform key is for: an app (2.0), or, as a string, the project of the keys before 2.0. */\nexport type RunnerPlatformScope = string | { app?: string; project?: string };\nconst scopeOf = (scope?: RunnerPlatformScope) => (typeof scope === 'string' ? { project: scope } : { ...(scope?.app ? { app: scope.app } : {}), ...(scope?.project ? { project: scope.project } : {}) });\n\nexport type RunnerStatus = {\n version: string;\n agentImage: string;\n url?: string;\n /** The app of the platform key asking (2.0): the tenants listed are those it sees. */\n app?: string;\n /** The project of the platform key asking, before 2.0. */\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; app?: 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 /** The app and the project of completions and chats (2.0): a label in the log of the runner, never a scope. */\n app?: string;\n project?: 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; app?: string; project?: 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, app, project, 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 ...(app ? { 'x-runner-app': app } : {}),\n ...(project ? { 'x-runner-project': project } : {}),\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 /**\n * `{ app }` (2.0): the platform key sees the organizations it makes and those the admin grants it. A string: the\n * project of the keys before 2.0, owning `<project>` and `<project>-…`.\n */\n pair(code: string, name?: string, scope?: RunnerPlatformScope): Promise<{ key: string; record: RunnerKey; version: string }> {\n return this.request('POST', '/v1/pair', { code, ...(name ? { name } : {}), ...scopeOf(scope) });\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, scope?: RunnerPlatformScope): Promise<RunnerPairingRequest> {\n return this.request('POST', '/v1/pair/requests', { name, ...scopeOf(scope) });\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>; modules?: string[]; 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 apps waiting for an organization another app made. */\n async grantRequests(): Promise<RunnerGrantRequest[]> {\n return (await this.request<{ grants: RunnerGrantRequest[] }>('GET', '/v1/admin/grants')).grants;\n }\n\n async answerGrant(id: string, approve: boolean): Promise<RunnerGrantRequest> {\n return (await this.request<{ grant: RunnerGrantRequest }>('POST', `/v1/admin/grants/${encodeURIComponent(id)}/${approve ? 'approve' : 'deny'}`)).grant;\n }\n\n /** A platform key sees a tenant, or (`allow: false`) no longer. */\n async grantTenant(tenant: string, key: string, allow = true): Promise<RunnerTenant> {\n return (await this.request<{ tenant: RunnerTenant }>(allow ? 'PUT' : 'DELETE', `/v1/admin/tenants/${encodeURIComponent(tenant)}/platforms/${encodeURIComponent(key)}`)).tenant;\n }\n\n /** The 2.0 migration of the tenants (`<app>-<org>` → `<org>`): a dry run unless `apply`; `map` names the others. */\n migrateTenants(options: { apply?: boolean; map?: Record<string, string> } = {}): Promise<RunnerTenantMigration> {\n return this.request('POST', '/v1/admin/migrate-tenants', options);\n }\n\n /** The project of a platform key before 2.0 (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 /**\n * A tenant, with its first project key unless `key: false` (seen once: keep it in the backend). An organization\n * another app made answers RunnerError `needs-grant` (409): the admin of the runner grants it in the console.\n */\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 /** The name of an account (its email, say); empty: none. */\n rename: async (provider: RunnerProvider, id: string, label: string): Promise<RunnerAccount[]> =>\n (await this.request<{ accounts: RunnerAccount[] }>('PATCH', `/v1/accounts/${provider}/${encodeURIComponent(id)}`, { label })).accounts,\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 /** The app and the project the person works in: labels in the log of the runner. */\n app?: string;\n project?: 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', 'PATCH', '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 ...(target.app ? { 'x-runner-app': target.app } : {}),\n ...(target.project ? { 'x-runner-project': target.project } : {}),\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,EA+CnGC,EAAW,GAAiC,OAAOC,GAAU,SAAW,CAAE,QAASA,CAAM,EAAI,CAAE,GAAIA,GAAO,IAAM,CAAE,IAAKA,EAAM,GAAI,EAAI,CAAC,EAAI,GAAIA,GAAO,QAAU,CAAE,QAASA,EAAM,OAAQ,EAAI,CAAC,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Y,EACvGiB,EAAM,IAAI,IAAIjB,EAAQ,GAAG,EACzBK,EAAS,MAAMa,EAAU,GAAGH,EAAO,IAAI,QAAQ,OAAQ,EAAE,IAAI1B,IAAO4B,EAAI,SAAU,CACpF,OAAQjB,EAAQ,OAChB,UACA,GAAIV,EAAO,CAAE,MAAK,EAAI,CAAC,EACvB,OAAQU,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"}
|
package/dist/client.mjs
CHANGED
|
@@ -6,7 +6,10 @@ var e = [
|
|
|
6
6
|
"mistral",
|
|
7
7
|
"deepseek",
|
|
8
8
|
"openrouter"
|
|
9
|
-
], t =
|
|
9
|
+
], t = (e) => typeof e == "string" ? { project: e } : {
|
|
10
|
+
...e?.app ? { app: e.app } : {},
|
|
11
|
+
...e?.project ? { project: e.project } : {}
|
|
12
|
+
}, n = class extends Error {
|
|
10
13
|
status;
|
|
11
14
|
code;
|
|
12
15
|
until;
|
|
@@ -14,7 +17,7 @@ var e = [
|
|
|
14
17
|
constructor(e, t, n = {}) {
|
|
15
18
|
super(t), this.name = "RunnerError", this.status = e, this.code = t, n.until && (this.until = n.until), n.detail && (this.detail = n.detail);
|
|
16
19
|
}
|
|
17
|
-
},
|
|
20
|
+
}, r = (e) => e.type === "error" && e.message.startsWith("no-credit:") ? e.message.slice(10) : void 0, i = class e {
|
|
18
21
|
options;
|
|
19
22
|
constructor(e) {
|
|
20
23
|
this.options = {
|
|
@@ -29,17 +32,19 @@ var e = [
|
|
|
29
32
|
});
|
|
30
33
|
}
|
|
31
34
|
async headers(e) {
|
|
32
|
-
let { key: t, tenant: n, user: r,
|
|
35
|
+
let { key: t, tenant: n, user: r, app: i, project: a, headers: o } = this.options;
|
|
33
36
|
return {
|
|
34
37
|
...e ? { "content-type": "application/json" } : {},
|
|
35
38
|
...t ? { authorization: `Bearer ${t}` } : {},
|
|
36
39
|
...n ? { "x-runner-tenant": n } : {},
|
|
37
40
|
...r ? { "x-runner-user": r } : {},
|
|
38
|
-
...
|
|
41
|
+
...i ? { "x-runner-app": i } : {},
|
|
42
|
+
...a ? { "x-runner-project": a } : {},
|
|
43
|
+
...await o?.()
|
|
39
44
|
};
|
|
40
45
|
}
|
|
41
|
-
async request(e,
|
|
42
|
-
let i = await (this.options.fetch ?? fetch)(`${this.options.url}${
|
|
46
|
+
async request(e, t, r) {
|
|
47
|
+
let i = await (this.options.fetch ?? fetch)(`${this.options.url}${t}`, {
|
|
43
48
|
method: e,
|
|
44
49
|
headers: await this.headers(r !== void 0),
|
|
45
50
|
...r === void 0 ? {} : { body: JSON.stringify(r) }
|
|
@@ -47,7 +52,7 @@ var e = [
|
|
|
47
52
|
try {
|
|
48
53
|
o = a ? JSON.parse(a) : {};
|
|
49
54
|
} catch {}
|
|
50
|
-
if (!i.ok) throw new
|
|
55
|
+
if (!i.ok) throw new n(i.status, typeof o.error == "string" ? o.error : `http-${i.status}`, {
|
|
51
56
|
...typeof o.until == "string" ? { until: o.until } : {},
|
|
52
57
|
...typeof o.detail == "string" ? { detail: o.detail } : {}
|
|
53
58
|
});
|
|
@@ -56,17 +61,17 @@ var e = [
|
|
|
56
61
|
health() {
|
|
57
62
|
return this.request("GET", "/health");
|
|
58
63
|
}
|
|
59
|
-
pair(e,
|
|
64
|
+
pair(e, n, r) {
|
|
60
65
|
return this.request("POST", "/v1/pair", {
|
|
61
66
|
code: e,
|
|
62
|
-
...
|
|
63
|
-
...
|
|
67
|
+
...n ? { name: n } : {},
|
|
68
|
+
...t(r)
|
|
64
69
|
});
|
|
65
70
|
}
|
|
66
|
-
requestPairing(e,
|
|
71
|
+
requestPairing(e, n) {
|
|
67
72
|
return this.request("POST", "/v1/pair/requests", {
|
|
68
73
|
name: e,
|
|
69
|
-
...t
|
|
74
|
+
...t(n)
|
|
70
75
|
});
|
|
71
76
|
}
|
|
72
77
|
pollPairing(e) {
|
|
@@ -84,6 +89,18 @@ var e = [
|
|
|
84
89
|
async answerPairing(e, t) {
|
|
85
90
|
return (await this.request("POST", `/v1/admin/pairing/requests/${encodeURIComponent(e)}/${t ? "approve" : "deny"}`)).request;
|
|
86
91
|
}
|
|
92
|
+
async grantRequests() {
|
|
93
|
+
return (await this.request("GET", "/v1/admin/grants")).grants;
|
|
94
|
+
}
|
|
95
|
+
async answerGrant(e, t) {
|
|
96
|
+
return (await this.request("POST", `/v1/admin/grants/${encodeURIComponent(e)}/${t ? "approve" : "deny"}`)).grant;
|
|
97
|
+
}
|
|
98
|
+
async grantTenant(e, t, n = !0) {
|
|
99
|
+
return (await this.request(n ? "PUT" : "DELETE", `/v1/admin/tenants/${encodeURIComponent(e)}/platforms/${encodeURIComponent(t)}`)).tenant;
|
|
100
|
+
}
|
|
101
|
+
migrateTenants(e = {}) {
|
|
102
|
+
return this.request("POST", "/v1/admin/migrate-tenants", e);
|
|
103
|
+
}
|
|
87
104
|
async setKeyProject(e, t) {
|
|
88
105
|
return (await this.request("PUT", `/v1/admin/keys/${encodeURIComponent(e)}/project`, { project: t })).record;
|
|
89
106
|
}
|
|
@@ -139,11 +156,11 @@ var e = [
|
|
|
139
156
|
stop: async (e) => (await this.request("POST", `/v1/chats/${encodeURIComponent(e)}/stop`)).stopped,
|
|
140
157
|
close: async (e) => (await this.request("DELETE", `/v1/chats/${encodeURIComponent(e)}`)).closed
|
|
141
158
|
};
|
|
142
|
-
async *stream(e,
|
|
159
|
+
async *stream(e, t, r) {
|
|
143
160
|
let i = await (this.options.fetch ?? fetch)(`${this.options.url}${e}`, {
|
|
144
161
|
method: "POST",
|
|
145
162
|
headers: await this.headers(!0),
|
|
146
|
-
body: JSON.stringify(
|
|
163
|
+
body: JSON.stringify(t),
|
|
147
164
|
...r ? { signal: r } : {}
|
|
148
165
|
});
|
|
149
166
|
if (!i.ok || !i.body) {
|
|
@@ -152,7 +169,7 @@ var e = [
|
|
|
152
169
|
let t = await i.json();
|
|
153
170
|
t.error && (e = t.error);
|
|
154
171
|
} catch {}
|
|
155
|
-
throw new
|
|
172
|
+
throw new n(i.status, e);
|
|
156
173
|
}
|
|
157
174
|
let a = i.body.getReader(), o = new TextDecoder(), s = "";
|
|
158
175
|
for (;;) {
|
|
@@ -173,9 +190,9 @@ var e = [
|
|
|
173
190
|
if (e) return;
|
|
174
191
|
}
|
|
175
192
|
}
|
|
176
|
-
},
|
|
177
|
-
async function
|
|
178
|
-
if (!
|
|
193
|
+
}, a = /^\/v1\/(info|models|complete|accounts(\/[A-Za-z0-9_.:-]+){0,3}|chats(\/[a-f0-9]{8}(\/(messages|stop|calls\/[a-f0-9]{12}))?)?)$/;
|
|
194
|
+
async function o(e, t, n, r = fetch) {
|
|
195
|
+
if (!a.test(t) || ![
|
|
179
196
|
"GET",
|
|
180
197
|
"POST",
|
|
181
198
|
"PUT",
|
|
@@ -185,15 +202,17 @@ async function a(e, t, n, r = fetch) {
|
|
|
185
202
|
status: 404,
|
|
186
203
|
headers: { "content-type": "application/json" }
|
|
187
204
|
});
|
|
188
|
-
let
|
|
205
|
+
let i = {
|
|
189
206
|
authorization: `Bearer ${n.key}`,
|
|
190
207
|
"x-runner-user": n.user,
|
|
191
|
-
...n.tenant ? { "x-runner-tenant": n.tenant } : {}
|
|
208
|
+
...n.tenant ? { "x-runner-tenant": n.tenant } : {},
|
|
209
|
+
...n.app ? { "x-runner-app": n.app } : {},
|
|
210
|
+
...n.project ? { "x-runner-project": n.project } : {}
|
|
192
211
|
}, o = e.headers.get("content-type");
|
|
193
|
-
o && (
|
|
212
|
+
o && (i["content-type"] = o);
|
|
194
213
|
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}`, {
|
|
195
214
|
method: e.method,
|
|
196
|
-
headers:
|
|
215
|
+
headers: i,
|
|
197
216
|
...s ? { body: s } : {},
|
|
198
217
|
signal: e.signal
|
|
199
218
|
});
|
|
@@ -206,6 +225,6 @@ async function a(e, t, n, r = fetch) {
|
|
|
206
225
|
}
|
|
207
226
|
});
|
|
208
227
|
}
|
|
209
|
-
export { e as RUNNER_KEY_PROVIDERS,
|
|
228
|
+
export { e as RUNNER_KEY_PROVIDERS, i as RunnerClient, n as RunnerError, o as forwardToRunner, r as noCreditUntil };
|
|
210
229
|
|
|
211
230
|
//# sourceMappingURL=client.mjs.map
|
package/dist/client.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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' | 'modules';\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>; modules?: string[]; 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 /** The name of an account (its email, say); empty: none. */\n rename: async (provider: RunnerProvider, id: string, label: string): Promise<RunnerAccount[]> =>\n (await this.request<{ accounts: RunnerAccount[] }>('PATCH', `/v1/accounts/${provider}/${encodeURIComponent(id)}`, { label })).accounts,\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', 'PATCH', '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')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M,SAAS,WAAQ,MAAMA;GACrC;GACA,IAAI+B,GAAM;EACd;CACJ;AACJ,GAKMG,IAAgB;AAiBtB,eAAsBC,EAAgB,GAAkB,GAAc,GAA2B,IAA0B,OAA0B;CAEjJ,IADI,CAACD,EAAc,KAAKxB,CAAI,KACxB,CAAC;EAAC;EAAO;EAAQ;EAAO;EAAS;CAAQ,CAAC,CAAC,SAASW,EAAQ,MAAM,GAAG,OAAO,IAAI,SAAS,KAAK,UAAU,EAAE,OAAO,YAAY,CAAC,GAAG;EAAE,QAAQ;EAAK,SAAS,EAAE,gBAAgB,mBAAmB;CAAE,CAAC;CACrM,IAAMb,IAAkC;EACpC,eAAe,UAAU4B,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,IAAM1B,IAAOU,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,IAAI1B,IAAO4B,EAAI,UAAU;EACpF,QAAQjB,EAAQ;EAChB;EACA,GAAIV,IAAO,EAAE,QAAK,IAAI,CAAC;EACvB,QAAQU,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","scopeOf","scope","RunnerError","code","status","extra","noCreditUntil","event","RunnerClient","options","json","key","tenant","user","app","project","headers","response","path","body","text","data","name","approve","id","allow","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' | 'modules';\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\n/** A tenant: an organization (2.0), shared by the apps that work for it. `platforms`: the platform keys that see it. */\nexport type RunnerTenant = { id: string; name: string; createdAt: string; usersWithAccounts?: number; platforms?: string[] };\nexport type RunnerKey = {\n id: string;\n kind: 'platform' | 'project';\n tenant?: string;\n /** Platform keys (2.0): the app that connected with it; it sees the tenants it made and those granted to it. */\n app?: string;\n /** Platform keys before 2.0: the project whose tenants (`<project>`, `<project>-…`) it owns. */\n project?: string;\n name: string;\n permissions: RunnerPermission[];\n createdAt: string;\n expiresAt: string | null;\n};\n/** An app asked for an organization another app made: the admin grants it in the console, or not. */\nexport type RunnerGrantRequest = { id: string; tenant: string; key: string; keyName: string; app?: string; createdAt: string };\n/** The 2.0 migration of the tenants: what moves (`<app>-<org>` → `<org>`), what stays and why. */\nexport type RunnerTenantMigration = {\n applied: boolean;\n moves: Array<{ from: string; to: string; merge: boolean; platforms: string[] }>;\n skipped: Array<{ tenant: string; reason: 'needs-name' | 'invalid' | 'same' }>;\n keys: string[];\n};\n/** Who a platform key is for: an app (2.0), or, as a string, the project of the keys before 2.0. */\nexport type RunnerPlatformScope = string | { app?: string; project?: string };\nconst scopeOf = (scope?: RunnerPlatformScope) => (typeof scope === 'string' ? { project: scope } : { ...(scope?.app ? { app: scope.app } : {}), ...(scope?.project ? { project: scope.project } : {}) });\n\nexport type RunnerStatus = {\n version: string;\n agentImage: string;\n url?: string;\n /** The app of the platform key asking (2.0): the tenants listed are those it sees. */\n app?: string;\n /** The project of the platform key asking, before 2.0. */\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; app?: 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 /** The app and the project of completions and chats (2.0): a label in the log of the runner, never a scope. */\n app?: string;\n project?: 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; app?: string; project?: 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, app, project, 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 ...(app ? { 'x-runner-app': app } : {}),\n ...(project ? { 'x-runner-project': project } : {}),\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 /**\n * `{ app }` (2.0): the platform key sees the organizations it makes and those the admin grants it. A string: the\n * project of the keys before 2.0, owning `<project>` and `<project>-…`.\n */\n pair(code: string, name?: string, scope?: RunnerPlatformScope): Promise<{ key: string; record: RunnerKey; version: string }> {\n return this.request('POST', '/v1/pair', { code, ...(name ? { name } : {}), ...scopeOf(scope) });\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, scope?: RunnerPlatformScope): Promise<RunnerPairingRequest> {\n return this.request('POST', '/v1/pair/requests', { name, ...scopeOf(scope) });\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>; modules?: string[]; 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 apps waiting for an organization another app made. */\n async grantRequests(): Promise<RunnerGrantRequest[]> {\n return (await this.request<{ grants: RunnerGrantRequest[] }>('GET', '/v1/admin/grants')).grants;\n }\n\n async answerGrant(id: string, approve: boolean): Promise<RunnerGrantRequest> {\n return (await this.request<{ grant: RunnerGrantRequest }>('POST', `/v1/admin/grants/${encodeURIComponent(id)}/${approve ? 'approve' : 'deny'}`)).grant;\n }\n\n /** A platform key sees a tenant, or (`allow: false`) no longer. */\n async grantTenant(tenant: string, key: string, allow = true): Promise<RunnerTenant> {\n return (await this.request<{ tenant: RunnerTenant }>(allow ? 'PUT' : 'DELETE', `/v1/admin/tenants/${encodeURIComponent(tenant)}/platforms/${encodeURIComponent(key)}`)).tenant;\n }\n\n /** The 2.0 migration of the tenants (`<app>-<org>` → `<org>`): a dry run unless `apply`; `map` names the others. */\n migrateTenants(options: { apply?: boolean; map?: Record<string, string> } = {}): Promise<RunnerTenantMigration> {\n return this.request('POST', '/v1/admin/migrate-tenants', options);\n }\n\n /** The project of a platform key before 2.0 (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 /**\n * A tenant, with its first project key unless `key: false` (seen once: keep it in the backend). An organization\n * another app made answers RunnerError `needs-grant` (409): the admin of the runner grants it in the console.\n */\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 /** The name of an account (its email, say); empty: none. */\n rename: async (provider: RunnerProvider, id: string, label: string): Promise<RunnerAccount[]> =>\n (await this.request<{ accounts: RunnerAccount[] }>('PATCH', `/v1/accounts/${provider}/${encodeURIComponent(id)}`, { label })).accounts,\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 /** The app and the project the person works in: labels in the log of the runner. */\n app?: string;\n project?: 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', 'PATCH', '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 ...(target.app ? { 'x-runner-app': target.app } : {}),\n ...(target.project ? { 'x-runner-project': target.project } : {}),\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',\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