@llmnative/runner 1.0.2 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -36,6 +36,11 @@ npx @llmnative/runner guide --domain runner.example.com # the steps to do it b
36
36
 
37
37
  On Coolify: `install/coolify.yaml`, then `node src/cli.ts pair` in the terminal of the service.
38
38
 
39
+ **Connecting a runner already installed, without copying codes** (device flow, as signing in to a service from
40
+ another device): the platform asks the runner (`POST /v1/pair/requests`) and shows a code; the person opens the
41
+ runner's console (`/console/?approve=<code>`, signed in with the admin token, which the browser can remember),
42
+ checks that the code is the same and approves; the platform gets its platform key by itself.
43
+
39
44
  **Console**: `https://runner.example.com/console`, signed in with the admin token
40
45
  (`docker compose -f /opt/llmnative-runner/compose.yaml exec runner node src/cli.ts admin-token`): state, pairing codes, tenants, keys, accounts of a tenant.
41
46
 
@@ -44,7 +49,7 @@ On Coolify: `install/coolify.yaml`, then `node src/cli.ts pair` in the terminal
44
49
  | Key | Who has it | What it does |
45
50
  |---|---|---|
46
51
  | admin token | the machine (`/data/admin-token`) | the console; pairing codes |
47
- | platform key `rk_platform_…` | the backend of a platform, from a pairing code | tenants and their keys; acts for any tenant with `X-Runner-Tenant` |
52
+ | platform key `rk_platform_…` | the backend of a platform, from a pairing code or an approved request | tenants and their keys; acts for any tenant with `X-Runner-Tenant` |
48
53
  | project key `rk_…` | the backend of a tenant | `complete`, `chat`, `chat:tools`, `accounts`, `accounts:tenant`, `act-as-user`, `keys` |
49
54
 
50
55
  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`).
@@ -80,6 +80,27 @@ export function startSetupServer({ port = 0, file = fleetFile(), log = () => {}
80
80
  return entry;
81
81
  }
82
82
 
83
+ // Requests to connect a runner already installed (device flow): their secrets stay here, in memory.
84
+ const pairings = new Map();
85
+ async function startPairing({ name, url }) {
86
+ const address = String(url ?? '').replace(/\/+$/, '');
87
+ if (!/^https?:\/\//.test(address)) throw Object.assign(new Error('invalid url'), { status: 400 });
88
+ const made = await new RunnerClient({ url: address }).requestPairing('setup on this computer');
89
+ const id = randomBytes(8).toString('hex');
90
+ pairings.set(id, { name: String(name || new URL(address).hostname), url: address, request: made.request, expiresAt: made.expiresAt });
91
+ log(`asked ${address} to connect: approve code ${made.code} on the runner`);
92
+ return { id, code: made.code, approveUrl: made.approveUrl, expiresAt: made.expiresAt };
93
+ }
94
+ async function pairingStatus(id) {
95
+ const pending = pairings.get(id);
96
+ if (!pending) return { status: 'expired' };
97
+ const polled = await new RunnerClient({ url: pending.url }).pollPairing(pending.request);
98
+ if (polled.status === 'pending') return polled;
99
+ pairings.delete(id);
100
+ if (polled.status !== 'approved') return { status: polled.status };
101
+ return { status: 'approved', runner: view(await connect({ name: pending.name, url: pending.url, key: polled.key })) };
102
+ }
103
+
83
104
  const server = createServer(async (request, response) => {
84
105
  const url = new URL(request.url ?? '/', 'http://localhost');
85
106
  try {
@@ -89,6 +110,8 @@ export function startSetupServer({ port = 0, file = fleetFile(), log = () => {}
89
110
  const [area, id, what] = parts;
90
111
  if (area === 'runners' && !id && request.method === 'GET') return send(response, 200, { runners: readFleet(file).runners.map(view) });
91
112
  if (area === 'runners' && !id && request.method === 'POST') return send(response, 201, { runner: view(await connect(await body(request))) });
113
+ if (area === 'pairings' && !id && request.method === 'POST') return send(response, 201, await startPairing(await body(request)));
114
+ if (area === 'pairings' && id && request.method === 'GET') return send(response, 200, await pairingStatus(id));
92
115
  const entry = readFleet(file).runners.find((runner) => runner.id === id);
93
116
  if (area === 'runners' && id && !entry) return send(response, 404, { error: 'not found' });
94
117
  if (area === 'runners' && what === 'status' && request.method === 'GET') {
package/dist/client.js CHANGED
@@ -1,3 +1,3 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=class extends Error{status;code;until;detail;constructor(e,t,n={}){super(t),this.name=`RunnerError`,this.status=e,this.code=t,n.until&&(this.until=n.until),n.detail&&(this.detail=n.detail)}},t=e=>e.type===`error`&&e.message.startsWith(`no-credit:`)?e.message.slice(10):void 0,n=class t{options;constructor(e){this.options={...e,url:e.url.replace(/\/+$/,``)}}as(e){return new t({...this.options,...e})}async headers(e){let{key:t,tenant:n,user:r,headers:i}=this.options;return{...e?{"content-type":`application/json`}:{},...t?{authorization:`Bearer ${t}`}:{},...n?{"x-runner-tenant":n}:{},...r?{"x-runner-user":r}:{},...await i?.()}}async request(t,n,r){let i=await(this.options.fetch??fetch)(`${this.options.url}${n}`,{method:t,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 e(i.status,typeof o.error==`string`?o.error:`http-${i.status}`,{...typeof o.until==`string`?{until:o.until}:{},...typeof o.detail==`string`?{detail:o.detail}:{}});return o}health(){return this.request(`GET`,`/health`)}pair(e,t){return this.request(`POST`,`/v1/pair`,{code:e,...t?{name:t}:{}})}info(){return this.request(`GET`,`/v1/info`)}createPairing(){return this.request(`POST`,`/v1/admin/pairing`)}platform={status:()=>this.request(`GET`,`/v1/platform/status`),tenants:async()=>(await this.request(`GET`,`/v1/platform/tenants`)).tenants,createTenant:(e,t={})=>this.request(`POST`,`/v1/platform/tenants`,{id:e,...t}),removeTenant:async e=>(await this.request(`DELETE`,`/v1/platform/tenants/${encodeURIComponent(e)}`)).removed,keys:async e=>(await this.request(`GET`,`/v1/platform/tenants/${encodeURIComponent(e)}/keys`)).keys,createKey:(e,t={})=>this.request(`POST`,`/v1/platform/tenants/${encodeURIComponent(e)}/keys`,t),revokeKey:async(e,t)=>(await this.request(`DELETE`,`/v1/platform/tenants/${encodeURIComponent(e)}/keys/${encodeURIComponent(t)}`)).removed,platformKeys:async()=>(await this.request(`GET`,`/v1/platform/keys`)).keys,revokePlatformKey:async e=>(await this.request(`DELETE`,`/v1/platform/keys/${encodeURIComponent(e)}`)).removed};accounts={list:async()=>this.request(`GET`,`/v1/accounts`),startClaudeLogin:()=>this.request(`POST`,`/v1/accounts/claude-code/login`),finishClaudeLogin:async(e,t)=>(await this.request(`POST`,`/v1/accounts/claude-code/login/code`,{code:e,...t?{label:t}:{}})).account,addClaudeToken:async(e,t)=>(await this.request(`POST`,`/v1/accounts/claude-code`,{token:e,...t?{label:t}:{}})).account,addKey:async(e,t,n)=>(await this.request(`POST`,`/v1/accounts/${e}`,{key:t,...n?{label:n}:{}})).account,remove:async(e,t)=>(await this.request(`DELETE`,`/v1/accounts/${e}/${encodeURIComponent(t)}`)).removed,order:async(e,t)=>(await this.request(`PUT`,`/v1/accounts/order`,{provider:e,ids:t})).accounts};models(){return this.request(`GET`,`/v1/models`)}complete(e){return this.request(`POST`,`/v1/complete`,e)}chats={start:(e,t)=>this.request(`POST`,`/v1/chats`,{id:e,...t?{tools:t}:{}}),send:(e,t,n)=>this.stream(`/v1/chats/${encodeURIComponent(e)}/messages`,t,n),answerCall:async(e,t,n)=>(await this.request(`POST`,`/v1/chats/${encodeURIComponent(e)}/calls/${encodeURIComponent(t)}`,n)).answered,stop:async e=>(await this.request(`POST`,`/v1/chats/${encodeURIComponent(e)}/stop`)).stopped,close:async e=>(await this.request(`DELETE`,`/v1/chats/${encodeURIComponent(e)}`)).closed};async*stream(t,n,r){let i=await(this.options.fetch??fetch)(`${this.options.url}${t}`,{method:`POST`,headers:await this.headers(!0),body:JSON.stringify(n),...r?{signal:r}:{}});if(!i.ok||!i.body){let t=`http-${i.status}`;try{let e=await i.json();e.error&&(t=e.error)}catch{}throw new e(i.status,t)}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(`
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=class extends Error{status;code;until;detail;constructor(e,t,n={}){super(t),this.name=`RunnerError`,this.status=e,this.code=t,n.until&&(this.until=n.until),n.detail&&(this.detail=n.detail)}},t=e=>e.type===`error`&&e.message.startsWith(`no-credit:`)?e.message.slice(10):void 0,n=class t{options;constructor(e){this.options={...e,url:e.url.replace(/\/+$/,``)}}as(e){return new t({...this.options,...e})}async headers(e){let{key:t,tenant:n,user:r,headers:i}=this.options;return{...e?{"content-type":`application/json`}:{},...t?{authorization:`Bearer ${t}`}:{},...n?{"x-runner-tenant":n}:{},...r?{"x-runner-user":r}:{},...await i?.()}}async request(t,n,r){let i=await(this.options.fetch??fetch)(`${this.options.url}${n}`,{method:t,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 e(i.status,typeof o.error==`string`?o.error:`http-${i.status}`,{...typeof o.until==`string`?{until:o.until}:{},...typeof o.detail==`string`?{detail:o.detail}:{}});return o}health(){return this.request(`GET`,`/health`)}pair(e,t){return this.request(`POST`,`/v1/pair`,{code:e,...t?{name:t}:{}})}requestPairing(e){return this.request(`POST`,`/v1/pair/requests`,{name:e})}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}platform={status:()=>this.request(`GET`,`/v1/platform/status`),tenants:async()=>(await this.request(`GET`,`/v1/platform/tenants`)).tenants,createTenant:(e,t={})=>this.request(`POST`,`/v1/platform/tenants`,{id:e,...t}),removeTenant:async e=>(await this.request(`DELETE`,`/v1/platform/tenants/${encodeURIComponent(e)}`)).removed,keys:async e=>(await this.request(`GET`,`/v1/platform/tenants/${encodeURIComponent(e)}/keys`)).keys,createKey:(e,t={})=>this.request(`POST`,`/v1/platform/tenants/${encodeURIComponent(e)}/keys`,t),revokeKey:async(e,t)=>(await this.request(`DELETE`,`/v1/platform/tenants/${encodeURIComponent(e)}/keys/${encodeURIComponent(t)}`)).removed,platformKeys:async()=>(await this.request(`GET`,`/v1/platform/keys`)).keys,revokePlatformKey:async e=>(await this.request(`DELETE`,`/v1/platform/keys/${encodeURIComponent(e)}`)).removed};accounts={list:async()=>this.request(`GET`,`/v1/accounts`),startClaudeLogin:()=>this.request(`POST`,`/v1/accounts/claude-code/login`),finishClaudeLogin:async(e,t)=>(await this.request(`POST`,`/v1/accounts/claude-code/login/code`,{code:e,...t?{label:t}:{}})).account,addClaudeToken:async(e,t)=>(await this.request(`POST`,`/v1/accounts/claude-code`,{token:e,...t?{label:t}:{}})).account,addKey:async(e,t,n)=>(await this.request(`POST`,`/v1/accounts/${e}`,{key:t,...n?{label:n}:{}})).account,remove:async(e,t)=>(await this.request(`DELETE`,`/v1/accounts/${e}/${encodeURIComponent(t)}`)).removed,order:async(e,t)=>(await this.request(`PUT`,`/v1/accounts/order`,{provider:e,ids:t})).accounts};models(){return this.request(`GET`,`/v1/models`)}complete(e){return this.request(`POST`,`/v1/complete`,e)}chats={start:(e,t)=>this.request(`POST`,`/v1/chats`,{id:e,...t?{tools:t}:{}}),send:(e,t,n)=>this.stream(`/v1/chats/${encodeURIComponent(e)}/messages`,t,n),answerCall:async(e,t,n)=>(await this.request(`POST`,`/v1/chats/${encodeURIComponent(e)}/calls/${encodeURIComponent(t)}`,n)).answered,stop:async e=>(await this.request(`POST`,`/v1/chats/${encodeURIComponent(e)}/stop`)).stopped,close:async e=>(await this.request(`DELETE`,`/v1/chats/${encodeURIComponent(e)}`)).closed};async*stream(t,n,r){let i=await(this.options.fetch??fetch)(`${this.options.url}${t}`,{method:`POST`,headers:await this.headers(!0),body:JSON.stringify(n),...r?{signal:r}:{}});if(!i.ok||!i.body){let t=`http-${i.status}`;try{let e=await i.json();e.error&&(t=e.error)}catch{}throw new e(i.status,t)}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
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}}},r=/^\/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 i(e,t,n,i=fetch){if(!r.test(t)||![`GET`,`POST`,`PUT`,`DELETE`].includes(e.method))return new Response(JSON.stringify({error:`not found`}),{status:404,headers:{"content-type":`application/json`}});let a={authorization:`Bearer ${n.key}`,"x-runner-user":n.user,...n.tenant?{"x-runner-tenant":n.tenant}:{}},o=e.headers.get(`content-type`);o&&(a[`content-type`]=o);let s=e.method===`GET`||e.method===`DELETE`?void 0:await e.arrayBuffer(),c=new URL(e.url),l=await i(`${n.url.replace(/\/+$/,``)}${t}${c.search}`,{method:e.method,headers:a,...s?{body:s}:{},signal:e.signal});return new Response(l.body,{status:l.status,headers:{"content-type":l.headers.get(`content-type`)??`application/json`,"cache-control":`no-store`,"x-accel-buffering":`no`}})}exports.RunnerClient=n,exports.RunnerError=e,exports.forwardToRunner=i,exports.noCreditUntil=t;
3
3
  //# sourceMappingURL=client.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"client.js","names":["RunnerError","code","status","extra","noCreditUntil","event","RunnerClient","options","scope","json","key","tenant","user","headers","response","path","body","text","data","name","id","input","label","provider","request","tools","message","signal","callId","answer","reader","decoder","buffer","value","done","lines","line","PERSON_ROUTES","forwardToRunner","target","type","url","fetchImpl"],"sources":["../src/client/index.ts"],"sourcesContent":["// @llmnative/runner/client — the client of the API v1 of the LLMNative Runner, for the browser and for Node.\n//\n// A key never belongs in the browser of the people of a tenant: a host app talks to the runner from its backend\n// (`createRunnerProxy` forwards the requests of its signed-in people, adding the key, the tenant and the person),\n// and its pages use `RunnerClient` against that backend. The console of the runner and a personal app with a key of\n// its own use `RunnerClient` directly.\n\nexport type RunnerProvider = 'claude-code' | 'opencode-go' | 'opencode';\nexport type RunnerPermission = 'complete' | 'chat' | 'chat:tools' | 'accounts' | 'accounts:tenant' | 'act-as-user' | 'keys';\n\nexport type RunnerAccount = {\n provider: RunnerProvider;\n id: string;\n label?: string;\n /** When it was connected. */\n at: string;\n scope: 'user' | 'tenant';\n /** Out of credit until then (the limit of a subscription); absent when it has credit. */\n noCreditUntil?: string;\n};\n\nexport type RunnerModels = {\n providers: Array<{ id: 'claude-code' | 'opencode-go'; models: string[]; accounts: number; available: number; yours: number; tenant: number }>;\n};\n\nexport type RunnerTenant = { id: string; name: string; createdAt: string; usersWithAccounts?: number };\nexport type RunnerKey = { id: string; kind: 'platform' | 'project'; tenant?: string; name: string; permissions: RunnerPermission[]; createdAt: string; expiresAt: string | null };\n\nexport type RunnerStatus = {\n version: string;\n agentImage: string;\n url?: string;\n load: { chats: number; answering: number; completions: number; maxChats: number };\n machine: { totalBytes: number; availableBytes: number; cpus: number };\n tenants: RunnerTenant[];\n};\n\nexport type RunnerHealth = { ok: boolean; version: string; chats: number; answering: number; completions: number; maxChats: number };\n\nexport type RunnerCompletionRequest = { provider: 'claude-code' | 'opencode-go'; model: string; prompt: string; effort?: 'low' | 'medium' | 'high' | 'xhigh' | 'max' };\nexport type RunnerCompletion = { text: string; usage?: { inputTokens: number; outputTokens: number } };\n\nexport type RunnerChatTool = { name: string; description: string; inputSchema: Record<string, unknown>; endsTurn?: boolean };\nexport type RunnerChatModel = { provider: string; model: string; variant?: string; name?: string; effort?: string };\nexport type RunnerChatEvent =\n | { type: 'text'; text: string }\n | { type: 'reasoning'; text: string }\n | { type: 'step'; id: string; label: string; status: 'running' | 'done' }\n | { type: 'tool-call'; id: string; name: string; input: Record<string, unknown> }\n | { type: 'done' }\n | { type: 'error'; message: string };\n\n/** An error of the runner: its status and code (`no-credit`, `busy`…), and for `no-credit` until when. */\nexport class RunnerError extends Error {\n readonly status: number;\n readonly code: string;\n readonly until?: string;\n readonly detail?: string;\n\n constructor(status: number, code: string, extra: { until?: string; detail?: string } = {}) {\n super(code);\n this.name = 'RunnerError';\n this.status = status;\n this.code = code;\n if (extra.until) this.until = extra.until;\n if (extra.detail) this.detail = extra.detail;\n }\n}\n\n/** When a chat event says the accounts ran out of credit: until when (`no-credit:<iso>`). */\nexport const noCreditUntil = (event: RunnerChatEvent): string | undefined =>\n event.type === 'error' && event.message.startsWith('no-credit:') ? event.message.slice('no-credit:'.length) : undefined;\n\nexport type RunnerClientOptions = {\n /** The address of the runner (`https://runner.example.com`), or of the backend of the host that forwards to it. */\n url: string;\n /** A key of the runner (or the admin token in the console); none when the backend of the host adds it. */\n key?: string;\n /** With a platform key or the admin token: the tenant the requests are for. */\n tenant?: string;\n /** The person the requests are for (needs `act-as-user` with a project key). */\n user?: string;\n fetch?: typeof fetch;\n /** More headers for each request (the session of the host, for its backend). */\n headers?: () => Record<string, string> | Promise<Record<string, string>>;\n};\n\nexport class RunnerClient {\n readonly options: RunnerClientOptions;\n\n constructor(options: RunnerClientOptions) {\n this.options = { ...options, url: options.url.replace(/\\/+$/, '') };\n }\n\n /** The same runner for another tenant or person. */\n as(scope: { tenant?: string; user?: string }): RunnerClient {\n return new RunnerClient({ ...this.options, ...scope });\n }\n\n private async headers(json: boolean): Promise<Record<string, string>> {\n const { key, tenant, user, headers } = this.options;\n return {\n ...(json ? { 'content-type': 'application/json' } : {}),\n ...(key ? { authorization: `Bearer ${key}` } : {}),\n ...(tenant ? { 'x-runner-tenant': tenant } : {}),\n ...(user ? { 'x-runner-user': user } : {}),\n ...(await headers?.()),\n };\n }\n\n /** One request; its JSON, or a RunnerError. */\n async request<T>(method: string, path: string, body?: unknown): Promise<T> {\n const response = await (this.options.fetch ?? fetch)(`${this.options.url}${path}`, {\n method,\n headers: await this.headers(body !== undefined),\n ...(body !== undefined ? { body: JSON.stringify(body) } : {}),\n });\n const text = await response.text();\n let data: Record<string, unknown> = {};\n try {\n data = text ? JSON.parse(text) as Record<string, unknown> : {};\n } catch {\n // Not JSON (a proxy in between): said by its status.\n }\n if (!response.ok) {\n throw new RunnerError(response.status, typeof data.error === 'string' ? data.error : `http-${response.status}`, {\n ...(typeof data.until === 'string' ? { until: data.until } : {}),\n ...(typeof data.detail === 'string' ? { detail: data.detail } : {}),\n });\n }\n return data as T;\n }\n\n // ── Public ──────────────────────────────────────────────────────────────────────────────────────────────\n health(): Promise<RunnerHealth> {\n return this.request('GET', '/health');\n }\n\n /** A pairing code (printed by the installer) → a platform key, seen once. */\n pair(code: string, name?: string): Promise<{ key: string; record: RunnerKey; version: string }> {\n return this.request('POST', '/v1/pair', { code, ...(name ? { name } : {}) });\n }\n\n info(): Promise<{ version: string; harnesses: string[]; capabilities: Record<string, boolean>; permissions: RunnerPermission[]; tenant?: string }> {\n return this.request('GET', '/v1/info');\n }\n\n // ── Admin token ─────────────────────────────────────────────────────────────────────────────────────────\n createPairing(): Promise<{ code: string; expiresAt: string }> {\n return this.request('POST', '/v1/admin/pairing');\n }\n\n // ── Platform key ────────────────────────────────────────────────────────────────────────────────────────\n readonly platform = {\n status: (): Promise<RunnerStatus> => this.request('GET', '/v1/platform/status'),\n tenants: async (): Promise<RunnerTenant[]> => (await this.request<{ tenants: RunnerTenant[] }>('GET', '/v1/platform/tenants')).tenants,\n /** A tenant, with its first project key unless `key: false` (seen once: keep it in the backend). */\n createTenant: (id: string, options: { name?: string; key?: boolean; keyPermissions?: RunnerPermission[] } = {}): Promise<{ tenant: RunnerTenant; key?: string; keyRecord?: RunnerKey }> =>\n this.request('POST', '/v1/platform/tenants', { id, ...options }),\n removeTenant: async (id: string): Promise<boolean> => (await this.request<{ removed: boolean }>('DELETE', `/v1/platform/tenants/${encodeURIComponent(id)}`)).removed,\n keys: async (tenant: string): Promise<RunnerKey[]> => (await this.request<{ keys: RunnerKey[] }>('GET', `/v1/platform/tenants/${encodeURIComponent(tenant)}/keys`)).keys,\n createKey: (tenant: string, input: { name?: string; permissions?: RunnerPermission[]; expiresAt?: string | null } = {}): Promise<{ key: string; record: RunnerKey }> =>\n this.request('POST', `/v1/platform/tenants/${encodeURIComponent(tenant)}/keys`, input),\n revokeKey: async (tenant: string, id: string): Promise<boolean> => (await this.request<{ removed: boolean }>('DELETE', `/v1/platform/tenants/${encodeURIComponent(tenant)}/keys/${encodeURIComponent(id)}`)).removed,\n platformKeys: async (): Promise<RunnerKey[]> => (await this.request<{ keys: RunnerKey[] }>('GET', '/v1/platform/keys')).keys,\n revokePlatformKey: async (id: string): Promise<boolean> => (await this.request<{ removed: boolean }>('DELETE', `/v1/platform/keys/${encodeURIComponent(id)}`)).removed,\n };\n\n // ── Accounts of the person (or of the tenant) ───────────────────────────────────────────────────────────\n readonly accounts = {\n list: async (): Promise<{ scope: 'user' | 'tenant'; accounts: RunnerAccount[] }> => this.request('GET', '/v1/accounts'),\n /** The sign-in of a Claude subscription: open `url`, then give the code Anthropic shows to `finishClaudeLogin`. */\n startClaudeLogin: (): Promise<{ url: string }> => this.request('POST', '/v1/accounts/claude-code/login'),\n finishClaudeLogin: async (code: string, label?: string): Promise<RunnerAccount> =>\n (await this.request<{ account: RunnerAccount }>('POST', '/v1/accounts/claude-code/login/code', { code, ...(label ? { label } : {}) })).account,\n /** A token made elsewhere with `claude setup-token`. */\n addClaudeToken: async (token: string, label?: string): Promise<RunnerAccount> =>\n (await this.request<{ account: RunnerAccount }>('POST', '/v1/accounts/claude-code', { token, ...(label ? { label } : {}) })).account,\n addKey: async (provider: 'opencode-go' | 'opencode', key: string, label?: string): Promise<RunnerAccount> =>\n (await this.request<{ account: RunnerAccount }>('POST', `/v1/accounts/${provider}`, { key, ...(label ? { label } : {}) })).account,\n remove: async (provider: RunnerProvider, id: string): Promise<boolean> =>\n (await this.request<{ removed: boolean }>('DELETE', `/v1/accounts/${provider}/${encodeURIComponent(id)}`)).removed,\n order: async (provider: RunnerProvider, ids: string[]): Promise<RunnerAccount[]> =>\n (await this.request<{ accounts: RunnerAccount[] }>('PUT', '/v1/accounts/order', { provider, ids })).accounts,\n };\n\n models(): Promise<RunnerModels> {\n return this.request('GET', '/v1/models');\n }\n\n complete(request: RunnerCompletionRequest): Promise<RunnerCompletion> {\n return this.request('POST', '/v1/complete', request);\n }\n\n // ── Chats ───────────────────────────────────────────────────────────────────────────────────────────────\n readonly chats = {\n /** A chat (id: 8 hex characters, chosen by the client), with the tools the harness may call. */\n start: (id: string, tools?: RunnerChatTool[]): Promise<{ id: string }> => this.request('POST', '/v1/chats', { id, ...(tools ? { tools } : {}) }),\n /** A message: its events as they come. Aborting the signal stops the harness. */\n send: (id: string, message: { text: string; model: RunnerChatModel; attachments?: Array<{ name: string; mimeType: string; base64: string }> }, signal?: AbortSignal): AsyncIterable<RunnerChatEvent> =>\n this.stream(`/v1/chats/${encodeURIComponent(id)}/messages`, message, signal),\n answerCall: async (id: string, callId: string, answer: { result?: unknown; isError?: boolean }): Promise<boolean> =>\n (await this.request<{ answered: boolean }>('POST', `/v1/chats/${encodeURIComponent(id)}/calls/${encodeURIComponent(callId)}`, answer)).answered,\n stop: async (id: string): Promise<boolean> => (await this.request<{ stopped: boolean }>('POST', `/v1/chats/${encodeURIComponent(id)}/stop`)).stopped,\n close: async (id: string): Promise<boolean> => (await this.request<{ closed: boolean }>('DELETE', `/v1/chats/${encodeURIComponent(id)}`)).closed,\n };\n\n private async *stream(path: string, body: unknown, signal?: AbortSignal): AsyncIterable<RunnerChatEvent> {\n const response = await (this.options.fetch ?? fetch)(`${this.options.url}${path}`, { method: 'POST', headers: await this.headers(true), body: JSON.stringify(body), ...(signal ? { signal } : {}) });\n if (!response.ok || !response.body) {\n let code = `http-${response.status}`;\n try {\n const data = await response.json() as { error?: string };\n if (data.error) code = data.error;\n } catch {\n // Said by its status.\n }\n throw new RunnerError(response.status, code);\n }\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n for (;;) {\n const { done, value } = await reader.read();\n buffer += decoder.decode(value ?? new Uint8Array(), { stream: !done });\n const lines = buffer.split('\\n');\n buffer = done ? '' : lines.pop() ?? '';\n for (const line of lines) {\n if (!line.trim()) continue;\n let event: RunnerChatEvent | { type: 'ping' };\n try {\n event = JSON.parse(line) as RunnerChatEvent | { type: 'ping' };\n } catch {\n continue;\n }\n if (event.type !== 'ping') yield event;\n }\n if (done) return;\n }\n }\n}\n\n// ── For the backend of a host ───────────────────────────────────────────────────────────────────────────────\n\n/** The routes the people of a tenant may reach through the backend of the host: never the platform ones. */\nconst PERSON_ROUTES = /^\\/v1\\/(info|models|complete|accounts(\\/[A-Za-z0-9_.:-]+){0,3}|chats(\\/[a-f0-9]{8}(\\/(messages|stop|calls\\/[a-f0-9]{12}))?)?)$/;\n\nexport type RunnerProxyTarget = {\n /** The address of the runner of this tenant. */\n url: string;\n /** A project key of the tenant (with `act-as-user`), or a platform key with `tenant`. */\n key: string;\n tenant?: string;\n /** The signed-in person, verified by the host. */\n user: string;\n};\n\n/**\n * Forwards a request of a signed-in person to their runner: only the routes of a person, with the key, tenant and\n * person added by the host (whatever the browser sent for them is dropped). Streams answers (chat replies) as they\n * come. `path` is the path of the runner, e.g. `/v1/models` (the host strips its own prefix).\n */\nexport async function forwardToRunner(request: Request, path: string, target: RunnerProxyTarget, fetchImpl: typeof fetch = fetch): Promise<Response> {\n if (!PERSON_ROUTES.test(path)) return new Response(JSON.stringify({ error: 'not found' }), { status: 404, headers: { 'content-type': 'application/json' } });\n if (!['GET', 'POST', 'PUT', 'DELETE'].includes(request.method)) return new Response(JSON.stringify({ error: 'not found' }), { status: 404, headers: { 'content-type': 'application/json' } });\n const headers: Record<string, string> = {\n authorization: `Bearer ${target.key}`,\n 'x-runner-user': target.user,\n ...(target.tenant ? { 'x-runner-tenant': target.tenant } : {}),\n };\n const type = request.headers.get('content-type');\n if (type) headers['content-type'] = type;\n const body = request.method === 'GET' || request.method === 'DELETE' ? undefined : await request.arrayBuffer();\n const url = new URL(request.url);\n const answer = await fetchImpl(`${target.url.replace(/\\/+$/, '')}${path}${url.search}`, {\n method: request.method,\n headers,\n ...(body ? { body } : {}),\n signal: request.signal,\n });\n return new Response(answer.body, {\n status: answer.status,\n headers: {\n 'content-type': answer.headers.get('content-type') ?? 'application/json',\n 'cache-control': 'no-store',\n 'x-accel-buffering': 'no',\n },\n });\n}\n"],"mappings":"A,mEAqDA,IAAaA,EAAb,cAAiC,KAAM,CACnC,OACA,KACA,MACA,OAEA,YAAY,EAAgB,EAAc,EAA6C,CAAC,EAAG,CACvF,MAAMC,CAAI,EACV,KAAK,KAAO,cACZ,KAAK,OAASC,EACd,KAAK,KAAOD,EACRE,EAAM,QAAO,KAAK,MAAQA,EAAM,OAChCA,EAAM,SAAQ,KAAK,OAASA,EAAM,OAC1C,CACJ,EAGaC,EAAiB,GAC1BC,EAAM,OAAS,SAAWA,EAAM,QAAQ,WAAW,YAAY,EAAIA,EAAM,QAAQ,MAAM,EAAmB,EAAI,IAAA,GAgBrGC,EAAb,MAAaA,CAAa,CACtB,QAEA,YAAY,EAA8B,CACtC,KAAK,QAAU,CAAE,GAAGC,EAAS,IAAKA,EAAQ,IAAI,QAAQ,OAAQ,EAAE,CAAE,CACtE,CAGA,GAAG,EAAyD,CACxD,OAAO,IAAID,EAAa,CAAE,GAAG,KAAK,QAAS,GAAGE,CAAM,CAAC,CACzD,CAEA,MAAc,QAAQ,EAAgD,CAClE,GAAM,CAAE,MAAK,SAAQ,OAAM,WAAY,KAAK,QAC5C,MAAO,CACH,GAAIC,EAAO,CAAE,eAAgB,kBAAmB,EAAI,CAAC,EACrD,GAAIC,EAAM,CAAE,cAAe,UAAUA,GAAM,EAAI,CAAC,EAChD,GAAIC,EAAS,CAAE,kBAAmBA,CAAO,EAAI,CAAC,EAC9C,GAAIC,EAAO,CAAE,gBAAiBA,CAAK,EAAI,CAAC,EACxC,GAAI,MAAMC,IAAU,CACxB,CACJ,CAGA,MAAM,QAAW,EAAgB,EAAc,EAA4B,CACvE,IAAMC,EAAW,MAAO,KAAK,QAAQ,OAAS,MAAA,CAAO,GAAG,KAAK,QAAQ,MAAMC,IAA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,IAAIxB,IAAO0B,EAAI,SAAU,CACpF,OAAQjB,EAAQ,OAChB,UACA,GAAIR,EAAO,CAAE,MAAK,EAAI,CAAC,EACvB,OAAQQ,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":["RunnerError","code","status","extra","noCreditUntil","event","RunnerClient","options","scope","json","key","tenant","user","headers","response","path","body","text","data","name","approve","id","input","label","provider","request","tools","message","signal","callId","answer","reader","decoder","buffer","value","done","lines","line","PERSON_ROUTES","forwardToRunner","target","type","url","fetchImpl"],"sources":["../src/client/index.ts"],"sourcesContent":["// @llmnative/runner/client — the client of the API v1 of the LLMNative Runner, for the browser and for Node.\n//\n// A key never belongs in the browser of the people of a tenant: a host app talks to the runner from its backend\n// (`createRunnerProxy` forwards the requests of its signed-in people, adding the key, the tenant and the person),\n// and its pages use `RunnerClient` against that backend. The console of the runner and a personal app with a key of\n// its own use `RunnerClient` directly.\n\nexport type RunnerProvider = 'claude-code' | 'opencode-go' | 'opencode';\nexport type RunnerPermission = 'complete' | 'chat' | 'chat:tools' | 'accounts' | 'accounts:tenant' | 'act-as-user' | 'keys';\n\nexport type RunnerAccount = {\n provider: RunnerProvider;\n id: string;\n label?: string;\n /** When it was connected. */\n at: string;\n scope: 'user' | 'tenant';\n /** Out of credit until then (the limit of a subscription); absent when it has credit. */\n noCreditUntil?: string;\n};\n\nexport type RunnerModels = {\n providers: Array<{ id: 'claude-code' | 'opencode-go'; models: string[]; accounts: number; available: number; yours: number; tenant: number }>;\n};\n\nexport type RunnerTenant = { id: string; name: string; createdAt: string; usersWithAccounts?: number };\nexport type RunnerKey = { id: string; kind: 'platform' | 'project'; tenant?: string; name: string; permissions: RunnerPermission[]; createdAt: string; expiresAt: string | null };\n\nexport type RunnerStatus = {\n version: string;\n agentImage: string;\n url?: string;\n load: { chats: number; answering: number; completions: number; maxChats: number };\n machine: { totalBytes: number; availableBytes: number; cpus: number };\n tenants: RunnerTenant[];\n};\n\n/** A pairing request made by a platform: `request` is its secret (keep it in the backend), `code` is shown on both sides. */\nexport type RunnerPairingRequest = { request: string; code: string; approveUrl: string; expiresAt: string; interval: number };\nexport type RunnerPairingPoll = { status: 'pending' | 'denied' | 'expired' } | { status: 'approved'; key: string; record: RunnerKey; version: string };\nexport type RunnerPairingRequestView = { code: string; name: string; from?: string; createdAt: string; expiresAt: string };\nexport type RunnerHealth = { ok: boolean; version: string; chats: number; answering: number; completions: number; maxChats: number };\n\nexport type RunnerCompletionRequest = { provider: 'claude-code' | 'opencode-go'; model: string; prompt: string; effort?: 'low' | 'medium' | 'high' | 'xhigh' | 'max' };\nexport type RunnerCompletion = { text: string; usage?: { inputTokens: number; outputTokens: number } };\n\nexport type RunnerChatTool = { name: string; description: string; inputSchema: Record<string, unknown>; endsTurn?: boolean };\nexport type RunnerChatModel = { provider: string; model: string; variant?: string; name?: string; effort?: string };\nexport type RunnerChatEvent =\n | { type: 'text'; text: string }\n | { type: 'reasoning'; text: string }\n | { type: 'step'; id: string; label: string; status: 'running' | 'done' }\n | { type: 'tool-call'; id: string; name: string; input: Record<string, unknown> }\n | { type: 'done' }\n | { type: 'error'; message: string };\n\n/** An error of the runner: its status and code (`no-credit`, `busy`…), and for `no-credit` until when. */\nexport class RunnerError extends Error {\n readonly status: number;\n readonly code: string;\n readonly until?: string;\n readonly detail?: string;\n\n constructor(status: number, code: string, extra: { until?: string; detail?: string } = {}) {\n super(code);\n this.name = 'RunnerError';\n this.status = status;\n this.code = code;\n if (extra.until) this.until = extra.until;\n if (extra.detail) this.detail = extra.detail;\n }\n}\n\n/** When a chat event says the accounts ran out of credit: until when (`no-credit:<iso>`). */\nexport const noCreditUntil = (event: RunnerChatEvent): string | undefined =>\n event.type === 'error' && event.message.startsWith('no-credit:') ? event.message.slice('no-credit:'.length) : undefined;\n\nexport type RunnerClientOptions = {\n /** The address of the runner (`https://runner.example.com`), or of the backend of the host that forwards to it. */\n url: string;\n /** A key of the runner (or the admin token in the console); none when the backend of the host adds it. */\n key?: string;\n /** With a platform key or the admin token: the tenant the requests are for. */\n tenant?: string;\n /** The person the requests are for (needs `act-as-user` with a project key). */\n user?: string;\n fetch?: typeof fetch;\n /** More headers for each request (the session of the host, for its backend). */\n headers?: () => Record<string, string> | Promise<Record<string, string>>;\n};\n\nexport class RunnerClient {\n readonly options: RunnerClientOptions;\n\n constructor(options: RunnerClientOptions) {\n this.options = { ...options, url: options.url.replace(/\\/+$/, '') };\n }\n\n /** The same runner for another tenant or person. */\n as(scope: { tenant?: string; user?: string }): RunnerClient {\n return new RunnerClient({ ...this.options, ...scope });\n }\n\n private async headers(json: boolean): Promise<Record<string, string>> {\n const { key, tenant, user, headers } = this.options;\n return {\n ...(json ? { 'content-type': 'application/json' } : {}),\n ...(key ? { authorization: `Bearer ${key}` } : {}),\n ...(tenant ? { 'x-runner-tenant': tenant } : {}),\n ...(user ? { 'x-runner-user': user } : {}),\n ...(await headers?.()),\n };\n }\n\n /** One request; its JSON, or a RunnerError. */\n async request<T>(method: string, path: string, body?: unknown): Promise<T> {\n const response = await (this.options.fetch ?? fetch)(`${this.options.url}${path}`, {\n method,\n headers: await this.headers(body !== undefined),\n ...(body !== undefined ? { body: JSON.stringify(body) } : {}),\n });\n const text = await response.text();\n let data: Record<string, unknown> = {};\n try {\n data = text ? JSON.parse(text) as Record<string, unknown> : {};\n } catch {\n // Not JSON (a proxy in between): said by its status.\n }\n if (!response.ok) {\n throw new RunnerError(response.status, typeof data.error === 'string' ? data.error : `http-${response.status}`, {\n ...(typeof data.until === 'string' ? { until: data.until } : {}),\n ...(typeof data.detail === 'string' ? { detail: data.detail } : {}),\n });\n }\n return data as T;\n }\n\n // ── Public ──────────────────────────────────────────────────────────────────────────────────────────────\n health(): Promise<RunnerHealth> {\n return this.request('GET', '/health');\n }\n\n /** A pairing code (printed by the installer) → a platform key, seen once. */\n pair(code: string, name?: string): Promise<{ key: string; record: RunnerKey; version: string }> {\n return this.request('POST', '/v1/pair', { code, ...(name ? { name } : {}) });\n }\n\n /**\n * Asks to connect (device flow): the admin of the runner approves it in the console at `approveUrl`, where the\n * same `code` is shown; meanwhile `pollPairing(request)` every `interval` seconds, until it gives the key.\n */\n requestPairing(name: string): Promise<RunnerPairingRequest> {\n return this.request('POST', '/v1/pair/requests', { name });\n }\n\n pollPairing(request: string): Promise<RunnerPairingPoll> {\n return this.request('POST', '/v1/pair/requests/poll', { request });\n }\n\n info(): Promise<{ version: string; harnesses: string[]; capabilities: Record<string, boolean>; permissions: RunnerPermission[]; tenant?: string }> {\n return this.request('GET', '/v1/info');\n }\n\n // ── Admin token ─────────────────────────────────────────────────────────────────────────────────────────\n createPairing(): Promise<{ code: string; expiresAt: string }> {\n return this.request('POST', '/v1/admin/pairing');\n }\n\n async pairingRequests(): Promise<RunnerPairingRequestView[]> {\n return (await this.request<{ requests: RunnerPairingRequestView[] }>('GET', '/v1/admin/pairing/requests')).requests;\n }\n\n async answerPairing(code: string, approve: boolean): Promise<RunnerPairingRequestView> {\n return (await this.request<{ request: RunnerPairingRequestView }>('POST', `/v1/admin/pairing/requests/${encodeURIComponent(code)}/${approve ? 'approve' : 'deny'}`)).request;\n }\n\n // ── Platform key ────────────────────────────────────────────────────────────────────────────────────────\n readonly platform = {\n status: (): Promise<RunnerStatus> => this.request('GET', '/v1/platform/status'),\n tenants: async (): Promise<RunnerTenant[]> => (await this.request<{ tenants: RunnerTenant[] }>('GET', '/v1/platform/tenants')).tenants,\n /** A tenant, with its first project key unless `key: false` (seen once: keep it in the backend). */\n createTenant: (id: string, options: { name?: string; key?: boolean; keyPermissions?: RunnerPermission[] } = {}): Promise<{ tenant: RunnerTenant; key?: string; keyRecord?: RunnerKey }> =>\n this.request('POST', '/v1/platform/tenants', { id, ...options }),\n removeTenant: async (id: string): Promise<boolean> => (await this.request<{ removed: boolean }>('DELETE', `/v1/platform/tenants/${encodeURIComponent(id)}`)).removed,\n keys: async (tenant: string): Promise<RunnerKey[]> => (await this.request<{ keys: RunnerKey[] }>('GET', `/v1/platform/tenants/${encodeURIComponent(tenant)}/keys`)).keys,\n createKey: (tenant: string, input: { name?: string; permissions?: RunnerPermission[]; expiresAt?: string | null } = {}): Promise<{ key: string; record: RunnerKey }> =>\n this.request('POST', `/v1/platform/tenants/${encodeURIComponent(tenant)}/keys`, input),\n revokeKey: async (tenant: string, id: string): Promise<boolean> => (await this.request<{ removed: boolean }>('DELETE', `/v1/platform/tenants/${encodeURIComponent(tenant)}/keys/${encodeURIComponent(id)}`)).removed,\n platformKeys: async (): Promise<RunnerKey[]> => (await this.request<{ keys: RunnerKey[] }>('GET', '/v1/platform/keys')).keys,\n revokePlatformKey: async (id: string): Promise<boolean> => (await this.request<{ removed: boolean }>('DELETE', `/v1/platform/keys/${encodeURIComponent(id)}`)).removed,\n };\n\n // ── Accounts of the person (or of the tenant) ───────────────────────────────────────────────────────────\n readonly accounts = {\n list: async (): Promise<{ scope: 'user' | 'tenant'; accounts: RunnerAccount[] }> => this.request('GET', '/v1/accounts'),\n /** The sign-in of a Claude subscription: open `url`, then give the code Anthropic shows to `finishClaudeLogin`. */\n startClaudeLogin: (): Promise<{ url: string }> => this.request('POST', '/v1/accounts/claude-code/login'),\n finishClaudeLogin: async (code: string, label?: string): Promise<RunnerAccount> =>\n (await this.request<{ account: RunnerAccount }>('POST', '/v1/accounts/claude-code/login/code', { code, ...(label ? { label } : {}) })).account,\n /** A token made elsewhere with `claude setup-token`. */\n addClaudeToken: async (token: string, label?: string): Promise<RunnerAccount> =>\n (await this.request<{ account: RunnerAccount }>('POST', '/v1/accounts/claude-code', { token, ...(label ? { label } : {}) })).account,\n addKey: async (provider: 'opencode-go' | 'opencode', key: string, label?: string): Promise<RunnerAccount> =>\n (await this.request<{ account: RunnerAccount }>('POST', `/v1/accounts/${provider}`, { key, ...(label ? { label } : {}) })).account,\n remove: async (provider: RunnerProvider, id: string): Promise<boolean> =>\n (await this.request<{ removed: boolean }>('DELETE', `/v1/accounts/${provider}/${encodeURIComponent(id)}`)).removed,\n order: async (provider: RunnerProvider, ids: string[]): Promise<RunnerAccount[]> =>\n (await this.request<{ accounts: RunnerAccount[] }>('PUT', '/v1/accounts/order', { provider, ids })).accounts,\n };\n\n models(): Promise<RunnerModels> {\n return this.request('GET', '/v1/models');\n }\n\n complete(request: RunnerCompletionRequest): Promise<RunnerCompletion> {\n return this.request('POST', '/v1/complete', request);\n }\n\n // ── Chats ───────────────────────────────────────────────────────────────────────────────────────────────\n readonly chats = {\n /** A chat (id: 8 hex characters, chosen by the client), with the tools the harness may call. */\n start: (id: string, tools?: RunnerChatTool[]): Promise<{ id: string }> => this.request('POST', '/v1/chats', { id, ...(tools ? { tools } : {}) }),\n /** A message: its events as they come. Aborting the signal stops the harness. */\n send: (id: string, message: { text: string; model: RunnerChatModel; attachments?: Array<{ name: string; mimeType: string; base64: string }> }, signal?: AbortSignal): AsyncIterable<RunnerChatEvent> =>\n this.stream(`/v1/chats/${encodeURIComponent(id)}/messages`, message, signal),\n answerCall: async (id: string, callId: string, answer: { result?: unknown; isError?: boolean }): Promise<boolean> =>\n (await this.request<{ answered: boolean }>('POST', `/v1/chats/${encodeURIComponent(id)}/calls/${encodeURIComponent(callId)}`, answer)).answered,\n stop: async (id: string): Promise<boolean> => (await this.request<{ stopped: boolean }>('POST', `/v1/chats/${encodeURIComponent(id)}/stop`)).stopped,\n close: async (id: string): Promise<boolean> => (await this.request<{ closed: boolean }>('DELETE', `/v1/chats/${encodeURIComponent(id)}`)).closed,\n };\n\n private async *stream(path: string, body: unknown, signal?: AbortSignal): AsyncIterable<RunnerChatEvent> {\n const response = await (this.options.fetch ?? fetch)(`${this.options.url}${path}`, { method: 'POST', headers: await this.headers(true), body: JSON.stringify(body), ...(signal ? { signal } : {}) });\n if (!response.ok || !response.body) {\n let code = `http-${response.status}`;\n try {\n const data = await response.json() as { error?: string };\n if (data.error) code = data.error;\n } catch {\n // Said by its status.\n }\n throw new RunnerError(response.status, code);\n }\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n for (;;) {\n const { done, value } = await reader.read();\n buffer += decoder.decode(value ?? new Uint8Array(), { stream: !done });\n const lines = buffer.split('\\n');\n buffer = done ? '' : lines.pop() ?? '';\n for (const line of lines) {\n if (!line.trim()) continue;\n let event: RunnerChatEvent | { type: 'ping' };\n try {\n event = JSON.parse(line) as RunnerChatEvent | { type: 'ping' };\n } catch {\n continue;\n }\n if (event.type !== 'ping') yield event;\n }\n if (done) return;\n }\n }\n}\n\n// ── For the backend of a host ───────────────────────────────────────────────────────────────────────────────\n\n/** The routes the people of a tenant may reach through the backend of the host: never the platform ones. */\nconst PERSON_ROUTES = /^\\/v1\\/(info|models|complete|accounts(\\/[A-Za-z0-9_.:-]+){0,3}|chats(\\/[a-f0-9]{8}(\\/(messages|stop|calls\\/[a-f0-9]{12}))?)?)$/;\n\nexport type RunnerProxyTarget = {\n /** The address of the runner of this tenant. */\n url: string;\n /** A project key of the tenant (with `act-as-user`), or a platform key with `tenant`. */\n key: string;\n tenant?: string;\n /** The signed-in person, verified by the host. */\n user: string;\n};\n\n/**\n * Forwards a request of a signed-in person to their runner: only the routes of a person, with the key, tenant and\n * person added by the host (whatever the browser sent for them is dropped). Streams answers (chat replies) as they\n * come. `path` is the path of the runner, e.g. `/v1/models` (the host strips its own prefix).\n */\nexport async function forwardToRunner(request: Request, path: string, target: RunnerProxyTarget, fetchImpl: typeof fetch = fetch): Promise<Response> {\n if (!PERSON_ROUTES.test(path)) return new Response(JSON.stringify({ error: 'not found' }), { status: 404, headers: { 'content-type': 'application/json' } });\n if (!['GET', 'POST', 'PUT', 'DELETE'].includes(request.method)) return new Response(JSON.stringify({ error: 'not found' }), { status: 404, headers: { 'content-type': 'application/json' } });\n const headers: Record<string, string> = {\n authorization: `Bearer ${target.key}`,\n 'x-runner-user': target.user,\n ...(target.tenant ? { 'x-runner-tenant': target.tenant } : {}),\n };\n const type = request.headers.get('content-type');\n if (type) headers['content-type'] = type;\n const body = request.method === 'GET' || request.method === 'DELETE' ? undefined : await request.arrayBuffer();\n const url = new URL(request.url);\n const answer = await fetchImpl(`${target.url.replace(/\\/+$/, '')}${path}${url.search}`, {\n method: request.method,\n headers,\n ...(body ? { body } : {}),\n signal: request.signal,\n });\n return new Response(answer.body, {\n status: answer.status,\n headers: {\n 'content-type': answer.headers.get('content-type') ?? 'application/json',\n 'cache-control': 'no-store',\n 'x-accel-buffering': 'no',\n },\n });\n}\n"],"mappings":"A,mEAyDA,IAAaA,EAAb,cAAiC,KAAM,CACnC,OACA,KACA,MACA,OAEA,YAAY,EAAgB,EAAc,EAA6C,CAAC,EAAG,CACvF,MAAMC,CAAI,EACV,KAAK,KAAO,cACZ,KAAK,OAASC,EACd,KAAK,KAAOD,EACRE,EAAM,QAAO,KAAK,MAAQA,EAAM,OAChCA,EAAM,SAAQ,KAAK,OAASA,EAAM,OAC1C,CACJ,EAGaC,EAAiB,GAC1BC,EAAM,OAAS,SAAWA,EAAM,QAAQ,WAAW,YAAY,EAAIA,EAAM,QAAQ,MAAM,EAAmB,EAAI,IAAA,GAgBrGC,EAAb,MAAaA,CAAa,CACtB,QAEA,YAAY,EAA8B,CACtC,KAAK,QAAU,CAAE,GAAGC,EAAS,IAAKA,EAAQ,IAAI,QAAQ,OAAQ,EAAE,CAAE,CACtE,CAGA,GAAG,EAAyD,CACxD,OAAO,IAAID,EAAa,CAAE,GAAG,KAAK,QAAS,GAAGE,CAAM,CAAC,CACzD,CAEA,MAAc,QAAQ,EAAgD,CAClE,GAAM,CAAE,MAAK,SAAQ,OAAM,WAAY,KAAK,QAC5C,MAAO,CACH,GAAIC,EAAO,CAAE,eAAgB,kBAAmB,EAAI,CAAC,EACrD,GAAIC,EAAM,CAAE,cAAe,UAAUA,GAAM,EAAI,CAAC,EAChD,GAAIC,EAAS,C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EjJ,GADI,CAACD,EAAc,KAAKvB,CAAI,GACxB,CAAC,CAAC,MAAO,OAAQ,MAAO,QAAQ,CAAC,CAAC,SAASU,EAAQ,MAAM,EAAG,OAAO,IAAI,SAAS,KAAK,UAAU,CAAE,MAAO,WAAY,CAAC,EAAG,CAAE,OAAQ,IAAK,QAAS,CAAE,eAAgB,kBAAmB,CAAE,CAAC,EAC5L,IAAMZ,EAAkC,CACpC,cAAe,UAAU2B,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,IAAMzB,EAAOS,EAAQ,SAAW,OAASA,EAAQ,SAAW,SAAW,IAAA,GAAY,MAAMA,EAAQ,YAAY,EACvGiB,EAAM,IAAI,IAAIjB,EAAQ,GAAG,EACzBK,EAAS,MAAMa,EAAU,GAAGH,EAAO,IAAI,QAAQ,OAAQ,EAAE,IAAIzB,IAAO2B,EAAI,SAAU,CACpF,OAAQjB,EAAQ,OAChB,UACA,GAAIT,EAAO,CAAE,MAAK,EAAI,CAAC,EACvB,OAAQS,EAAQ,MACpB,CAAC,EACD,OAAO,IAAI,SAASK,EAAO,KAAM,CAC7B,OAAQA,EAAO,OACf,QAAS,CACL,eAAgBA,EAAO,QAAQ,IAAI,cAAc,GAAK,mBACtD,gBAAiB,WACjB,oBAAqB,IACzB,CACJ,CAAC,CACL,C"}
package/dist/client.mjs CHANGED
@@ -55,12 +55,24 @@ var e = class extends Error {
55
55
  ...t ? { name: t } : {}
56
56
  });
57
57
  }
58
+ requestPairing(e) {
59
+ return this.request("POST", "/v1/pair/requests", { name: e });
60
+ }
61
+ pollPairing(e) {
62
+ return this.request("POST", "/v1/pair/requests/poll", { request: e });
63
+ }
58
64
  info() {
59
65
  return this.request("GET", "/v1/info");
60
66
  }
61
67
  createPairing() {
62
68
  return this.request("POST", "/v1/admin/pairing");
63
69
  }
70
+ async pairingRequests() {
71
+ return (await this.request("GET", "/v1/admin/pairing/requests")).requests;
72
+ }
73
+ async answerPairing(e, t) {
74
+ return (await this.request("POST", `/v1/admin/pairing/requests/${encodeURIComponent(e)}/${t ? "approve" : "deny"}`)).request;
75
+ }
64
76
  platform = {
65
77
  status: () => this.request("GET", "/v1/platform/status"),
66
78
  tenants: async () => (await this.request("GET", "/v1/platform/tenants")).tenants,
@@ -1 +1 @@
1
- {"version":3,"file":"client.mjs","names":["RunnerError","code","status","extra","noCreditUntil","event","RunnerClient","options","scope","json","key","tenant","user","headers","response","path","body","text","data","name","id","input","label","provider","request","tools","message","signal","callId","answer","reader","decoder","buffer","value","done","lines","line","PERSON_ROUTES","forwardToRunner","target","type","url","fetchImpl"],"sources":["../src/client/index.ts"],"sourcesContent":["// @llmnative/runner/client — the client of the API v1 of the LLMNative Runner, for the browser and for Node.\n//\n// A key never belongs in the browser of the people of a tenant: a host app talks to the runner from its backend\n// (`createRunnerProxy` forwards the requests of its signed-in people, adding the key, the tenant and the person),\n// and its pages use `RunnerClient` against that backend. The console of the runner and a personal app with a key of\n// its own use `RunnerClient` directly.\n\nexport type RunnerProvider = 'claude-code' | 'opencode-go' | 'opencode';\nexport type RunnerPermission = 'complete' | 'chat' | 'chat:tools' | 'accounts' | 'accounts:tenant' | 'act-as-user' | 'keys';\n\nexport type RunnerAccount = {\n provider: RunnerProvider;\n id: string;\n label?: string;\n /** When it was connected. */\n at: string;\n scope: 'user' | 'tenant';\n /** Out of credit until then (the limit of a subscription); absent when it has credit. */\n noCreditUntil?: string;\n};\n\nexport type RunnerModels = {\n providers: Array<{ id: 'claude-code' | 'opencode-go'; models: string[]; accounts: number; available: number; yours: number; tenant: number }>;\n};\n\nexport type RunnerTenant = { id: string; name: string; createdAt: string; usersWithAccounts?: number };\nexport type RunnerKey = { id: string; kind: 'platform' | 'project'; tenant?: string; name: string; permissions: RunnerPermission[]; createdAt: string; expiresAt: string | null };\n\nexport type RunnerStatus = {\n version: string;\n agentImage: string;\n url?: string;\n load: { chats: number; answering: number; completions: number; maxChats: number };\n machine: { totalBytes: number; availableBytes: number; cpus: number };\n tenants: RunnerTenant[];\n};\n\nexport type RunnerHealth = { ok: boolean; version: string; chats: number; answering: number; completions: number; maxChats: number };\n\nexport type RunnerCompletionRequest = { provider: 'claude-code' | 'opencode-go'; model: string; prompt: string; effort?: 'low' | 'medium' | 'high' | 'xhigh' | 'max' };\nexport type RunnerCompletion = { text: string; usage?: { inputTokens: number; outputTokens: number } };\n\nexport type RunnerChatTool = { name: string; description: string; inputSchema: Record<string, unknown>; endsTurn?: boolean };\nexport type RunnerChatModel = { provider: string; model: string; variant?: string; name?: string; effort?: string };\nexport type RunnerChatEvent =\n | { type: 'text'; text: string }\n | { type: 'reasoning'; text: string }\n | { type: 'step'; id: string; label: string; status: 'running' | 'done' }\n | { type: 'tool-call'; id: string; name: string; input: Record<string, unknown> }\n | { type: 'done' }\n | { type: 'error'; message: string };\n\n/** An error of the runner: its status and code (`no-credit`, `busy`…), and for `no-credit` until when. */\nexport class RunnerError extends Error {\n readonly status: number;\n readonly code: string;\n readonly until?: string;\n readonly detail?: string;\n\n constructor(status: number, code: string, extra: { until?: string; detail?: string } = {}) {\n super(code);\n this.name = 'RunnerError';\n this.status = status;\n this.code = code;\n if (extra.until) this.until = extra.until;\n if (extra.detail) this.detail = extra.detail;\n }\n}\n\n/** When a chat event says the accounts ran out of credit: until when (`no-credit:<iso>`). */\nexport const noCreditUntil = (event: RunnerChatEvent): string | undefined =>\n event.type === 'error' && event.message.startsWith('no-credit:') ? event.message.slice('no-credit:'.length) : undefined;\n\nexport type RunnerClientOptions = {\n /** The address of the runner (`https://runner.example.com`), or of the backend of the host that forwards to it. */\n url: string;\n /** A key of the runner (or the admin token in the console); none when the backend of the host adds it. */\n key?: string;\n /** With a platform key or the admin token: the tenant the requests are for. */\n tenant?: string;\n /** The person the requests are for (needs `act-as-user` with a project key). */\n user?: string;\n fetch?: typeof fetch;\n /** More headers for each request (the session of the host, for its backend). */\n headers?: () => Record<string, string> | Promise<Record<string, string>>;\n};\n\nexport class RunnerClient {\n readonly options: RunnerClientOptions;\n\n constructor(options: RunnerClientOptions) {\n this.options = { ...options, url: options.url.replace(/\\/+$/, '') };\n }\n\n /** The same runner for another tenant or person. */\n as(scope: { tenant?: string; user?: string }): RunnerClient {\n return new RunnerClient({ ...this.options, ...scope });\n }\n\n private async headers(json: boolean): Promise<Record<string, string>> {\n const { key, tenant, user, headers } = this.options;\n return {\n ...(json ? { 'content-type': 'application/json' } : {}),\n ...(key ? { authorization: `Bearer ${key}` } : {}),\n ...(tenant ? { 'x-runner-tenant': tenant } : {}),\n ...(user ? { 'x-runner-user': user } : {}),\n ...(await headers?.()),\n };\n }\n\n /** One request; its JSON, or a RunnerError. */\n async request<T>(method: string, path: string, body?: unknown): Promise<T> {\n const response = await (this.options.fetch ?? fetch)(`${this.options.url}${path}`, {\n method,\n headers: await this.headers(body !== undefined),\n ...(body !== undefined ? { body: JSON.stringify(body) } : {}),\n });\n const text = await response.text();\n let data: Record<string, unknown> = {};\n try {\n data = text ? JSON.parse(text) as Record<string, unknown> : {};\n } catch {\n // Not JSON (a proxy in between): said by its status.\n }\n if (!response.ok) {\n throw new RunnerError(response.status, typeof data.error === 'string' ? data.error : `http-${response.status}`, {\n ...(typeof data.until === 'string' ? { until: data.until } : {}),\n ...(typeof data.detail === 'string' ? { detail: data.detail } : {}),\n });\n }\n return data as T;\n }\n\n // ── Public ──────────────────────────────────────────────────────────────────────────────────────────────\n health(): Promise<RunnerHealth> {\n return this.request('GET', '/health');\n }\n\n /** A pairing code (printed by the installer) → a platform key, seen once. */\n pair(code: string, name?: string): Promise<{ key: string; record: RunnerKey; version: string }> {\n return this.request('POST', '/v1/pair', { code, ...(name ? { name } : {}) });\n }\n\n info(): Promise<{ version: string; harnesses: string[]; capabilities: Record<string, boolean>; permissions: RunnerPermission[]; tenant?: string }> {\n return this.request('GET', '/v1/info');\n }\n\n // ── Admin token ─────────────────────────────────────────────────────────────────────────────────────────\n createPairing(): Promise<{ code: string; expiresAt: string }> {\n return this.request('POST', '/v1/admin/pairing');\n }\n\n // ── Platform key ────────────────────────────────────────────────────────────────────────────────────────\n readonly platform = {\n status: (): Promise<RunnerStatus> => this.request('GET', '/v1/platform/status'),\n tenants: async (): Promise<RunnerTenant[]> => (await this.request<{ tenants: RunnerTenant[] }>('GET', '/v1/platform/tenants')).tenants,\n /** A tenant, with its first project key unless `key: false` (seen once: keep it in the backend). */\n createTenant: (id: string, options: { name?: string; key?: boolean; keyPermissions?: RunnerPermission[] } = {}): Promise<{ tenant: RunnerTenant; key?: string; keyRecord?: RunnerKey }> =>\n this.request('POST', '/v1/platform/tenants', { id, ...options }),\n removeTenant: async (id: string): Promise<boolean> => (await this.request<{ removed: boolean }>('DELETE', `/v1/platform/tenants/${encodeURIComponent(id)}`)).removed,\n keys: async (tenant: string): Promise<RunnerKey[]> => (await this.request<{ keys: RunnerKey[] }>('GET', `/v1/platform/tenants/${encodeURIComponent(tenant)}/keys`)).keys,\n createKey: (tenant: string, input: { name?: string; permissions?: RunnerPermission[]; expiresAt?: string | null } = {}): Promise<{ key: string; record: RunnerKey }> =>\n this.request('POST', `/v1/platform/tenants/${encodeURIComponent(tenant)}/keys`, input),\n revokeKey: async (tenant: string, id: string): Promise<boolean> => (await this.request<{ removed: boolean }>('DELETE', `/v1/platform/tenants/${encodeURIComponent(tenant)}/keys/${encodeURIComponent(id)}`)).removed,\n platformKeys: async (): Promise<RunnerKey[]> => (await this.request<{ keys: RunnerKey[] }>('GET', '/v1/platform/keys')).keys,\n revokePlatformKey: async (id: string): Promise<boolean> => (await this.request<{ removed: boolean }>('DELETE', `/v1/platform/keys/${encodeURIComponent(id)}`)).removed,\n };\n\n // ── Accounts of the person (or of the tenant) ───────────────────────────────────────────────────────────\n readonly accounts = {\n list: async (): Promise<{ scope: 'user' | 'tenant'; accounts: RunnerAccount[] }> => this.request('GET', '/v1/accounts'),\n /** The sign-in of a Claude subscription: open `url`, then give the code Anthropic shows to `finishClaudeLogin`. */\n startClaudeLogin: (): Promise<{ url: string }> => this.request('POST', '/v1/accounts/claude-code/login'),\n finishClaudeLogin: async (code: string, label?: string): Promise<RunnerAccount> =>\n (await this.request<{ account: RunnerAccount }>('POST', '/v1/accounts/claude-code/login/code', { code, ...(label ? { label } : {}) })).account,\n /** A token made elsewhere with `claude setup-token`. */\n addClaudeToken: async (token: string, label?: string): Promise<RunnerAccount> =>\n (await this.request<{ account: RunnerAccount }>('POST', '/v1/accounts/claude-code', { token, ...(label ? { label } : {}) })).account,\n addKey: async (provider: 'opencode-go' | 'opencode', key: string, label?: string): Promise<RunnerAccount> =>\n (await this.request<{ account: RunnerAccount }>('POST', `/v1/accounts/${provider}`, { key, ...(label ? { label } : {}) })).account,\n remove: async (provider: RunnerProvider, id: string): Promise<boolean> =>\n (await this.request<{ removed: boolean }>('DELETE', `/v1/accounts/${provider}/${encodeURIComponent(id)}`)).removed,\n order: async (provider: RunnerProvider, ids: string[]): Promise<RunnerAccount[]> =>\n (await this.request<{ accounts: RunnerAccount[] }>('PUT', '/v1/accounts/order', { provider, ids })).accounts,\n };\n\n models(): Promise<RunnerModels> {\n return this.request('GET', '/v1/models');\n }\n\n complete(request: RunnerCompletionRequest): Promise<RunnerCompletion> {\n return this.request('POST', '/v1/complete', request);\n }\n\n // ── Chats ───────────────────────────────────────────────────────────────────────────────────────────────\n readonly chats = {\n /** A chat (id: 8 hex characters, chosen by the client), with the tools the harness may call. */\n start: (id: string, tools?: RunnerChatTool[]): Promise<{ id: string }> => this.request('POST', '/v1/chats', { id, ...(tools ? { tools } : {}) }),\n /** A message: its events as they come. Aborting the signal stops the harness. */\n send: (id: string, message: { text: string; model: RunnerChatModel; attachments?: Array<{ name: string; mimeType: string; base64: string }> }, signal?: AbortSignal): AsyncIterable<RunnerChatEvent> =>\n this.stream(`/v1/chats/${encodeURIComponent(id)}/messages`, message, signal),\n answerCall: async (id: string, callId: string, answer: { result?: unknown; isError?: boolean }): Promise<boolean> =>\n (await this.request<{ answered: boolean }>('POST', `/v1/chats/${encodeURIComponent(id)}/calls/${encodeURIComponent(callId)}`, answer)).answered,\n stop: async (id: string): Promise<boolean> => (await this.request<{ stopped: boolean }>('POST', `/v1/chats/${encodeURIComponent(id)}/stop`)).stopped,\n close: async (id: string): Promise<boolean> => (await this.request<{ closed: boolean }>('DELETE', `/v1/chats/${encodeURIComponent(id)}`)).closed,\n };\n\n private async *stream(path: string, body: unknown, signal?: AbortSignal): AsyncIterable<RunnerChatEvent> {\n const response = await (this.options.fetch ?? fetch)(`${this.options.url}${path}`, { method: 'POST', headers: await this.headers(true), body: JSON.stringify(body), ...(signal ? { signal } : {}) });\n if (!response.ok || !response.body) {\n let code = `http-${response.status}`;\n try {\n const data = await response.json() as { error?: string };\n if (data.error) code = data.error;\n } catch {\n // Said by its status.\n }\n throw new RunnerError(response.status, code);\n }\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n for (;;) {\n const { done, value } = await reader.read();\n buffer += decoder.decode(value ?? new Uint8Array(), { stream: !done });\n const lines = buffer.split('\\n');\n buffer = done ? '' : lines.pop() ?? '';\n for (const line of lines) {\n if (!line.trim()) continue;\n let event: RunnerChatEvent | { type: 'ping' };\n try {\n event = JSON.parse(line) as RunnerChatEvent | { type: 'ping' };\n } catch {\n continue;\n }\n if (event.type !== 'ping') yield event;\n }\n if (done) return;\n }\n }\n}\n\n// ── For the backend of a host ───────────────────────────────────────────────────────────────────────────────\n\n/** The routes the people of a tenant may reach through the backend of the host: never the platform ones. */\nconst PERSON_ROUTES = /^\\/v1\\/(info|models|complete|accounts(\\/[A-Za-z0-9_.:-]+){0,3}|chats(\\/[a-f0-9]{8}(\\/(messages|stop|calls\\/[a-f0-9]{12}))?)?)$/;\n\nexport type RunnerProxyTarget = {\n /** The address of the runner of this tenant. */\n url: string;\n /** A project key of the tenant (with `act-as-user`), or a platform key with `tenant`. */\n key: string;\n tenant?: string;\n /** The signed-in person, verified by the host. */\n user: string;\n};\n\n/**\n * Forwards a request of a signed-in person to their runner: only the routes of a person, with the key, tenant and\n * person added by the host (whatever the browser sent for them is dropped). Streams answers (chat replies) as they\n * come. `path` is the path of the runner, e.g. `/v1/models` (the host strips its own prefix).\n */\nexport async function forwardToRunner(request: Request, path: string, target: RunnerProxyTarget, fetchImpl: typeof fetch = fetch): Promise<Response> {\n if (!PERSON_ROUTES.test(path)) return new Response(JSON.stringify({ error: 'not found' }), { status: 404, headers: { 'content-type': 'application/json' } });\n if (!['GET', 'POST', 'PUT', 'DELETE'].includes(request.method)) return new Response(JSON.stringify({ error: 'not found' }), { status: 404, headers: { 'content-type': 'application/json' } });\n const headers: Record<string, string> = {\n authorization: `Bearer ${target.key}`,\n 'x-runner-user': target.user,\n ...(target.tenant ? { 'x-runner-tenant': target.tenant } : {}),\n };\n const type = request.headers.get('content-type');\n if (type) headers['content-type'] = type;\n const body = request.method === 'GET' || request.method === 'DELETE' ? undefined : await request.arrayBuffer();\n const url = new URL(request.url);\n const answer = await fetchImpl(`${target.url.replace(/\\/+$/, '')}${path}${url.search}`, {\n method: request.method,\n headers,\n ...(body ? { body } : {}),\n signal: request.signal,\n });\n return new Response(answer.body, {\n status: answer.status,\n headers: {\n 'content-type': answer.headers.get('content-type') ?? 'application/json',\n 'cache-control': 'no-store',\n 'x-accel-buffering': 'no',\n },\n });\n}\n"],"mappings":";AAqDA,IAAaA,IAAb,cAAiC,MAAM;CACnC;CACA;CACA;CACA;CAEA,YAAY,GAAgB,GAAc,IAA6C,CAAC,GAAG;EAMvF,AALA,MAAMC,CAAI,GACV,KAAK,OAAO,eACZ,KAAK,SAASC,GACd,KAAK,OAAOD,GACRE,EAAM,UAAO,KAAK,QAAQA,EAAM,QAChCA,EAAM,WAAQ,KAAK,SAASA,EAAM;CAC1C;AACJ,GAGaC,KAAiB,MAC1BC,EAAM,SAAS,WAAWA,EAAM,QAAQ,WAAW,YAAY,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AAMA;GACrC;GACA,IAAI6B,GAAM;EACd;CACJ;AACJ,GAKMG,IAAgB;AAiBtB,eAAsBC,EAAgB,GAAkB,GAAc,GAA2B,IAA0B,OAA0B;CAEjJ,IADI,CAACD,EAAc,KAAKtB,CAAI,KACxB,CAAC;EAAC;EAAO;EAAQ;EAAO;CAAQ,CAAC,CAAC,SAASS,EAAQ,MAAM,GAAG,OAAO,IAAI,SAAS,KAAK,UAAU,EAAE,OAAO,YAAY,CAAC,GAAG;EAAE,QAAQ;EAAK,SAAS,EAAE,gBAAgB,mBAAmB;CAAE,CAAC;CAC5L,IAAMX,IAAkC;EACpC,eAAe,UAAU0B,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,IAAMxB,IAAOQ,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,IAAIxB,IAAO0B,EAAI,UAAU;EACpF,QAAQjB,EAAQ;EAChB;EACA,GAAIR,IAAO,EAAE,QAAK,IAAI,CAAC;EACvB,QAAQQ,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":["RunnerError","code","status","extra","noCreditUntil","event","RunnerClient","options","scope","json","key","tenant","user","headers","response","path","body","text","data","name","approve","id","input","label","provider","request","tools","message","signal","callId","answer","reader","decoder","buffer","value","done","lines","line","PERSON_ROUTES","forwardToRunner","target","type","url","fetchImpl"],"sources":["../src/client/index.ts"],"sourcesContent":["// @llmnative/runner/client — the client of the API v1 of the LLMNative Runner, for the browser and for Node.\n//\n// A key never belongs in the browser of the people of a tenant: a host app talks to the runner from its backend\n// (`createRunnerProxy` forwards the requests of its signed-in people, adding the key, the tenant and the person),\n// and its pages use `RunnerClient` against that backend. The console of the runner and a personal app with a key of\n// its own use `RunnerClient` directly.\n\nexport type RunnerProvider = 'claude-code' | 'opencode-go' | 'opencode';\nexport type RunnerPermission = 'complete' | 'chat' | 'chat:tools' | 'accounts' | 'accounts:tenant' | 'act-as-user' | 'keys';\n\nexport type RunnerAccount = {\n provider: RunnerProvider;\n id: string;\n label?: string;\n /** When it was connected. */\n at: string;\n scope: 'user' | 'tenant';\n /** Out of credit until then (the limit of a subscription); absent when it has credit. */\n noCreditUntil?: string;\n};\n\nexport type RunnerModels = {\n providers: Array<{ id: 'claude-code' | 'opencode-go'; models: string[]; accounts: number; available: number; yours: number; tenant: number }>;\n};\n\nexport type RunnerTenant = { id: string; name: string; createdAt: string; usersWithAccounts?: number };\nexport type RunnerKey = { id: string; kind: 'platform' | 'project'; tenant?: string; name: string; permissions: RunnerPermission[]; createdAt: string; expiresAt: string | null };\n\nexport type RunnerStatus = {\n version: string;\n agentImage: string;\n url?: string;\n load: { chats: number; answering: number; completions: number; maxChats: number };\n machine: { totalBytes: number; availableBytes: number; cpus: number };\n tenants: RunnerTenant[];\n};\n\n/** A pairing request made by a platform: `request` is its secret (keep it in the backend), `code` is shown on both sides. */\nexport type RunnerPairingRequest = { request: string; code: string; approveUrl: string; expiresAt: string; interval: number };\nexport type RunnerPairingPoll = { status: 'pending' | 'denied' | 'expired' } | { status: 'approved'; key: string; record: RunnerKey; version: string };\nexport type RunnerPairingRequestView = { code: string; name: string; from?: string; createdAt: string; expiresAt: string };\nexport type RunnerHealth = { ok: boolean; version: string; chats: number; answering: number; completions: number; maxChats: number };\n\nexport type RunnerCompletionRequest = { provider: 'claude-code' | 'opencode-go'; model: string; prompt: string; effort?: 'low' | 'medium' | 'high' | 'xhigh' | 'max' };\nexport type RunnerCompletion = { text: string; usage?: { inputTokens: number; outputTokens: number } };\n\nexport type RunnerChatTool = { name: string; description: string; inputSchema: Record<string, unknown>; endsTurn?: boolean };\nexport type RunnerChatModel = { provider: string; model: string; variant?: string; name?: string; effort?: string };\nexport type RunnerChatEvent =\n | { type: 'text'; text: string }\n | { type: 'reasoning'; text: string }\n | { type: 'step'; id: string; label: string; status: 'running' | 'done' }\n | { type: 'tool-call'; id: string; name: string; input: Record<string, unknown> }\n | { type: 'done' }\n | { type: 'error'; message: string };\n\n/** An error of the runner: its status and code (`no-credit`, `busy`…), and for `no-credit` until when. */\nexport class RunnerError extends Error {\n readonly status: number;\n readonly code: string;\n readonly until?: string;\n readonly detail?: string;\n\n constructor(status: number, code: string, extra: { until?: string; detail?: string } = {}) {\n super(code);\n this.name = 'RunnerError';\n this.status = status;\n this.code = code;\n if (extra.until) this.until = extra.until;\n if (extra.detail) this.detail = extra.detail;\n }\n}\n\n/** When a chat event says the accounts ran out of credit: until when (`no-credit:<iso>`). */\nexport const noCreditUntil = (event: RunnerChatEvent): string | undefined =>\n event.type === 'error' && event.message.startsWith('no-credit:') ? event.message.slice('no-credit:'.length) : undefined;\n\nexport type RunnerClientOptions = {\n /** The address of the runner (`https://runner.example.com`), or of the backend of the host that forwards to it. */\n url: string;\n /** A key of the runner (or the admin token in the console); none when the backend of the host adds it. */\n key?: string;\n /** With a platform key or the admin token: the tenant the requests are for. */\n tenant?: string;\n /** The person the requests are for (needs `act-as-user` with a project key). */\n user?: string;\n fetch?: typeof fetch;\n /** More headers for each request (the session of the host, for its backend). */\n headers?: () => Record<string, string> | Promise<Record<string, string>>;\n};\n\nexport class RunnerClient {\n readonly options: RunnerClientOptions;\n\n constructor(options: RunnerClientOptions) {\n this.options = { ...options, url: options.url.replace(/\\/+$/, '') };\n }\n\n /** The same runner for another tenant or person. */\n as(scope: { tenant?: string; user?: string }): RunnerClient {\n return new RunnerClient({ ...this.options, ...scope });\n }\n\n private async headers(json: boolean): Promise<Record<string, string>> {\n const { key, tenant, user, headers } = this.options;\n return {\n ...(json ? { 'content-type': 'application/json' } : {}),\n ...(key ? { authorization: `Bearer ${key}` } : {}),\n ...(tenant ? { 'x-runner-tenant': tenant } : {}),\n ...(user ? { 'x-runner-user': user } : {}),\n ...(await headers?.()),\n };\n }\n\n /** One request; its JSON, or a RunnerError. */\n async request<T>(method: string, path: string, body?: unknown): Promise<T> {\n const response = await (this.options.fetch ?? fetch)(`${this.options.url}${path}`, {\n method,\n headers: await this.headers(body !== undefined),\n ...(body !== undefined ? { body: JSON.stringify(body) } : {}),\n });\n const text = await response.text();\n let data: Record<string, unknown> = {};\n try {\n data = text ? JSON.parse(text) as Record<string, unknown> : {};\n } catch {\n // Not JSON (a proxy in between): said by its status.\n }\n if (!response.ok) {\n throw new RunnerError(response.status, typeof data.error === 'string' ? data.error : `http-${response.status}`, {\n ...(typeof data.until === 'string' ? { until: data.until } : {}),\n ...(typeof data.detail === 'string' ? { detail: data.detail } : {}),\n });\n }\n return data as T;\n }\n\n // ── Public ──────────────────────────────────────────────────────────────────────────────────────────────\n health(): Promise<RunnerHealth> {\n return this.request('GET', '/health');\n }\n\n /** A pairing code (printed by the installer) → a platform key, seen once. */\n pair(code: string, name?: string): Promise<{ key: string; record: RunnerKey; version: string }> {\n return this.request('POST', '/v1/pair', { code, ...(name ? { name } : {}) });\n }\n\n /**\n * Asks to connect (device flow): the admin of the runner approves it in the console at `approveUrl`, where the\n * same `code` is shown; meanwhile `pollPairing(request)` every `interval` seconds, until it gives the key.\n */\n requestPairing(name: string): Promise<RunnerPairingRequest> {\n return this.request('POST', '/v1/pair/requests', { name });\n }\n\n pollPairing(request: string): Promise<RunnerPairingPoll> {\n return this.request('POST', '/v1/pair/requests/poll', { request });\n }\n\n info(): Promise<{ version: string; harnesses: string[]; capabilities: Record<string, boolean>; permissions: RunnerPermission[]; tenant?: string }> {\n return this.request('GET', '/v1/info');\n }\n\n // ── Admin token ─────────────────────────────────────────────────────────────────────────────────────────\n createPairing(): Promise<{ code: string; expiresAt: string }> {\n return this.request('POST', '/v1/admin/pairing');\n }\n\n async pairingRequests(): Promise<RunnerPairingRequestView[]> {\n return (await this.request<{ requests: RunnerPairingRequestView[] }>('GET', '/v1/admin/pairing/requests')).requests;\n }\n\n async answerPairing(code: string, approve: boolean): Promise<RunnerPairingRequestView> {\n return (await this.request<{ request: RunnerPairingRequestView }>('POST', `/v1/admin/pairing/requests/${encodeURIComponent(code)}/${approve ? 'approve' : 'deny'}`)).request;\n }\n\n // ── Platform key ────────────────────────────────────────────────────────────────────────────────────────\n readonly platform = {\n status: (): Promise<RunnerStatus> => this.request('GET', '/v1/platform/status'),\n tenants: async (): Promise<RunnerTenant[]> => (await this.request<{ tenants: RunnerTenant[] }>('GET', '/v1/platform/tenants')).tenants,\n /** A tenant, with its first project key unless `key: false` (seen once: keep it in the backend). */\n createTenant: (id: string, options: { name?: string; key?: boolean; keyPermissions?: RunnerPermission[] } = {}): Promise<{ tenant: RunnerTenant; key?: string; keyRecord?: RunnerKey }> =>\n this.request('POST', '/v1/platform/tenants', { id, ...options }),\n removeTenant: async (id: string): Promise<boolean> => (await this.request<{ removed: boolean }>('DELETE', `/v1/platform/tenants/${encodeURIComponent(id)}`)).removed,\n keys: async (tenant: string): Promise<RunnerKey[]> => (await this.request<{ keys: RunnerKey[] }>('GET', `/v1/platform/tenants/${encodeURIComponent(tenant)}/keys`)).keys,\n createKey: (tenant: string, input: { name?: string; permissions?: RunnerPermission[]; expiresAt?: string | null } = {}): Promise<{ key: string; record: RunnerKey }> =>\n this.request('POST', `/v1/platform/tenants/${encodeURIComponent(tenant)}/keys`, input),\n revokeKey: async (tenant: string, id: string): Promise<boolean> => (await this.request<{ removed: boolean }>('DELETE', `/v1/platform/tenants/${encodeURIComponent(tenant)}/keys/${encodeURIComponent(id)}`)).removed,\n platformKeys: async (): Promise<RunnerKey[]> => (await this.request<{ keys: RunnerKey[] }>('GET', '/v1/platform/keys')).keys,\n revokePlatformKey: async (id: string): Promise<boolean> => (await this.request<{ removed: boolean }>('DELETE', `/v1/platform/keys/${encodeURIComponent(id)}`)).removed,\n };\n\n // ── Accounts of the person (or of the tenant) ───────────────────────────────────────────────────────────\n readonly accounts = {\n list: async (): Promise<{ scope: 'user' | 'tenant'; accounts: RunnerAccount[] }> => this.request('GET', '/v1/accounts'),\n /** The sign-in of a Claude subscription: open `url`, then give the code Anthropic shows to `finishClaudeLogin`. */\n startClaudeLogin: (): Promise<{ url: string }> => this.request('POST', '/v1/accounts/claude-code/login'),\n finishClaudeLogin: async (code: string, label?: string): Promise<RunnerAccount> =>\n (await this.request<{ account: RunnerAccount }>('POST', '/v1/accounts/claude-code/login/code', { code, ...(label ? { label } : {}) })).account,\n /** A token made elsewhere with `claude setup-token`. */\n addClaudeToken: async (token: string, label?: string): Promise<RunnerAccount> =>\n (await this.request<{ account: RunnerAccount }>('POST', '/v1/accounts/claude-code', { token, ...(label ? { label } : {}) })).account,\n addKey: async (provider: 'opencode-go' | 'opencode', key: string, label?: string): Promise<RunnerAccount> =>\n (await this.request<{ account: RunnerAccount }>('POST', `/v1/accounts/${provider}`, { key, ...(label ? { label } : {}) })).account,\n remove: async (provider: RunnerProvider, id: string): Promise<boolean> =>\n (await this.request<{ removed: boolean }>('DELETE', `/v1/accounts/${provider}/${encodeURIComponent(id)}`)).removed,\n order: async (provider: RunnerProvider, ids: string[]): Promise<RunnerAccount[]> =>\n (await this.request<{ accounts: RunnerAccount[] }>('PUT', '/v1/accounts/order', { provider, ids })).accounts,\n };\n\n models(): Promise<RunnerModels> {\n return this.request('GET', '/v1/models');\n }\n\n complete(request: RunnerCompletionRequest): Promise<RunnerCompletion> {\n return this.request('POST', '/v1/complete', request);\n }\n\n // ── Chats ───────────────────────────────────────────────────────────────────────────────────────────────\n readonly chats = {\n /** A chat (id: 8 hex characters, chosen by the client), with the tools the harness may call. */\n start: (id: string, tools?: RunnerChatTool[]): Promise<{ id: string }> => this.request('POST', '/v1/chats', { id, ...(tools ? { tools } : {}) }),\n /** A message: its events as they come. Aborting the signal stops the harness. */\n send: (id: string, message: { text: string; model: RunnerChatModel; attachments?: Array<{ name: string; mimeType: string; base64: string }> }, signal?: AbortSignal): AsyncIterable<RunnerChatEvent> =>\n this.stream(`/v1/chats/${encodeURIComponent(id)}/messages`, message, signal),\n answerCall: async (id: string, callId: string, answer: { result?: unknown; isError?: boolean }): Promise<boolean> =>\n (await this.request<{ answered: boolean }>('POST', `/v1/chats/${encodeURIComponent(id)}/calls/${encodeURIComponent(callId)}`, answer)).answered,\n stop: async (id: string): Promise<boolean> => (await this.request<{ stopped: boolean }>('POST', `/v1/chats/${encodeURIComponent(id)}/stop`)).stopped,\n close: async (id: string): Promise<boolean> => (await this.request<{ closed: boolean }>('DELETE', `/v1/chats/${encodeURIComponent(id)}`)).closed,\n };\n\n private async *stream(path: string, body: unknown, signal?: AbortSignal): AsyncIterable<RunnerChatEvent> {\n const response = await (this.options.fetch ?? fetch)(`${this.options.url}${path}`, { method: 'POST', headers: await this.headers(true), body: JSON.stringify(body), ...(signal ? { signal } : {}) });\n if (!response.ok || !response.body) {\n let code = `http-${response.status}`;\n try {\n const data = await response.json() as { error?: string };\n if (data.error) code = data.error;\n } catch {\n // Said by its status.\n }\n throw new RunnerError(response.status, code);\n }\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n for (;;) {\n const { done, value } = await reader.read();\n buffer += decoder.decode(value ?? new Uint8Array(), { stream: !done });\n const lines = buffer.split('\\n');\n buffer = done ? '' : lines.pop() ?? '';\n for (const line of lines) {\n if (!line.trim()) continue;\n let event: RunnerChatEvent | { type: 'ping' };\n try {\n event = JSON.parse(line) as RunnerChatEvent | { type: 'ping' };\n } catch {\n continue;\n }\n if (event.type !== 'ping') yield event;\n }\n if (done) return;\n }\n }\n}\n\n// ── For the backend of a host ───────────────────────────────────────────────────────────────────────────────\n\n/** The routes the people of a tenant may reach through the backend of the host: never the platform ones. */\nconst PERSON_ROUTES = /^\\/v1\\/(info|models|complete|accounts(\\/[A-Za-z0-9_.:-]+){0,3}|chats(\\/[a-f0-9]{8}(\\/(messages|stop|calls\\/[a-f0-9]{12}))?)?)$/;\n\nexport type RunnerProxyTarget = {\n /** The address of the runner of this tenant. */\n url: string;\n /** A project key of the tenant (with `act-as-user`), or a platform key with `tenant`. */\n key: string;\n tenant?: string;\n /** The signed-in person, verified by the host. */\n user: string;\n};\n\n/**\n * Forwards a request of a signed-in person to their runner: only the routes of a person, with the key, tenant and\n * person added by the host (whatever the browser sent for them is dropped). Streams answers (chat replies) as they\n * come. `path` is the path of the runner, e.g. `/v1/models` (the host strips its own prefix).\n */\nexport async function forwardToRunner(request: Request, path: string, target: RunnerProxyTarget, fetchImpl: typeof fetch = fetch): Promise<Response> {\n if (!PERSON_ROUTES.test(path)) return new Response(JSON.stringify({ error: 'not found' }), { status: 404, headers: { 'content-type': 'application/json' } });\n if (!['GET', 'POST', 'PUT', 'DELETE'].includes(request.method)) return new Response(JSON.stringify({ error: 'not found' }), { status: 404, headers: { 'content-type': 'application/json' } });\n const headers: Record<string, string> = {\n authorization: `Bearer ${target.key}`,\n 'x-runner-user': target.user,\n ...(target.tenant ? { 'x-runner-tenant': target.tenant } : {}),\n };\n const type = request.headers.get('content-type');\n if (type) headers['content-type'] = type;\n const body = request.method === 'GET' || request.method === 'DELETE' ? undefined : await request.arrayBuffer();\n const url = new URL(request.url);\n const answer = await fetchImpl(`${target.url.replace(/\\/+$/, '')}${path}${url.search}`, {\n method: request.method,\n headers,\n ...(body ? { body } : {}),\n signal: request.signal,\n });\n return new Response(answer.body, {\n status: answer.status,\n headers: {\n 'content-type': answer.headers.get('content-type') ?? 'application/json',\n 'cache-control': 'no-store',\n 'x-accel-buffering': 'no',\n },\n });\n}\n"],"mappings":";AAyDA,IAAaA,IAAb,cAAiC,MAAM;CACnC;CACA;CAC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