@llmnative/runner 1.1.1 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -5,7 +5,7 @@
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
6
  <meta name="robots" content="noindex" />
7
7
  <title>Runner setup</title>
8
- <script type="module" crossorigin src="./assets/index-NBwNtvQf.js"></script>
8
+ <script type="module" crossorigin src="./assets/index-Ce40a4eE.js"></script>
9
9
  <link rel="modulepreload" crossorigin href="./assets/rolldown-runtime-XKyaHtl9.js">
10
10
  <link rel="stylesheet" crossorigin href="./assets/index-CmPc3Q2I.css">
11
11
  </head>
package/dist/setup.js CHANGED
@@ -1,3 +1,3 @@
1
1
  Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./client.js"),t=require("./steps.js");let n=require("ssh2");var r=class extends Error{code;output;constructor(e,t,n=``){super(t),this.name=`InstallError`,this.code=e,this.output=n}};function i(e){let n=e.root?`sh`:`sudo -n sh`;return`curl -fsSL ${t.installScriptUrl(e.version)} | ${n} -s -- ${t.installArguments(e).join(` `)}`}function a(e,a){return new Promise((o,s)=>{let c=new n.Client,l=``,u=``,d=!1,f=(e,t)=>{d||(d=!0,clearTimeout(p),c.end(),e?s(e):o(t))},p=setTimeout(()=>f(new r(`timeout`,`the installation took too long`,u)),a.timeoutMs??12e5),m={host:e.host,port:e.port??22,username:e.username,readyTimeout:3e4,...e.privateKey?{privateKey:e.privateKey,...e.passphrase?{passphrase:e.passphrase}:{}}:{},...e.password?{password:e.password}:{},hostHash:`sha256`,hostVerifier:t=>(l=`SHA256:${Buffer.from(t,`hex`).toString(`base64`).replace(/=+$/,``)}`,!e.hostFingerprint||e.hostFingerprint===l)};c.on(`error`,e=>{let t=/authentication/i.test(e.message)?`ssh-auth`:/verif/i.test(e.message)?`ssh-host-key`:`ssh-connect`;f(new r(t,e.message,u))}),c.on(`ready`,()=>{let n=e.username===`root`;c.exec(i({...a,root:n}),(e,i)=>{if(e)return f(new r(`ssh-exec`,e.message,u));let o=``,s=e=>{let n=e.toString(`utf8`);u=(u+n).slice(-2e5),o+=n;let r=o.split(`
2
- `);o=r.pop()??``;for(let e of r){let n=e.replace(/^(PAIRING_CODE=).+$/,`$1…`).replace(/(Pairing code:\s+)\S+/,`$1…`);a.onProgress?.({line:n,...t.phaseOf(e)?{phase:t.phaseOf(e)}:{}})}};i.on(`data`,s),i.stderr.on(`data`,s),i.on(`close`,e=>{let i=t.parseInstallOutput(u);if(e===0&&i.url&&i.pairingCode)return f(void 0,{url:i.url,pairingCode:i.pairingCode,hostFingerprint:l});if(!n&&/sudo: a password is required|sudo: a terminal is required/.test(u))return f(new r(`sudo`,`the user needs sudo without a password, or connect as root`,u));f(new r(i.error??`install`,`the installer ended with ${e??`no code`}`,u))})})}),c.connect(m)})}async function o(t,n){let r=await a(t,n),i=await new e.RunnerClient({url:r.url,...n.fetch?{fetch:n.fetch}:{}}).pair(r.pairingCode,n.name);return{url:r.url,hostFingerprint:r.hostFingerprint,platformKey:i.key,version:i.version}}var s=(e,t)=>{let n=e.replace(/[.+^${}()|[\]\\]/g,e=>`\\${e}`).replace(/\*/g,`.*`).replace(/\?/g,`.`);return RegExp(`^${n}$`,`i`).test(t)};function c(e,t){let n=!0,r,i=[];for(let a of e.split(/\r?\n/)){let e=a.trim();if(!e||e.startsWith(`#`))continue;let[o,...c]=e.split(/\s+/),l=c.join(` `).replace(/^"(.*)"$/,`$1`),u=o.toLowerCase();if(u===`host`){let e=c;n=e.some(e=>!e.startsWith(`!`)&&s(e,t))&&!e.some(e=>e.startsWith(`!`)&&s(e.slice(1),t))}else u===`match`?n=!1:n&&u===`user`&&r===void 0?r=l:n&&u===`identityfile`&&i.push(l)}return{...r?{user:r}:{},identityFiles:i}}exports.DOMAIN_PATTERN=t.DOMAIN_PATTERN,exports.GUIDE_STEPS=t.GUIDE_STEPS,exports.INSTALL_PHASES=t.INSTALL_PHASES,exports.InstallError=r,exports.RUNNER_REPOSITORY=t.RUNNER_REPOSITORY,exports.RUNNER_REQUIREMENTS=t.RUNNER_REQUIREMENTS,exports.RUNNER_VERSION=t.RUNNER_VERSION,exports.checkRunner=t.checkRunner,exports.checksumUrl=t.checksumUrl,exports.installAndPair=o,exports.installArguments=t.installArguments,exports.installCommand=t.installCommand,exports.installOverSsh=a,exports.installScriptUrl=t.installScriptUrl,exports.isDomain=t.isDomain,exports.lookupDomain=t.lookupDomain,exports.parseInstallOutput=t.parseInstallOutput,exports.phaseOf=t.phaseOf,exports.remoteInstallCommand=i,exports.sshConfigFor=c,exports.verifiedInstallCommands=t.verifiedInstallCommands;
2
+ `);o=r.pop()??``;for(let e of r){let n=e.replace(/^(PAIRING_CODE=).+$/,`$1…`).replace(/(Pairing code:\s+)\S+/,`$1…`);a.onProgress?.({line:n,...t.phaseOf(e)?{phase:t.phaseOf(e)}:{}})}};i.on(`data`,s),i.stderr.on(`data`,s),i.on(`close`,e=>{let i=t.parseInstallOutput(u);if(e===0&&i.url&&i.pairingCode)return f(void 0,{url:i.url,pairingCode:i.pairingCode,hostFingerprint:l});if(!n&&/sudo: a password is required|sudo: a terminal is required/.test(u))return f(new r(`sudo`,`the user needs sudo without a password, or connect as root`,u));f(new r(i.error??`install`,`the installer ended with ${e??`no code`}`,u))})})}),c.connect(m)})}async function o(t,n){let r=await a(t,n),i=await new e.RunnerClient({url:r.url,...n.fetch?{fetch:n.fetch}:{}}).pair(r.pairingCode,n.name,n.project);return{url:r.url,hostFingerprint:r.hostFingerprint,platformKey:i.key,version:i.version}}var s=(e,t)=>{let n=e.replace(/[.+^${}()|[\]\\]/g,e=>`\\${e}`).replace(/\*/g,`.*`).replace(/\?/g,`.`);return RegExp(`^${n}$`,`i`).test(t)};function c(e,t){let n=!0,r,i=[];for(let a of e.split(/\r?\n/)){let e=a.trim();if(!e||e.startsWith(`#`))continue;let[o,...c]=e.split(/\s+/),l=c.join(` `).replace(/^"(.*)"$/,`$1`),u=o.toLowerCase();if(u===`host`){let e=c;n=e.some(e=>!e.startsWith(`!`)&&s(e,t))&&!e.some(e=>e.startsWith(`!`)&&s(e.slice(1),t))}else u===`match`?n=!1:n&&u===`user`&&r===void 0?r=l:n&&u===`identityfile`&&i.push(l)}return{...r?{user:r}:{},identityFiles:i}}exports.DOMAIN_PATTERN=t.DOMAIN_PATTERN,exports.GUIDE_STEPS=t.GUIDE_STEPS,exports.INSTALL_PHASES=t.INSTALL_PHASES,exports.InstallError=r,exports.RUNNER_REPOSITORY=t.RUNNER_REPOSITORY,exports.RUNNER_REQUIREMENTS=t.RUNNER_REQUIREMENTS,exports.RUNNER_VERSION=t.RUNNER_VERSION,exports.checkRunner=t.checkRunner,exports.checksumUrl=t.checksumUrl,exports.installAndPair=o,exports.installArguments=t.installArguments,exports.installCommand=t.installCommand,exports.installOverSsh=a,exports.installScriptUrl=t.installScriptUrl,exports.isDomain=t.isDomain,exports.lookupDomain=t.lookupDomain,exports.parseInstallOutput=t.parseInstallOutput,exports.phaseOf=t.phaseOf,exports.remoteInstallCommand=i,exports.sshConfigFor=c,exports.verifiedInstallCommands=t.verifiedInstallCommands;
3
3
  //# sourceMappingURL=setup.js.map
package/dist/setup.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"setup.js","names":["installScriptUrl","installArguments","Client","phaseOf","parseInstallOutput","RunnerClient","require_client","require_steps","ssh2","InstallError","message","code","output","remoteInstallCommand","run","options","installOverSsh","connection","fingerprint","settled","finish","timer","error","reject","resolve","result","config","target","hash","root","pending","read","text","chunk","lines","line","shown","stream","parsed","installAndPair","installed","paired","hostMatches","escaped","pattern","char","host","sshConfigFor","applies","user","identityFiles","raw","configText","keyword","rest","value","name","patterns"],"sources":["../src/setup/index.ts"],"sourcesContent":["// @llmnative/runner/setup — installs a runner on a VPS over SSH, for Node: the command line\n// (`npx @llmnative/runner install`) and the backend of a host (a Cloud Function, the server of a studio). It runs the\n// same install.sh a person pastes by hand (steps.ts), streams what it prints, and reads the address and the pairing\n// code at its end. The SSH credentials are used for this connection only and never kept.\n\nimport { Client, type ConnectConfig } from 'ssh2';\nimport { RunnerClient } from '../client';\nimport { installArguments, installScriptUrl, parseInstallOutput, phaseOf, type InstallOptions, type InstallPhase } from './steps';\n\nexport * from './steps';\n\nexport type SshTarget = {\n host: string;\n port?: number;\n username: string;\n /** A private key (PEM/OpenSSH), or a password. */\n privateKey?: string;\n passphrase?: string;\n password?: string;\n /**\n * The fingerprint the server must have (`SHA256:…`, as `ssh-keygen -lf` prints it); none: the first one is taken\n * and given back in the result, to be kept for the next time.\n */\n hostFingerprint?: string;\n};\n\nexport type InstallProgress = { line: string; phase?: InstallPhase };\n\nexport type InstallResult = { url: string; pairingCode: string; hostFingerprint: string };\n\nexport class InstallError extends Error {\n readonly code: string;\n readonly output: string;\n\n constructor(code: string, message: string, output = '') {\n super(message);\n this.name = 'InstallError';\n this.code = code;\n this.output = output;\n }\n}\n\n/** The command run on the VPS: the script of the release, with sudo unless the user is root. */\nexport function remoteInstallCommand(options: InstallOptions & { root: boolean }): string {\n const run = options.root ? 'sh' : 'sudo -n sh';\n return `curl -fsSL ${installScriptUrl(options.version)} | ${run} -s -- ${installArguments(options).join(' ')}`;\n}\n\n/** Installs a runner over SSH; `onProgress` gets every line it prints (and the phase when one starts). */\nexport function installOverSsh(target: SshTarget, options: InstallOptions & { onProgress?: (progress: InstallProgress) => void; timeoutMs?: number }): Promise<InstallResult> {\n return new Promise((resolve, reject) => {\n const connection = new Client();\n let fingerprint = '';\n let output = '';\n let settled = false;\n const finish = (error?: InstallError, result?: InstallResult) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n connection.end();\n if (error) reject(error);\n else resolve(result!);\n };\n const timer = setTimeout(() => finish(new InstallError('timeout', 'the installation took too long', output)), options.timeoutMs ?? 20 * 60_000);\n const config: ConnectConfig = {\n host: target.host,\n port: target.port ?? 22,\n username: target.username,\n readyTimeout: 30_000,\n ...(target.privateKey ? { privateKey: target.privateKey, ...(target.passphrase ? { passphrase: target.passphrase } : {}) } : {}),\n ...(target.password ? { password: target.password } : {}),\n hostHash: 'sha256',\n hostVerifier: (hash: string) => {\n // ssh2 gives the hash in hex: shown as OpenSSH does (SHA256:<base64>).\n fingerprint = `SHA256:${Buffer.from(hash, 'hex').toString('base64').replace(/=+$/, '')}`;\n return !target.hostFingerprint || target.hostFingerprint === fingerprint;\n },\n };\n connection.on('error', (error: Error & { level?: string }) => {\n const code = /authentication/i.test(error.message) ? 'ssh-auth' : /verif/i.test(error.message) ? 'ssh-host-key' : 'ssh-connect';\n finish(new InstallError(code, error.message, output));\n });\n connection.on('ready', () => {\n const root = target.username === 'root';\n connection.exec(remoteInstallCommand({ ...options, root }), (error, stream) => {\n if (error) return finish(new InstallError('ssh-exec', error.message, output));\n let pending = '';\n const read = (chunk: Buffer) => {\n const text = chunk.toString('utf8');\n output = (output + text).slice(-200_000);\n pending += text;\n const lines = pending.split('\\n');\n pending = lines.pop() ?? '';\n for (const line of lines) {\n // The pairing code is for the result, not for a log that may be kept.\n const shown = line.replace(/^(PAIRING_CODE=).+$/, '$1…').replace(/(Pairing code:\\s+)\\S+/, '$1…');\n options.onProgress?.({ line: shown, ...(phaseOf(line) ? { phase: phaseOf(line) } : {}) });\n }\n };\n stream.on('data', read);\n stream.stderr.on('data', read);\n stream.on('close', (code: number | null) => {\n const parsed = parseInstallOutput(output);\n if (code === 0 && parsed.url && parsed.pairingCode) return finish(undefined, { url: parsed.url, pairingCode: parsed.pairingCode, hostFingerprint: fingerprint });\n if (!root && /sudo: a password is required|sudo: a terminal is required/.test(output)) return finish(new InstallError('sudo', 'the user needs sudo without a password, or connect as root', output));\n finish(new InstallError(parsed.error ?? 'install', `the installer ended with ${code ?? 'no code'}`, output));\n });\n });\n });\n connection.connect(config);\n });\n}\n\n/** Installs and pairs at once: the platform key, seen once, to keep in the backend of the host. */\nexport async function installAndPair(target: SshTarget, options: InstallOptions & { name?: string; onProgress?: (progress: InstallProgress) => void; fetch?: typeof fetch }) {\n const installed = await installOverSsh(target, options);\n const paired = await new RunnerClient({ url: installed.url, ...(options.fetch ? { fetch: options.fetch } : {}) }).pair(installed.pairingCode, options.name);\n return { url: installed.url, hostFingerprint: installed.hostFingerprint, platformKey: paired.key, version: paired.version };\n}\n\n/** A `Host` pattern of ~/.ssh/config (`*` and `?`) against a host name. */\nconst hostMatches = (pattern: string, host: string) => {\n const escaped = pattern.replace(/[.+^${}()|[\\]\\\\]/g, (char) => `\\\\${char}`).replace(/\\*/g, '.*').replace(/\\?/g, '.');\n return new RegExp(`^${escaped}$`, 'i').test(host);\n};\n\n/**\n * What ~/.ssh/config says for a host: its user and its key files, in the order ssh tries them (first match of each\n * option wins, as ssh does). `~` left as is: the caller resolves it.\n */\nexport function sshConfigFor(configText: string, host: string): { user?: string; identityFiles: string[] } {\n let applies = true;\n let user: string | undefined;\n const identityFiles: string[] = [];\n for (const raw of configText.split(/\\r?\\n/)) {\n const line = raw.trim();\n if (!line || line.startsWith('#')) continue;\n const [keyword, ...rest] = line.split(/\\s+/);\n const value = rest.join(' ').replace(/^\"(.*)\"$/, '$1');\n const name = keyword.toLowerCase();\n if (name === 'host') {\n const patterns = rest;\n applies = patterns.some((pattern) => !pattern.startsWith('!') && hostMatches(pattern, host)) && !patterns.some((pattern) => pattern.startsWith('!') && hostMatches(pattern.slice(1), host));\n } else if (name === 'match') applies = false;\n else if (applies && name === 'user' && user === undefined) user = value;\n else if (applies && name === 'identityfile') identityFiles.push(value);\n }\n return { ...(user ? { user } : {}), identityFiles };\n}\n"],"mappings":"A,gJA8BA,IAAaS,EAAb,cAAkC,KAAM,CACpC,KACA,OAEA,YAAY,EAAc,EAAiB,EAAS,GAAI,CACpD,MAAMC,CAAO,EACb,KAAK,KAAO,eACZ,KAAK,KAAOC,EACZ,KAAK,OAASC,CAClB,CACJ,EAGA,SAAgBC,EAAqB,EAAqD,CACtF,IAAMC,EAAMC,EAAQ,KAAO,KAAO,aAClC,MAAO,cAAcf,EAAAA,iBAAiBe,EAAQ,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,EACzDP,GAAWQ,IAAS,gBAAgBN,EAAc,KAAKK,CAAK,CACzE,CACA,MAAO,CAAE,GAAIN,EAAO,CAAE,MAAK,EAAI,CAAC,EAAI,eAAc,CACtD,C"}
1
+ {"version":3,"file":"setup.js","names":["installScriptUrl","installArguments","Client","phaseOf","parseInstallOutput","RunnerClient","require_client","require_steps","ssh2","InstallError","message","code","output","remoteInstallCommand","run","options","installOverSsh","connection","fingerprint","settled","finish","timer","error","reject","resolve","result","config","target","hash","root","pending","read","text","chunk","lines","line","shown","stream","parsed","installAndPair","installed","paired","hostMatches","escaped","pattern","char","host","sshConfigFor","applies","user","identityFiles","raw","configText","keyword","rest","value","name","patterns"],"sources":["../src/setup/index.ts"],"sourcesContent":["// @llmnative/runner/setup — installs a runner on a VPS over SSH, for Node: the command line\n// (`npx @llmnative/runner install`) and the backend of a host (a Cloud Function, the server of a studio). It runs the\n// same install.sh a person pastes by hand (steps.ts), streams what it prints, and reads the address and the pairing\n// code at its end. The SSH credentials are used for this connection only and never kept.\n\nimport { Client, type ConnectConfig } from 'ssh2';\nimport { RunnerClient } from '../client';\nimport { installArguments, installScriptUrl, parseInstallOutput, phaseOf, type InstallOptions, type InstallPhase } from './steps';\n\nexport * from './steps';\n\nexport type SshTarget = {\n host: string;\n port?: number;\n username: string;\n /** A private key (PEM/OpenSSH), or a password. */\n privateKey?: string;\n passphrase?: string;\n password?: string;\n /**\n * The fingerprint the server must have (`SHA256:…`, as `ssh-keygen -lf` prints it); none: the first one is taken\n * and given back in the result, to be kept for the next time.\n */\n hostFingerprint?: string;\n};\n\nexport type InstallProgress = { line: string; phase?: InstallPhase };\n\nexport type InstallResult = { url: string; pairingCode: string; hostFingerprint: string };\n\nexport class InstallError extends Error {\n readonly code: string;\n readonly output: string;\n\n constructor(code: string, message: string, output = '') {\n super(message);\n this.name = 'InstallError';\n this.code = code;\n this.output = output;\n }\n}\n\n/** The command run on the VPS: the script of the release, with sudo unless the user is root. */\nexport function remoteInstallCommand(options: InstallOptions & { root: boolean }): string {\n const run = options.root ? 'sh' : 'sudo -n sh';\n return `curl -fsSL ${installScriptUrl(options.version)} | ${run} -s -- ${installArguments(options).join(' ')}`;\n}\n\n/** Installs a runner over SSH; `onProgress` gets every line it prints (and the phase when one starts). */\nexport function installOverSsh(target: SshTarget, options: InstallOptions & { onProgress?: (progress: InstallProgress) => void; timeoutMs?: number }): Promise<InstallResult> {\n return new Promise((resolve, reject) => {\n const connection = new Client();\n let fingerprint = '';\n let output = '';\n let settled = false;\n const finish = (error?: InstallError, result?: InstallResult) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n connection.end();\n if (error) reject(error);\n else resolve(result!);\n };\n const timer = setTimeout(() => finish(new InstallError('timeout', 'the installation took too long', output)), options.timeoutMs ?? 20 * 60_000);\n const config: ConnectConfig = {\n host: target.host,\n port: target.port ?? 22,\n username: target.username,\n readyTimeout: 30_000,\n ...(target.privateKey ? { privateKey: target.privateKey, ...(target.passphrase ? { passphrase: target.passphrase } : {}) } : {}),\n ...(target.password ? { password: target.password } : {}),\n hostHash: 'sha256',\n hostVerifier: (hash: string) => {\n // ssh2 gives the hash in hex: shown as OpenSSH does (SHA256:<base64>).\n fingerprint = `SHA256:${Buffer.from(hash, 'hex').toString('base64').replace(/=+$/, '')}`;\n return !target.hostFingerprint || target.hostFingerprint === fingerprint;\n },\n };\n connection.on('error', (error: Error & { level?: string }) => {\n const code = /authentication/i.test(error.message) ? 'ssh-auth' : /verif/i.test(error.message) ? 'ssh-host-key' : 'ssh-connect';\n finish(new InstallError(code, error.message, output));\n });\n connection.on('ready', () => {\n const root = target.username === 'root';\n connection.exec(remoteInstallCommand({ ...options, root }), (error, stream) => {\n if (error) return finish(new InstallError('ssh-exec', error.message, output));\n let pending = '';\n const read = (chunk: Buffer) => {\n const text = chunk.toString('utf8');\n output = (output + text).slice(-200_000);\n pending += text;\n const lines = pending.split('\\n');\n pending = lines.pop() ?? '';\n for (const line of lines) {\n // The pairing code is for the result, not for a log that may be kept.\n const shown = line.replace(/^(PAIRING_CODE=).+$/, '$1…').replace(/(Pairing code:\\s+)\\S+/, '$1…');\n options.onProgress?.({ line: shown, ...(phaseOf(line) ? { phase: phaseOf(line) } : {}) });\n }\n };\n stream.on('data', read);\n stream.stderr.on('data', read);\n stream.on('close', (code: number | null) => {\n const parsed = parseInstallOutput(output);\n if (code === 0 && parsed.url && parsed.pairingCode) return finish(undefined, { url: parsed.url, pairingCode: parsed.pairingCode, hostFingerprint: fingerprint });\n if (!root && /sudo: a password is required|sudo: a terminal is required/.test(output)) return finish(new InstallError('sudo', 'the user needs sudo without a password, or connect as root', output));\n finish(new InstallError(parsed.error ?? 'install', `the installer ended with ${code ?? 'no code'}`, output));\n });\n });\n });\n connection.connect(config);\n });\n}\n\n/** Installs and pairs at once: the platform key, seen once, to keep in the backend of the host. */\nexport async function installAndPair(target: SshTarget, options: InstallOptions & { name?: string; /** The project the platform key owns the tenants of. */ project?: string; onProgress?: (progress: InstallProgress) => void; fetch?: typeof fetch }) {\n const installed = await installOverSsh(target, options);\n const paired = await new RunnerClient({ url: installed.url, ...(options.fetch ? { fetch: options.fetch } : {}) }).pair(installed.pairingCode, options.name, options.project);\n return { url: installed.url, hostFingerprint: installed.hostFingerprint, platformKey: paired.key, version: paired.version };\n}\n\n/** A `Host` pattern of ~/.ssh/config (`*` and `?`) against a host name. */\nconst hostMatches = (pattern: string, host: string) => {\n const escaped = pattern.replace(/[.+^${}()|[\\]\\\\]/g, (char) => `\\\\${char}`).replace(/\\*/g, '.*').replace(/\\?/g, '.');\n return new RegExp(`^${escaped}$`, 'i').test(host);\n};\n\n/**\n * What ~/.ssh/config says for a host: its user and its key files, in the order ssh tries them (first match of each\n * option wins, as ssh does). `~` left as is: the caller resolves it.\n */\nexport function sshConfigFor(configText: string, host: string): { user?: string; identityFiles: string[] } {\n let applies = true;\n let user: string | undefined;\n const identityFiles: string[] = [];\n for (const raw of configText.split(/\\r?\\n/)) {\n const line = raw.trim();\n if (!line || line.startsWith('#')) continue;\n const [keyword, ...rest] = line.split(/\\s+/);\n const value = rest.join(' ').replace(/^\"(.*)\"$/, '$1');\n const name = keyword.toLowerCase();\n if (name === 'host') {\n const patterns = rest;\n applies = patterns.some((pattern) => !pattern.startsWith('!') && hostMatches(pattern, host)) && !patterns.some((pattern) => pattern.startsWith('!') && hostMatches(pattern.slice(1), host));\n } else if (name === 'match') applies = false;\n else if (applies && name === 'user' && user === undefined) user = value;\n else if (applies && name === 'identityfile') identityFiles.push(value);\n }\n return { ...(user ? { user } : {}), identityFiles };\n}\n"],"mappings":"A,gJA8BA,IAAaS,EAAb,cAAkC,KAAM,CACpC,KACA,OAEA,YAAY,EAAc,EAAiB,EAAS,GAAI,CACpD,MAAMC,CAAO,EACb,KAAK,KAAO,eACZ,KAAK,KAAOC,EACZ,KAAK,OAASC,CAClB,CACJ,EAGA,SAAgBC,EAAqB,EAAqD,CACtF,IAAMC,EAAMC,EAAQ,KAAO,KAAO,aAClC,MAAO,cAAcf,EAAAA,iBAAiBe,EAAQ,OAAO,EAAE,KAAKD,EAAI,SAASb,EAAAA,iBAAiBc,CAAO,CAAC,CAAC,KAAK,GAAG,GAC/G,CAGA,SAAgBC,EAAe,EAAmB,EAA4H,CAC1K,OAAO,IAAI,SAAS,EAAS,IAAW,CACpC,IAAMC,EAAa,IAAIf,EAAAA,OACnBgB,EAAc,GACdN,EAAS,GACTO,EAAU,GACRC,GAAU,EAAsB,IAA2B,CACzDD,IACJ,EAAU,GACV,aAAaE,CAAK,EAClBJ,EAAW,IAAI,EACXK,EAAOC,EAAOD,CAAK,EAClBE,EAAQC,CAAO,EACxB,EACMJ,EAAQ,eAAiBD,EAAO,IAAIX,EAAa,UAAW,iCAAkCG,CAAM,CAAC,EAAGG,EAAQ,WAAa,IAAW,EACxIW,EAAwB,CAC1B,KAAMC,EAAO,KACb,KAAMA,EAAO,MAAQ,GACrB,SAAUA,EAAO,SACjB,aAAc,IACd,GAAIA,EAAO,WAAa,CAAE,WAAYA,EA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AAIC,EAAU,GACVC,EACEC,EAA0B,CAAC,EACjC,IAAK,IAAMC,KAAOC,EAAW,MAAM,OAAO,EAAG,CACzC,IAAMjB,EAAOgB,EAAI,KAAK,EACtB,GAAI,CAAChB,GAAQA,EAAK,WAAW,GAAG,EAAG,SACnC,GAAM,CAACkB,EAAS,GAAGC,GAAQnB,EAAK,MAAM,KAAK,EACrCoB,EAAQD,EAAK,KAAK,GAAG,CAAC,CAAC,QAAQ,WAAY,IAAI,EAC/CE,EAAOH,EAAQ,YAAY,EACjC,GAAIG,IAAS,OAAQ,CACjB,IAAMC,EAAWH,EACjB,EAAUG,EAAS,KAAM,GAAY,CAACb,EAAQ,WAAW,GAAG,GAAKF,EAAYE,EAASE,CAAI,CAAC,GAAK,CAACW,EAAS,KAAM,GAAYb,EAAQ,WAAW,GAAG,GAAKF,EAAYE,EAAQ,MAAM,CAAC,EAAGE,CAAI,CAAC,CAC9L,MAAWU,IAAS,QAAS,EAAU,GAC9BR,GAAWQ,IAAS,QAAUP,IAAS,IAAA,GAAW,EAAOM,EACzDP,GAAWQ,IAAS,gBAAgBN,EAAc,KAAKK,CAAK,CACzE,CACA,MAAO,CAAE,GAAIN,EAAO,CAAE,MAAK,EAAI,CAAC,EAAI,eAAc,CACtD,C"}
package/dist/setup.mjs CHANGED
@@ -71,7 +71,7 @@ async function x(t, n) {
71
71
  let r = await b(t, n), i = await new e({
72
72
  url: r.url,
73
73
  ...n.fetch ? { fetch: n.fetch } : {}
74
- }).pair(r.pairingCode, n.name);
74
+ }).pair(r.pairingCode, n.name, n.project);
75
75
  return {
76
76
  url: r.url,
77
77
  hostFingerprint: r.hostFingerprint,
@@ -1 +1 @@
1
- {"version":3,"file":"setup.mjs","names":["InstallError","message","code","output","remoteInstallCommand","run","options","installScriptUrl","installArguments","installOverSsh","connection","Client","fingerprint","settled","finish","timer","error","reject","resolve","result","config","target","hash","root","pending","read","text","chunk","lines","line","shown","phaseOf","stream","parsed","parseInstallOutput","installAndPair","installed","paired","RunnerClient","hostMatches","escaped","pattern","char","host","sshConfigFor","applies","user","identityFiles","raw","configText","keyword","rest","value","name","patterns","DOMAIN_PATTERN","GUIDE_STEPS","INSTALL_PHASES","RUNNER_REPOSITORY","RUNNER_REQUIREMENTS","RUNNER_VERSION","checkRunner","checksumUrl","installCommand","isDomain","lookupDomain","verifiedInstallCommands"],"sources":["../src/setup/index.ts"],"sourcesContent":["// @llmnative/runner/setup — installs a runner on a VPS over SSH, for Node: the command line\n// (`npx @llmnative/runner install`) and the backend of a host (a Cloud Function, the server of a studio). It runs the\n// same install.sh a person pastes by hand (steps.ts), streams what it prints, and reads the address and the pairing\n// code at its end. The SSH credentials are used for this connection only and never kept.\n\nimport { Client, type ConnectConfig } from 'ssh2';\nimport { RunnerClient } from '../client';\nimport { installArguments, installScriptUrl, parseInstallOutput, phaseOf, type InstallOptions, type InstallPhase } from './steps';\n\nexport * from './steps';\n\nexport type SshTarget = {\n host: string;\n port?: number;\n username: string;\n /** A private key (PEM/OpenSSH), or a password. */\n privateKey?: string;\n passphrase?: string;\n password?: string;\n /**\n * The fingerprint the server must have (`SHA256:…`, as `ssh-keygen -lf` prints it); none: the first one is taken\n * and given back in the result, to be kept for the next time.\n */\n hostFingerprint?: string;\n};\n\nexport type InstallProgress = { line: string; phase?: InstallPhase };\n\nexport type InstallResult = { url: string; pairingCode: string; hostFingerprint: string };\n\nexport class InstallError extends Error {\n readonly code: string;\n readonly output: string;\n\n constructor(code: string, message: string, output = '') {\n super(message);\n this.name = 'InstallError';\n this.code = code;\n this.output = output;\n }\n}\n\n/** The command run on the VPS: the script of the release, with sudo unless the user is root. */\nexport function remoteInstallCommand(options: InstallOptions & { root: boolean }): string {\n const run = options.root ? 'sh' : 'sudo -n sh';\n return `curl -fsSL ${installScriptUrl(options.version)} | ${run} -s -- ${installArguments(options).join(' ')}`;\n}\n\n/** Installs a runner over SSH; `onProgress` gets every line it prints (and the phase when one starts). */\nexport function installOverSsh(target: SshTarget, options: InstallOptions & { onProgress?: (progress: InstallProgress) => void; timeoutMs?: number }): Promise<InstallResult> {\n return new Promise((resolve, reject) => {\n const connection = new Client();\n let fingerprint = '';\n let output = '';\n let settled = false;\n const finish = (error?: InstallError, result?: InstallResult) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n connection.end();\n if (error) reject(error);\n else resolve(result!);\n };\n const timer = setTimeout(() => finish(new InstallError('timeout', 'the installation took too long', output)), options.timeoutMs ?? 20 * 60_000);\n const config: ConnectConfig = {\n host: target.host,\n port: target.port ?? 22,\n username: target.username,\n readyTimeout: 30_000,\n ...(target.privateKey ? { privateKey: target.privateKey, ...(target.passphrase ? { passphrase: target.passphrase } : {}) } : {}),\n ...(target.password ? { password: target.password } : {}),\n hostHash: 'sha256',\n hostVerifier: (hash: string) => {\n // ssh2 gives the hash in hex: shown as OpenSSH does (SHA256:<base64>).\n fingerprint = `SHA256:${Buffer.from(hash, 'hex').toString('base64').replace(/=+$/, '')}`;\n return !target.hostFingerprint || target.hostFingerprint === fingerprint;\n },\n };\n connection.on('error', (error: Error & { level?: string }) => {\n const code = /authentication/i.test(error.message) ? 'ssh-auth' : /verif/i.test(error.message) ? 'ssh-host-key' : 'ssh-connect';\n finish(new InstallError(code, error.message, output));\n });\n connection.on('ready', () => {\n const root = target.username === 'root';\n connection.exec(remoteInstallCommand({ ...options, root }), (error, stream) => {\n if (error) return finish(new InstallError('ssh-exec', error.message, output));\n let pending = '';\n const read = (chunk: Buffer) => {\n const text = chunk.toString('utf8');\n output = (output + text).slice(-200_000);\n pending += text;\n const lines = pending.split('\\n');\n pending = lines.pop() ?? '';\n for (const line of lines) {\n // The pairing code is for the result, not for a log that may be kept.\n const shown = line.replace(/^(PAIRING_CODE=).+$/, '$1…').replace(/(Pairing code:\\s+)\\S+/, '$1…');\n options.onProgress?.({ line: shown, ...(phaseOf(line) ? { phase: phaseOf(line) } : {}) });\n }\n };\n stream.on('data', read);\n stream.stderr.on('data', read);\n stream.on('close', (code: number | null) => {\n const parsed = parseInstallOutput(output);\n if (code === 0 && parsed.url && parsed.pairingCode) return finish(undefined, { url: parsed.url, pairingCode: parsed.pairingCode, hostFingerprint: fingerprint });\n if (!root && /sudo: a password is required|sudo: a terminal is required/.test(output)) return finish(new InstallError('sudo', 'the user needs sudo without a password, or connect as root', output));\n finish(new InstallError(parsed.error ?? 'install', `the installer ended with ${code ?? 'no code'}`, output));\n });\n });\n });\n connection.connect(config);\n });\n}\n\n/** Installs and pairs at once: the platform key, seen once, to keep in the backend of the host. */\nexport async function installAndPair(target: SshTarget, options: InstallOptions & { name?: string; onProgress?: (progress: InstallProgress) => void; fetch?: typeof fetch }) {\n const installed = await installOverSsh(target, options);\n const paired = await new RunnerClient({ url: installed.url, ...(options.fetch ? { fetch: options.fetch } : {}) }).pair(installed.pairingCode, options.name);\n return { url: installed.url, hostFingerprint: installed.hostFingerprint, platformKey: paired.key, version: paired.version };\n}\n\n/** A `Host` pattern of ~/.ssh/config (`*` and `?`) against a host name. */\nconst hostMatches = (pattern: string, host: string) => {\n const escaped = pattern.replace(/[.+^${}()|[\\]\\\\]/g, (char) => `\\\\${char}`).replace(/\\*/g, '.*').replace(/\\?/g, '.');\n return new RegExp(`^${escaped}$`, 'i').test(host);\n};\n\n/**\n * What ~/.ssh/config says for a host: its user and its key files, in the order ssh tries them (first match of each\n * option wins, as ssh does). `~` left as is: the caller resolves it.\n */\nexport function sshConfigFor(configText: string, host: string): { user?: string; identityFiles: string[] } {\n let applies = true;\n let user: string | undefined;\n const identityFiles: string[] = [];\n for (const raw of configText.split(/\\r?\\n/)) {\n const line = raw.trim();\n if (!line || line.startsWith('#')) continue;\n const [keyword, ...rest] = line.split(/\\s+/);\n const value = rest.join(' ').replace(/^\"(.*)\"$/, '$1');\n const name = keyword.toLowerCase();\n if (name === 'host') {\n const patterns = rest;\n applies = patterns.some((pattern) => !pattern.startsWith('!') && hostMatches(pattern, host)) && !patterns.some((pattern) => pattern.startsWith('!') && hostMatches(pattern.slice(1), host));\n } else if (name === 'match') applies = false;\n else if (applies && name === 'user' && user === undefined) user = value;\n else if (applies && name === 'identityfile') identityFiles.push(value);\n }\n return { ...(user ? { user } : {}), identityFiles };\n}\n"],"mappings":";;;;AA8BA,IAAaA,IAAb,cAAkC,MAAM;CACpC;CACA;CAEA,YAAY,GAAc,GAAiB,IAAS,IAAI;EAIpD,AAHA,MAAMC,CAAO,GACb,KAAK,OAAO,gBACZ,KAAK,OAAOC,GACZ,KAAK,SAASC;CAClB;AACJ;AAGA,SAAgBC,EAAqB,GAAqD;CACtF,IAAMC,IAAMC,EAAQ,OAAO,OAAO;CAClC,OAAO,cAAcC,EAAiBD,EAAQ,OAAO,EAAE,KAAKD,EAAI,SAASG,EAAiBF,CAAO,CAAC,CAAC,KAAK,GAAG;AAC/G;AAGA,SAAgBG,EAAe,GAAmB,GAA4H;CAC1K,OAAO,IAAI,SAAS,GAAS,MAAW;EACpC,IAAMC,IAAa,IAAIC,EAAO,GAC1BC,IAAc,IACdT,IAAS,IACTU,IAAU,IACRC,KAAU,GAAsB,MAA2B;GAC7D,AAAID,MACJ,IAAU,IACV,aAAaE,CAAK,GAClBL,EAAW,IAAI,GACXM,IAAOC,EAAOD,CAAK,IAClBE,EAAQC,CAAO;EACxB,GACMJ,IAAQ,iBAAiBD,EAAO,IAAId,EAAa,WAAW,kCAAkCG,CAAM,CAAC,GAAGG,EAAQ,aAAa,IAAW,GACxIc,IAAwB;GAC1B,MAAMC,EAAO;GACb,MAAMA,EAAO,QAAQ;GACrB,UAAUA,EAAO;GACjB,cAAc;GACd,GAAIA,EAAO,aAAa;IAAE,YAAYA,EAAO;IAAY,GAAIA,EAAO,aAAa,EAAE,YAAYA,EAAO,WAAW,IAAI,CAAC;GAAG,IAAI,CAAC;GAC9H,GAAIA,EAAO,WAAW,EAAE,UAAUA,EAAO,SAAS,IAAI,CAAC;GACvD,UAAU;GACV,eAAe,OAEX,IAAc,UAAU,OAAO,KAAKC,GAAM,KAAK,CAAC,CAAC,SAAS,QAAQ,C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,YAAY,IAAI,GAC/CE,IAAOH,EAAQ,YAAY;EACjC,IAAIG,MAAS,QAAQ;GACjB,IAAMC,IAAWH;GACjB,IAAUG,EAAS,MAAM,MAAY,CAACb,EAAQ,WAAW,GAAG,KAAKF,EAAYE,GAASE,CAAI,CAAC,KAAK,CAACW,EAAS,MAAM,MAAYb,EAAQ,WAAW,GAAG,KAAKF,EAAYE,EAAQ,MAAM,CAAC,GAAGE,CAAI,CAAC;EAC9L,OAAO,AAAIU,MAAS,UAAS,IAAU,KAC9BR,KAAWQ,MAAS,UAAUP,MAAS,KAAA,IAAW,IAAOM,IACzDP,KAAWQ,MAAS,kBAAgBN,EAAc,KAAKK,CAAK;CACzE;CACA,OAAO;EAAE,GAAIN,IAAO,EAAE,QAAK,IAAI,CAAC;EAAI;CAAc;AACtD"}
1
+ {"version":3,"file":"setup.mjs","names":["InstallError","message","code","output","remoteInstallCommand","run","options","installScriptUrl","installArguments","installOverSsh","connection","Client","fingerprint","settled","finish","timer","error","reject","resolve","result","config","target","hash","root","pending","read","text","chunk","lines","line","shown","phaseOf","stream","parsed","parseInstallOutput","installAndPair","installed","paired","RunnerClient","hostMatches","escaped","pattern","char","host","sshConfigFor","applies","user","identityFiles","raw","configText","keyword","rest","value","name","patterns","DOMAIN_PATTERN","GUIDE_STEPS","INSTALL_PHASES","RUNNER_REPOSITORY","RUNNER_REQUIREMENTS","RUNNER_VERSION","checkRunner","checksumUrl","installCommand","isDomain","lookupDomain","verifiedInstallCommands"],"sources":["../src/setup/index.ts"],"sourcesContent":["// @llmnative/runner/setup — installs a runner on a VPS over SSH, for Node: the command line\n// (`npx @llmnative/runner install`) and the backend of a host (a Cloud Function, the server of a studio). It runs the\n// same install.sh a person pastes by hand (steps.ts), streams what it prints, and reads the address and the pairing\n// code at its end. The SSH credentials are used for this connection only and never kept.\n\nimport { Client, type ConnectConfig } from 'ssh2';\nimport { RunnerClient } from '../client';\nimport { installArguments, installScriptUrl, parseInstallOutput, phaseOf, type InstallOptions, type InstallPhase } from './steps';\n\nexport * from './steps';\n\nexport type SshTarget = {\n host: string;\n port?: number;\n username: string;\n /** A private key (PEM/OpenSSH), or a password. */\n privateKey?: string;\n passphrase?: string;\n password?: string;\n /**\n * The fingerprint the server must have (`SHA256:…`, as `ssh-keygen -lf` prints it); none: the first one is taken\n * and given back in the result, to be kept for the next time.\n */\n hostFingerprint?: string;\n};\n\nexport type InstallProgress = { line: string; phase?: InstallPhase };\n\nexport type InstallResult = { url: string; pairingCode: string; hostFingerprint: string };\n\nexport class InstallError extends Error {\n readonly code: string;\n readonly output: string;\n\n constructor(code: string, message: string, output = '') {\n super(message);\n this.name = 'InstallError';\n this.code = code;\n this.output = output;\n }\n}\n\n/** The command run on the VPS: the script of the release, with sudo unless the user is root. */\nexport function remoteInstallCommand(options: InstallOptions & { root: boolean }): string {\n const run = options.root ? 'sh' : 'sudo -n sh';\n return `curl -fsSL ${installScriptUrl(options.version)} | ${run} -s -- ${installArguments(options).join(' ')}`;\n}\n\n/** Installs a runner over SSH; `onProgress` gets every line it prints (and the phase when one starts). */\nexport function installOverSsh(target: SshTarget, options: InstallOptions & { onProgress?: (progress: InstallProgress) => void; timeoutMs?: number }): Promise<InstallResult> {\n return new Promise((resolve, reject) => {\n const connection = new Client();\n let fingerprint = '';\n let output = '';\n let settled = false;\n const finish = (error?: InstallError, result?: InstallResult) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n connection.end();\n if (error) reject(error);\n else resolve(result!);\n };\n const timer = setTimeout(() => finish(new InstallError('timeout', 'the installation took too long', output)), options.timeoutMs ?? 20 * 60_000);\n const config: ConnectConfig = {\n host: target.host,\n port: target.port ?? 22,\n username: target.username,\n readyTimeout: 30_000,\n ...(target.privateKey ? { privateKey: target.privateKey, ...(target.passphrase ? { passphrase: target.passphrase } : {}) } : {}),\n ...(target.password ? { password: target.password } : {}),\n hostHash: 'sha256',\n hostVerifier: (hash: string) => {\n // ssh2 gives the hash in hex: shown as OpenSSH does (SHA256:<base64>).\n fingerprint = `SHA256:${Buffer.from(hash, 'hex').toString('base64').replace(/=+$/, '')}`;\n return !target.hostFingerprint || target.hostFingerprint === fingerprint;\n },\n };\n connection.on('error', (error: Error & { level?: string }) => {\n const code = /authentication/i.test(error.message) ? 'ssh-auth' : /verif/i.test(error.message) ? 'ssh-host-key' : 'ssh-connect';\n finish(new InstallError(code, error.message, output));\n });\n connection.on('ready', () => {\n const root = target.username === 'root';\n connection.exec(remoteInstallCommand({ ...options, root }), (error, stream) => {\n if (error) return finish(new InstallError('ssh-exec', error.message, output));\n let pending = '';\n const read = (chunk: Buffer) => {\n const text = chunk.toString('utf8');\n output = (output + text).slice(-200_000);\n pending += text;\n const lines = pending.split('\\n');\n pending = lines.pop() ?? '';\n for (const line of lines) {\n // The pairing code is for the result, not for a log that may be kept.\n const shown = line.replace(/^(PAIRING_CODE=).+$/, '$1…').replace(/(Pairing code:\\s+)\\S+/, '$1…');\n options.onProgress?.({ line: shown, ...(phaseOf(line) ? { phase: phaseOf(line) } : {}) });\n }\n };\n stream.on('data', read);\n stream.stderr.on('data', read);\n stream.on('close', (code: number | null) => {\n const parsed = parseInstallOutput(output);\n if (code === 0 && parsed.url && parsed.pairingCode) return finish(undefined, { url: parsed.url, pairingCode: parsed.pairingCode, hostFingerprint: fingerprint });\n if (!root && /sudo: a password is required|sudo: a terminal is required/.test(output)) return finish(new InstallError('sudo', 'the user needs sudo without a password, or connect as root', output));\n finish(new InstallError(parsed.error ?? 'install', `the installer ended with ${code ?? 'no code'}`, output));\n });\n });\n });\n connection.connect(config);\n });\n}\n\n/** Installs and pairs at once: the platform key, seen once, to keep in the backend of the host. */\nexport async function installAndPair(target: SshTarget, options: InstallOptions & { name?: string; /** The project the platform key owns the tenants of. */ project?: string; onProgress?: (progress: InstallProgress) => void; fetch?: typeof fetch }) {\n const installed = await installOverSsh(target, options);\n const paired = await new RunnerClient({ url: installed.url, ...(options.fetch ? { fetch: options.fetch } : {}) }).pair(installed.pairingCode, options.name, options.project);\n return { url: installed.url, hostFingerprint: installed.hostFingerprint, platformKey: paired.key, version: paired.version };\n}\n\n/** A `Host` pattern of ~/.ssh/config (`*` and `?`) against a host name. */\nconst hostMatches = (pattern: string, host: string) => {\n const escaped = pattern.replace(/[.+^${}()|[\\]\\\\]/g, (char) => `\\\\${char}`).replace(/\\*/g, '.*').replace(/\\?/g, '.');\n return new RegExp(`^${escaped}$`, 'i').test(host);\n};\n\n/**\n * What ~/.ssh/config says for a host: its user and its key files, in the order ssh tries them (first match of each\n * option wins, as ssh does). `~` left as is: the caller resolves it.\n */\nexport function sshConfigFor(configText: string, host: string): { user?: string; identityFiles: string[] } {\n let applies = true;\n let user: string | undefined;\n const identityFiles: string[] = [];\n for (const raw of configText.split(/\\r?\\n/)) {\n const line = raw.trim();\n if (!line || line.startsWith('#')) continue;\n const [keyword, ...rest] = line.split(/\\s+/);\n const value = rest.join(' ').replace(/^\"(.*)\"$/, '$1');\n const name = keyword.toLowerCase();\n if (name === 'host') {\n const patterns = rest;\n applies = patterns.some((pattern) => !pattern.startsWith('!') && hostMatches(pattern, host)) && !patterns.some((pattern) => pattern.startsWith('!') && hostMatches(pattern.slice(1), host));\n } else if (name === 'match') applies = false;\n else if (applies && name === 'user' && user === undefined) user = value;\n else if (applies && name === 'identityfile') identityFiles.push(value);\n }\n return { ...(user ? { user } : {}), identityFiles };\n}\n"],"mappings":";;;;AA8BA,IAAaA,IAAb,cAAkC,MAAM;CACpC;CACA;CAEA,YAAY,GAAc,GAAiB,IAAS,IAAI;EAIpD,AAHA,MAAMC,CAAO,GACb,KAAK,OAAO,gBACZ,KAAK,OAAOC,GACZ,KAAK,SAASC;CAClB;AACJ;AAGA,SAAgBC,EAAqB,GAAqD;CACtF,IAAMC,IAAMC,EAAQ,OAAO,OAAO;CAClC,OAAO,cAAcC,EAAiBD,EAAQ,OAAO,EAAE,KAAKD,EAAI,SAASG,EAAiBF,CAAO,CAAC,CAAC,KAAK,GAAG;AAC/G;AAGA,SAAgBG,EAA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AAC;EAAI;CAAc;AACtD"}
package/dist/steps.js CHANGED
@@ -1,2 +1,2 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=`1.1.1`,t=`sherpadvisorylab/llmnative-runner`,n={systems:[`Ubuntu 22.04 or newer`,`Debian 12 or newer`],architectures:[`x86_64`,`arm64`],cpus:2,memoryGb:4,diskGb:20,ports:[22,80,443]},r=/^(?=.{4,253}$)([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/,i=e=>r.test(e.trim().toLowerCase()),a=(n=e)=>`https://github.com/${t}/releases/download/v${n}/install.sh`,o=(t=e)=>`${a(t)}.sha256`;function s({domain:e,maxChats:t}){return[`--domain`,(e=>`'${e.replace(/'/g,`'\\''`)}'`)(e.trim().toLowerCase()),...t?[`--max-chats`,String(t)]:[]]}function c(e){return`curl -fsSL ${a(e.version)} | sudo sh -s -- ${s(e).join(` `)}`}function l(e){let t=e.version??`1.1.1`;return[`curl -fsSLO ${a(t)}`,`curl -fsSL ${o(t)} | sha256sum -c -`,`sudo sh install.sh ${s(e).join(` `)}`]}var u=[{id:`server`},{id:`dns`,check:`dns`},{id:`access`},{id:`install`},{id:`pair`,check:`health`}];function d(e){let t=t=>RegExp(`^${t}=(.+)$`,`m`).exec(e)?.[1]?.trim(),n=t(`RUNNER_URL`),r=t(`PAIRING_CODE`),i=t(`RUNNER_ERROR`);return{...n?{url:n}:{},...r?{pairingCode:r}:{},...i?{error:i}:{}}}var f=[`check`,`docker`,`files`,`start`,`agent`,`health`,`pair`,`tls`,`done`],p=e=>{let t=/^STEP=([a-z]+)$/.exec(e.trim());return t&&f.includes(t[1])?t[1]:void 0};async function m(e,t={}){let n=t.resolver??`https://cloudflare-dns.com/dns-query`,r=async r=>{let i=await(t.fetch??fetch)(`${n}?name=${encodeURIComponent(e)}&type=${r}`,{headers:{accept:`application/dns-json`}});return i.ok?((await i.json()).Answer??[]).filter(e=>e.type===(r===`A`?1:28)).map(e=>e.data):[]},[i,a]=await Promise.all([r(`A`),r(`AAAA`)]);return[...i,...a]}async function h(e,t=fetch){try{let n=await t(`${e.replace(/\/+$/,``)}/health`);if(!n.ok)return{ok:!1,reason:`not-a-runner`};let r=await n.json();return r.ok&&typeof r.version==`string`?{ok:!0,version:r.version}:{ok:!1,reason:`not-a-runner`}}catch{return{ok:!1,reason:`unreachable`}}}exports.DOMAIN_PATTERN=r,exports.GUIDE_STEPS=u,exports.INSTALL_PHASES=f,exports.RUNNER_REPOSITORY=t,exports.RUNNER_REQUIREMENTS=n,exports.RUNNER_VERSION=e,exports.checkRunner=h,exports.checksumUrl=o,exports.installArguments=s,exports.installCommand=c,exports.installScriptUrl=a,exports.isDomain=i,exports.lookupDomain=m,exports.parseInstallOutput=d,exports.phaseOf=p,exports.verifiedInstallCommands=l;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=`1.2.0`,t=`sherpadvisorylab/llmnative-runner`,n={systems:[`Ubuntu 22.04 or newer`,`Debian 12 or newer`],architectures:[`x86_64`,`arm64`],cpus:2,memoryGb:4,diskGb:20,ports:[22,80,443]},r=/^(?=.{4,253}$)([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/,i=e=>r.test(e.trim().toLowerCase()),a=(n=e)=>`https://github.com/${t}/releases/download/v${n}/install.sh`,o=(t=e)=>`${a(t)}.sha256`;function s({domain:e,maxChats:t}){return[`--domain`,(e=>`'${e.replace(/'/g,`'\\''`)}'`)(e.trim().toLowerCase()),...t?[`--max-chats`,String(t)]:[]]}function c(e){return`curl -fsSL ${a(e.version)} | sudo sh -s -- ${s(e).join(` `)}`}function l(e){let t=e.version??`1.2.0`;return[`curl -fsSLO ${a(t)}`,`curl -fsSL ${o(t)} | sha256sum -c -`,`sudo sh install.sh ${s(e).join(` `)}`]}var u=[{id:`server`},{id:`dns`,check:`dns`},{id:`access`},{id:`install`},{id:`pair`,check:`health`}];function d(e){let t=t=>RegExp(`^${t}=(.+)$`,`m`).exec(e)?.[1]?.trim(),n=t(`RUNNER_URL`),r=t(`PAIRING_CODE`),i=t(`RUNNER_ERROR`);return{...n?{url:n}:{},...r?{pairingCode:r}:{},...i?{error:i}:{}}}var f=[`check`,`docker`,`files`,`start`,`agent`,`health`,`pair`,`tls`,`done`],p=e=>{let t=/^STEP=([a-z]+)$/.exec(e.trim());return t&&f.includes(t[1])?t[1]:void 0};async function m(e,t={}){let n=t.resolver??`https://cloudflare-dns.com/dns-query`,r=async r=>{let i=await(t.fetch??fetch)(`${n}?name=${encodeURIComponent(e)}&type=${r}`,{headers:{accept:`application/dns-json`}});return i.ok?((await i.json()).Answer??[]).filter(e=>e.type===(r===`A`?1:28)).map(e=>e.data):[]},[i,a]=await Promise.all([r(`A`),r(`AAAA`)]);return[...i,...a]}async function h(e,t=fetch){try{let n=await t(`${e.replace(/\/+$/,``)}/health`);if(!n.ok)return{ok:!1,reason:`not-a-runner`};let r=await n.json();return r.ok&&typeof r.version==`string`?{ok:!0,version:r.version}:{ok:!1,reason:`not-a-runner`}}catch{return{ok:!1,reason:`unreachable`}}}exports.DOMAIN_PATTERN=r,exports.GUIDE_STEPS=u,exports.INSTALL_PHASES=f,exports.RUNNER_REPOSITORY=t,exports.RUNNER_REQUIREMENTS=n,exports.RUNNER_VERSION=e,exports.checkRunner=h,exports.checksumUrl=o,exports.installArguments=s,exports.installCommand=c,exports.installScriptUrl=a,exports.isDomain=i,exports.lookupDomain=m,exports.parseInstallOutput=d,exports.phaseOf=p,exports.verifiedInstallCommands=l;
2
2
  //# sourceMappingURL=steps.js.map
package/dist/steps.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  // src/setup/steps.ts
2
- var e = "1.1.1", t = "sherpadvisorylab/llmnative-runner", n = {
2
+ var e = "1.2.0", t = "sherpadvisorylab/llmnative-runner", n = {
3
3
  systems: ["Ubuntu 22.04 or newer", "Debian 12 or newer"],
4
4
  architectures: ["x86_64", "arm64"],
5
5
  cpus: 2,
@@ -22,7 +22,7 @@ function c(e) {
22
22
  return `curl -fsSL ${a(e.version)} | sudo sh -s -- ${s(e).join(" ")}`;
23
23
  }
24
24
  function l(e) {
25
- let t = e.version ?? "1.1.1";
25
+ let t = e.version ?? "1.2.0";
26
26
  return [
27
27
  `curl -fsSLO ${a(t)}`,
28
28
  `curl -fsSL ${o(t)} | sha256sum -c -`,
@@ -1,4 +1,7 @@
1
- export type RunnerProvider = 'claude-code' | 'opencode-go' | 'opencode';
1
+ /** The providers paid by use whose API key the runner keeps and opencode runs (ids of @llmnative/react). */
2
+ export declare const RUNNER_KEY_PROVIDERS: readonly ['anthropic', 'openai', 'gemini', 'mistral', 'deepseek', 'openrouter'];
3
+ export type RunnerKeyProvider = (typeof RUNNER_KEY_PROVIDERS)[number];
4
+ export type RunnerProvider = 'claude-code' | 'opencode-go' | 'opencode' | RunnerKeyProvider;
2
5
  export type RunnerPermission = 'complete' | 'chat' | 'chat:tools' | 'accounts' | 'accounts:tenant' | 'act-as-user' | 'keys';
3
6
  export type RunnerAccount = {
4
7
  provider: RunnerProvider;
@@ -11,8 +14,10 @@ export type RunnerAccount = {
11
14
  noCreditUntil?: string;
12
15
  };
13
16
  export type RunnerModels = {
17
+ /** `models`: the list a subscription serves; empty for a provider by use, which runs any model the client names. */
14
18
  providers: Array<{
15
- id: 'claude-code' | 'opencode-go';
19
+ id: RunnerProvider;
20
+ kind: 'subscription' | 'usage';
16
21
  models: string[];
17
22
  accounts: number;
18
23
  available: number;
@@ -29,7 +34,8 @@ export type RunnerTenant = {
29
34
  export type RunnerKey = {
30
35
  id: string;
31
36
  kind: 'platform' | 'project';
32
- tenant?: string;
37
+ tenant?: string; /** Platform keys: the project whose tenants (`<project>`, `<project>-…`) it owns. */
38
+ project?: string;
33
39
  name: string;
34
40
  permissions: RunnerPermission[];
35
41
  createdAt: string;
@@ -39,6 +45,8 @@ export type RunnerStatus = {
39
45
  version: string;
40
46
  agentImage: string;
41
47
  url?: string;
48
+ /** The project of the platform key asking: the tenants listed are its own only. */
49
+ project?: string;
42
50
  load: {
43
51
  chats: number;
44
52
  answering: number;
@@ -71,6 +79,7 @@ export type RunnerPairingPoll = {
71
79
  export type RunnerPairingRequestView = {
72
80
  code: string;
73
81
  name: string;
82
+ project?: string;
74
83
  from?: string;
75
84
  createdAt: string;
76
85
  expiresAt: string;
@@ -84,7 +93,7 @@ export type RunnerHealth = {
84
93
  maxChats: number;
85
94
  };
86
95
  export type RunnerCompletionRequest = {
87
- provider: 'claude-code' | 'opencode-go';
96
+ provider: RunnerProvider;
88
97
  model: string;
89
98
  prompt: string;
90
99
  effort?: 'low' | 'medium' | 'high' | 'xhigh' | 'max';
@@ -170,7 +179,8 @@ export declare class RunnerClient {
170
179
  request<T>(method: string, path: string, body?: unknown): Promise<T>;
171
180
  health(): Promise<RunnerHealth>;
172
181
  /** A pairing code (printed by the installer) → a platform key, seen once. */
173
- pair(code: string, name?: string): Promise<{
182
+ /** `project`: the platform key owns only the tenants of that project (`<project>`, `<project>-…`). */
183
+ pair(code: string, name?: string, project?: string): Promise<{
174
184
  key: string;
175
185
  record: RunnerKey;
176
186
  version: string;
@@ -179,7 +189,7 @@ export declare class RunnerClient {
179
189
  * Asks to connect (device flow): the admin of the runner approves it in the console at `approveUrl`, where the
180
190
  * same `code` is shown; meanwhile `pollPairing(request)` every `interval` seconds, until it gives the key.
181
191
  */
182
- requestPairing(name: string): Promise<RunnerPairingRequest>;
192
+ requestPairing(name: string, project?: string): Promise<RunnerPairingRequest>;
183
193
  pollPairing(request: string): Promise<RunnerPairingPoll>;
184
194
  info(): Promise<{
185
195
  version: string;
@@ -194,6 +204,8 @@ export declare class RunnerClient {
194
204
  }>;
195
205
  pairingRequests(): Promise<RunnerPairingRequestView[]>;
196
206
  answerPairing(code: string, approve: boolean): Promise<RunnerPairingRequestView>;
207
+ /** The project of a platform key (null: every tenant, as keys made before 1.2). */
208
+ setKeyProject(id: string, project: string | null): Promise<RunnerKey>;
197
209
  readonly platform: {
198
210
  status: () => Promise<RunnerStatus>;
199
211
  tenants: () => Promise<RunnerTenant[]>;
@@ -233,7 +245,8 @@ export declare class RunnerClient {
233
245
  finishClaudeLogin: (code: string, label?: string) => Promise<RunnerAccount>;
234
246
  /** A token made elsewhere with `claude setup-token`. */
235
247
  addClaudeToken: (token: string, label?: string) => Promise<RunnerAccount>;
236
- addKey: (provider: 'opencode-go' | 'opencode', key: string, label?: string) => Promise<RunnerAccount>;
248
+ /** A key: OpenCode Go/Zen, or the API key of a provider by use the runner keeps (opencode runs it). */
249
+ addKey: (provider: Exclude<RunnerProvider, 'claude-code'>, key: string, label?: string) => Promise<RunnerAccount>;
237
250
  remove: (provider: RunnerProvider, id: string) => Promise<boolean>;
238
251
  order: (provider: RunnerProvider, ids: string[]) => Promise<RunnerAccount[]>;
239
252
  };
@@ -39,7 +39,8 @@ export declare function installOverSsh(target: SshTarget, options: InstallOption
39
39
  }): Promise<InstallResult>;
40
40
  /** Installs and pairs at once: the platform key, seen once, to keep in the backend of the host. */
41
41
  export declare function installAndPair(target: SshTarget, options: InstallOptions & {
42
- name?: string;
42
+ name?: string; /** The project the platform key owns the tenants of. */
43
+ project?: string;
43
44
  onProgress?: (progress: InstallProgress) => void;
44
45
  fetch?: typeof fetch;
45
46
  }): Promise<{
@@ -1,5 +1,5 @@
1
1
  import React from 'react';
2
- import { type RunnerAccount, type RunnerClient } from '../client';
2
+ import { type RunnerAccount, type RunnerClient, type RunnerProvider } from '../client';
3
3
  import { type RunnerUiTexts } from './texts';
4
4
  export type RunnerAccountsProps = {
5
5
  /** A client for this scope: through the backend of the host for a person, with the admin token in the console. */
@@ -9,5 +9,7 @@ export type RunnerAccountsProps = {
9
9
  texts?: Partial<RunnerUiTexts>;
10
10
  /** Called after an account was added or removed (the host refreshes its list of models). */
11
11
  onChange?: (accounts: RunnerAccount[]) => void;
12
+ /** What can be added here: default the subscriptions and, for a tenant, the API keys of the providers by use too. */
13
+ providers?: RunnerProvider[];
12
14
  };
13
- export declare function RunnerAccounts({ client, scope, locale, texts, onChange }: RunnerAccountsProps): React.JSX.Element;
15
+ export declare function RunnerAccounts({ client, scope, locale, texts, onChange, providers }: RunnerAccountsProps): React.JSX.Element;
@@ -21,6 +21,9 @@ export declare const en: {
21
21
  opencodeConnect: string;
22
22
  opencodeKey: string;
23
23
  opencodeAdd: string;
24
+ keyConnect: string;
25
+ keyProvider: string;
26
+ keyLabel: string;
24
27
  termsNote: string;
25
28
  guideTitle: string;
26
29
  guideServerTitle: string;
@@ -124,6 +127,15 @@ export declare const en: {
124
127
  consoleRequestsHint: string;
125
128
  consoleRequestsEmpty: string;
126
129
  consoleRequestFrom: string;
130
+ consoleRequestProject: string;
131
+ consoleRequestAll: string;
132
+ consolePlatforms: string;
133
+ consolePlatformsHint: string;
134
+ consolePlatformsEmpty: string;
135
+ consolePlatformAll: string;
136
+ consolePlatformProject: string;
137
+ consolePlatformSave: string;
138
+ consolePlatformRevokeConfirm: string;
127
139
  consoleRequestMatch: string;
128
140
  consoleApprove: string;
129
141
  consoleDeny: string;
@@ -159,6 +171,9 @@ export declare const runnerTexts: {
159
171
  opencodeConnect: string;
160
172
  opencodeKey: string;
161
173
  opencodeAdd: string;
174
+ keyConnect: string;
175
+ keyProvider: string;
176
+ keyLabel: string;
162
177
  termsNote: string;
163
178
  guideTitle: string;
164
179
  guideServerTitle: string;
@@ -262,6 +277,15 @@ export declare const runnerTexts: {
262
277
  consoleRequestsHint: string;
263
278
  consoleRequestsEmpty: string;
264
279
  consoleRequestFrom: string;
280
+ consoleRequestProject: string;
281
+ consoleRequestAll: string;
282
+ consolePlatforms: string;
283
+ consolePlatformsHint: string;
284
+ consolePlatformsEmpty: string;
285
+ consolePlatformAll: string;
286
+ consolePlatformProject: string;
287
+ consolePlatformSave: string;
288
+ consolePlatformRevokeConfirm: string;
265
289
  consoleRequestMatch: string;
266
290
  consoleApprove: string;
267
291
  consoleDeny: string;
@@ -294,6 +318,9 @@ export declare const runnerTexts: {
294
318
  opencodeConnect: string;
295
319
  opencodeKey: string;
296
320
  opencodeAdd: string;
321
+ keyConnect: string;
322
+ keyProvider: string;
323
+ keyLabel: string;
297
324
  termsNote: string;
298
325
  guideTitle: string;
299
326
  guideServerTitle: string;
@@ -397,6 +424,15 @@ export declare const runnerTexts: {
397
424
  consoleRequestsHint: string;
398
425
  consoleRequestsEmpty: string;
399
426
  consoleRequestFrom: string;
427
+ consoleRequestProject: string;
428
+ consoleRequestAll: string;
429
+ consolePlatforms: string;
430
+ consolePlatformsHint: string;
431
+ consolePlatformsEmpty: string;
432
+ consolePlatformAll: string;
433
+ consolePlatformProject: string;
434
+ consolePlatformSave: string;
435
+ consolePlatformRevokeConfirm: string;
400
436
  consoleRequestMatch: string;
401
437
  consoleApprove: string;
402
438
  consoleDeny: string;
package/dist/ui.js CHANGED
@@ -1,4 +1,4 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,s)=>(s=n==null?{}:e(i(n)),o(r||!n||!n.__esModule||!a.call(n,`default`)?t(s,`default`,{value:n,enumerable:!0}):s,n));const c=require("./client.js"),l=require("./steps.js");let u=require("react");u=s(u,1);let d=require("@llmnative/react"),f=require("react/jsx-runtime"),p=require("react-dom");var m={accountsTitleUser:`My subscriptions`,accountsTitleTenant:`Subscriptions of the tenant`,accountsIntroUser:`Connect your own subscription: it is used only for your requests. Without one, the API keys of the workspace are used.`,accountsIntroTenant:`Accounts used by everyone of the tenant, after their own.`,accountsEmpty:`No subscription connected.`,accountsNoCredit:`Limit reached, back at {at}`,accountsConnected:`Connected {at}`,accountsRemove:`Disconnect`,accountsRemoveConfirm:`Disconnect {name}? Its token is deleted from the runner.`,claudeConnect:`Connect Claude`,claudeStep1:`Open the page of Anthropic and sign in with your Claude account (Pro or Max).`,claudeOpen:`Open the page of Anthropic`,claudeStep2:`Anthropic shows a code: paste it here.`,claudeCode:`Code`,claudeLabel:`Name (optional)`,claudeLabelPlaceholder:`Personal Max`,claudeFinish:`Connect`,claudeRefused:`Anthropic did not accept the code: start again.`,claudeNoLink:`The runner could not start the sign-in. Try again in a minute.`,opencodeConnect:`Add OpenCode Go`,opencodeKey:`API key of OpenCode Go`,opencodeAdd:`Add`,termsNote:`A Pro or Max subscription is personal: connect only your own.`,guideTitle:`Install a runner by hand`,guideServerTitle:`1. A VPS`,guideServer:`Any provider works. It needs {systems}, at least {cpus} cores, {memory} GB of memory and {disk} GB of disk, with ports {ports} open.`,guideDnsTitle:`2. The domain`,guideDns:`In the DNS of your domain, create a record A for the runner (e.g. runner.example.com) with the IP address of the VPS.`,guideDomain:`Domain of the runner`,guideCheckDns:`Check`,guideDnsOk:`The domain points to {ips}.`,guideDnsMissing:`The domain does not point anywhere yet: DNS changes can take some minutes.`,guideAccessTitle:`3. Enter the VPS`,guideAccess:`From a terminal: ssh root@<IP of the VPS>. Or open the web console of your provider.`,guideInstallTitle:`4. Run the installer`,guideInstall:`Paste this command and press Enter. It takes 3–10 minutes.`,guideVerified:`Prefer to check the script first?`,guideCopy:`Copy`,guideCopied:`Copied`,guidePairTitle:`5. Connect it`,guidePair:`At the end the installer prints a pairing code (valid 15 minutes). Paste it here.`,guideCheckHealth:`Check the runner`,guideHealthOk:`The runner {version} answers at {url}.`,guideHealthKo:`No runner answers at {url} yet: check the domain and that ports 80 and 443 are open.`,guideTroubleTitle:`If something goes wrong`,guideTrouble:`"port is used": another web server is running (stop it). "certificate": the domain does not point to the VPS yet. Run the command again at any time: nothing is lost.`,runnersTitle:`Runners`,runnersIntro:`The servers where Claude Code and opencode run. Each tenant uses one of them.`,runnersEmpty:`No runner yet.`,runnersAdd:`Add a runner`,runnersDefault:`Default for new tenants`,runnersDraining:`Draining (no new chats)`,runnersRemove:`Remove`,runnersRemoveConfirm:`Remove {name}? Its tenants must be moved first.`,runnersLoad:`{chats} of {max} chats`,runnersTenants:`{count} tenants`,runnersUnreachable:`Not reachable`,runnersVersion:`Version {version}`,distributionTitle:`Tenants`,distributionIntro:`Which runner each tenant uses. Moving a tenant asks its people to connect their subscriptions again.`,distributionRunner:`Runner`,distributionNone:`None`,addTitle:`Add a runner`,addAutomatic:`Install it for me`,addAutomaticHint:`Give the access to a new VPS: the runner is installed and connected by itself.`,addGuided:`Guide me`,addGuidedHint:`Step by step instructions to install it by hand.`,addExisting:`It is already installed`,addExistingHint:`Its address: you approve on the runner.`,addName:`Name`,addNamePlaceholder:`Runner Europe 1`,addUrl:`Address`,addCode:`Pairing code`,addConnect:`Connect`,addHost:`IP address of the VPS`,addPort:`SSH port`,addUser:`User`,addAuth:`Access`,addKey:`Private SSH key`,addLocalKey:`The SSH key of this computer`,addLocalKeyHint:`The key ~/.ssh/config gives this host (or ~/.ssh/id_ed25519), and its user when it says one: leave the user empty to take it from there.`,addPassword:`Password`,addInstall:`Install`,addInstalling:`Installing…`,addCredentialsNote:`The access is used only for this installation and is not kept.`,addBack:`Back`,addDone:`The runner is connected.`,error:`Something went wrong: {error}`,consoleTitle:`Runner console`,consoleSignIn:`Sign in`,consoleToken:`Admin token`,consoleTokenHint:`On the VPS: docker compose -f /opt/llmnative-runner/compose.yaml exec runner node src/cli.ts admin-token`,consoleSignOut:`Sign out`,consoleStatus:`Status`,consoleMachine:`{memory} GB of memory free of {total}, {cpus} cores`,consolePairing:`Connect a platform`,consolePairingHint:`A code to connect this runner to a CMS or a studio (15 minutes, once).`,consoleNewCode:`New pairing code`,consoleCode:`Code: {code} (until {at})`,consoleTenants:`Tenants`,consoleNewTenant:`New tenant`,consoleTenantId:`Id (lowercase, digits, -)`,consoleTenantName:`Name`,consoleCreate:`Create`,consoleKeys:`Keys`,consoleNewKey:`New key`,consoleKeyShown:`The key, shown this once: {key}`,consoleRevoke:`Revoke`,consoleRemoveTenant:`Remove tenant`,consoleRemoveTenantConfirm:`Remove {name}, its keys and chats?`,consoleAccounts:`Accounts`,pairNext:`Continue`,pairWaitingTitle:`Approve on the runner`,pairWaitingHint:`Open the runner and approve the request: check that it shows this same code.`,pairOpen:`Open the runner to approve`,pairWaiting:`Waiting for the approval… (until {at})`,pairDenied:`The request was refused on the runner.`,pairExpired:`The request expired: ask again.`,pairAgain:`Ask again`,pairWithCode:`I have a pairing code`,pairWithApproval:`Approve on the runner instead`,consoleRequests:`Requests to connect`,consoleRequestsHint:`A platform asked to connect to this runner. Approve only if you asked from there and the code is the one it shows.`,consoleRequestsEmpty:`No requests waiting.`,consoleRequestFrom:`{name}, from {from}, asked at {at}`,consoleRequestMatch:`The request you opened`,consoleApprove:`Approve`,consoleDeny:`Refuse`,consoleApproved:`Approved: {name} is connected.`,consoleDenied:`Refused.`,consoleRemember:`Remember on this browser`,close:`Close`,cancel:`Cancel`},h={accountsTitleUser:`I miei abbonamenti`,accountsTitleTenant:`Abbonamenti del tenant`,accountsIntroUser:`Collega il tuo abbonamento: lo usano solo le tue richieste. Senza, si usano le API key del workspace.`,accountsIntroTenant:`Account usati da tutti nel tenant, dopo i loro.`,accountsEmpty:`Nessun abbonamento collegato.`,accountsNoCredit:`Limite raggiunto, torna alle {at}`,accountsConnected:`Collegato il {at}`,accountsRemove:`Scollega`,accountsRemoveConfirm:`Scollegare {name}? Il token viene cancellato dal runner.`,claudeConnect:`Collega Claude`,claudeStep1:`Apri la pagina di Anthropic ed entra con il tuo account Claude (Pro o Max).`,claudeOpen:`Apri la pagina di Anthropic`,claudeStep2:`Anthropic mostra un codice: incollalo qui.`,claudeCode:`Codice`,claudeLabel:`Nome (facoltativo)`,claudeLabelPlaceholder:`Max personale`,claudeFinish:`Collega`,claudeRefused:`Anthropic non ha accettato il codice: ricomincia.`,claudeNoLink:`Il runner non è riuscito ad avviare l'accesso. Riprova tra un minuto.`,opencodeConnect:`Aggiungi OpenCode Go`,opencodeKey:`API key di OpenCode Go`,opencodeAdd:`Aggiungi`,termsNote:`Un abbonamento Pro o Max è personale: collega solo il tuo.`,guideTitle:`Installa un runner a mano`,guideServerTitle:`1. Una VPS`,guideServer:`Va bene qualunque fornitore. Servono {systems}, almeno {cpus} core, {memory} GB di memoria e {disk} GB di disco, con le porte {ports} aperte.`,guideDnsTitle:`2. Il dominio`,guideDns:`Nel DNS del tuo dominio crea un record A per il runner (es. runner.example.com) con l'indirizzo IP della VPS.`,guideDomain:`Dominio del runner`,guideCheckDns:`Controlla`,guideDnsOk:`Il dominio punta a {ips}.`,guideDnsMissing:`Il dominio non punta ancora da nessuna parte: le modifiche al DNS possono richiedere qualche minuto.`,guideAccessTitle:`3. Entra nella VPS`,guideAccess:`Da un terminale: ssh root@<IP della VPS>. Oppure apri la console web del fornitore.`,guideInstallTitle:`4. Lancia l'installazione`,guideInstall:`Incolla questo comando e premi Invio. Ci vogliono 3–10 minuti.`,guideVerified:`Preferisci controllare lo script prima?`,guideCopy:`Copia`,guideCopied:`Copiato`,guidePairTitle:`5. Collegalo`,guidePair:`Alla fine l'installazione stampa un codice di abbinamento (valido 15 minuti). Incollalo qui.`,guideCheckHealth:`Controlla il runner`,guideHealthOk:`Il runner {version} risponde su {url}.`,guideHealthKo:`Nessun runner risponde ancora su {url}: controlla il dominio e che le porte 80 e 443 siano aperte.`,guideTroubleTitle:`Se qualcosa non va`,guideTrouble:`"port is used": c'è già un altro server web (fermalo). "certificate": il dominio non punta ancora alla VPS. Puoi rilanciare il comando quando vuoi: non si perde niente.`,runnersTitle:`Runner`,runnersIntro:`I server dove girano Claude Code e opencode. Ogni tenant ne usa uno.`,runnersEmpty:`Nessun runner.`,runnersAdd:`Aggiungi un runner`,runnersDefault:`Predefinito per i nuovi tenant`,runnersDraining:`In svuotamento (niente chat nuove)`,runnersRemove:`Rimuovi`,runnersRemoveConfirm:`Rimuovere {name}? Prima vanno spostati i suoi tenant.`,runnersLoad:`{chats} chat su {max}`,runnersTenants:`{count} tenant`,runnersUnreachable:`Non raggiungibile`,runnersVersion:`Versione {version}`,distributionTitle:`Tenant`,distributionIntro:`Quale runner usa ogni tenant. Spostare un tenant chiede alle sue persone di ricollegare gli abbonamenti.`,distributionRunner:`Runner`,distributionNone:`Nessuno`,addTitle:`Aggiungi un runner`,addAutomatic:`Installalo tu`,addAutomaticHint:`Dai l'accesso a una VPS nuova: il runner si installa e si collega da solo.`,addGuided:`Guidami`,addGuidedHint:`Istruzioni passo passo per installarlo a mano.`,addExisting:`È già installato`,addExistingHint:`Il suo indirizzo: approvi sul runner.`,addName:`Nome`,addNamePlaceholder:`Runner Europa 1`,addUrl:`Indirizzo`,addCode:`Codice di abbinamento`,addConnect:`Collega`,addHost:`Indirizzo IP della VPS`,addPort:`Porta SSH`,addUser:`Utente`,addAuth:`Accesso`,addKey:`Chiave SSH privata`,addLocalKey:`La chiave SSH di questo computer`,addLocalKeyHint:`La chiave che ~/.ssh/config indica per questo host (o ~/.ssh/id_ed25519), e il suo utente se lo indica: lascia vuoto l'utente per prenderlo da lì.`,addPassword:`Password`,addInstall:`Installa`,addInstalling:`Installazione in corso…`,addCredentialsNote:`L'accesso serve solo per questa installazione e non viene salvato.`,addBack:`Indietro`,addDone:`Il runner è collegato.`,error:`Qualcosa è andato storto: {error}`,consoleTitle:`Console del runner`,consoleSignIn:`Entra`,consoleToken:`Token di amministrazione`,consoleTokenHint:`Sulla VPS: docker compose -f /opt/llmnative-runner/compose.yaml exec runner node src/cli.ts admin-token`,consoleSignOut:`Esci`,consoleStatus:`Stato`,consoleMachine:`{memory} GB di memoria liberi su {total}, {cpus} core`,consolePairing:`Collega una piattaforma`,consolePairingHint:`Un codice per collegare questo runner a un CMS o a uno studio (15 minuti, una volta).`,consoleNewCode:`Nuovo codice di abbinamento`,consoleCode:`Codice: {code} (fino alle {at})`,consoleTenants:`Tenant`,consoleNewTenant:`Nuovo tenant`,consoleTenantId:`Id (minuscole, cifre, -)`,consoleTenantName:`Nome`,consoleCreate:`Crea`,consoleKeys:`Chiavi`,consoleNewKey:`Nuova chiave`,consoleKeyShown:`La chiave, mostrata solo ora: {key}`,consoleRevoke:`Revoca`,consoleRemoveTenant:`Rimuovi tenant`,consoleRemoveTenantConfirm:`Rimuovere {name}, le sue chiavi e le sue chat?`,consoleAccounts:`Account`,pairNext:`Continua`,pairWaitingTitle:`Approva sul runner`,pairWaitingHint:`Apri il runner e approva la richiesta: controlla che mostri questo stesso codice.`,pairOpen:`Apri il runner per approvare`,pairWaiting:`In attesa dell'approvazione… (fino alle {at})`,pairDenied:`La richiesta è stata rifiutata sul runner.`,pairExpired:`La richiesta è scaduta: chiedi di nuovo.`,pairAgain:`Chiedi di nuovo`,pairWithCode:`Ho un codice di abbinamento`,pairWithApproval:`Approva sul runner invece`,consoleRequests:`Richieste di collegamento`,consoleRequestsHint:`Una piattaforma ha chiesto di collegarsi a questo runner. Approva solo se l'hai chiesto tu da lì e il codice è quello che mostra.`,consoleRequestsEmpty:`Nessuna richiesta in attesa.`,consoleRequestFrom:`{name}, da {from}, alle {at}`,consoleRequestMatch:`La richiesta che hai aperto`,consoleApprove:`Approva`,consoleDeny:`Rifiuta`,consoleApproved:`Approvata: {name} è collegato.`,consoleDenied:`Rifiutata.`,consoleRemember:`Ricorda su questo browser`,close:`Chiudi`,cancel:`Annulla`},g={en:m,it:h};function _(e,t){let n=e&&e.toLowerCase().startsWith(`it`)?h:m;return t?{...n,...t}:n}var v=(e,t)=>e.replace(/\{(\w+)\}/g,(e,n)=>n in t?String(t[n]):e),y={"claude-code":`Claude Code`,"opencode-go":`OpenCode Go`,opencode:`OpenCode Zen`},b=e=>new Date(e).toLocaleString(void 0,{dateStyle:`medium`,timeStyle:`short`});function x({client:e,scope:t,locale:n,texts:r,onChange:i}){let a=_(n,r),[o,s]=(0,u.useState)(null),[l,p]=(0,u.useState)(null),[m,h]=(0,u.useState)(null),[g,x]=(0,u.useState)(null),w=(0,u.useCallback)(async()=>{try{let{accounts:t}=await e.accounts.list();return s(t),p(null),t}catch(e){return p(e instanceof c.RunnerError?e.code:String(e)),s([]),[]}},[e]);(0,u.useEffect)(()=>{w()},[w]);let T=async()=>{h(null);let e=await w();i?.(e)};return(0,f.jsxs)(d.Card,{title:t===`user`?a.accountsTitleUser:a.accountsTitleTenant,loading:o===null,loaderMinHeight:120,children:[(0,f.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[(0,f.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:t===`user`?a.accountsIntroUser:a.accountsIntroTenant}),l&&(0,f.jsx)(d.Alert,{variant:`danger`,children:v(a.error,{error:l})}),o?.length===0&&!l&&(0,f.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:a.accountsEmpty}),o?.map(e=>(0,f.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 rounded-md border border-border p-3`,children:[(0,f.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,f.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,f.jsx)(`span`,{className:`font-medium`,children:e.label??y[e.provider]??e.provider}),(0,f.jsx)(d.Badge,{variant:`secondary`,children:y[e.provider]??e.provider}),e.noCreditUntil&&(0,f.jsx)(d.Badge,{variant:`warning`,children:v(a.accountsNoCredit,{at:b(e.noCreditUntil)})})]}),(0,f.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:v(a.accountsConnected,{at:b(e.at)})})]}),(0,f.jsx)(d.ActionButton,{icon:`unlink`,label:a.accountsRemove,variant:`outline-danger`,onClick:()=>x(e)})]},`${e.provider}/${e.id}`)),m===`claude`&&(0,f.jsx)(S,{client:e,t:a,onDone:T,onCancel:()=>h(null)}),m===`opencode`&&(0,f.jsx)(C,{client:e,t:a,onDone:T,onCancel:()=>h(null)}),!m&&(0,f.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,f.jsx)(d.ActionButton,{icon:`plus`,label:a.claudeConnect,variant:`primary`,onClick:()=>h(`claude`)}),(0,f.jsx)(d.ActionButton,{icon:`plus`,label:a.opencodeConnect,variant:`outline-secondary`,onClick:()=>h(`opencode`)})]}),(0,f.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:a.termsNote})]}),g&&(0,f.jsx)(d.ModalYesNo,{title:a.accountsRemove,danger:!0,onClose:()=>x(null),onYes:async()=>(await e.accounts.remove(g.provider,g.id).catch(()=>!1),x(null),await T(),!0),children:v(a.accountsRemoveConfirm,{name:g.label??y[g.provider]??g.provider})})]})}function S({client:e,t,onDone:n,onCancel:r}){let[i,a]=(0,u.useState)(null),[o,s]=(0,u.useState)(``),[l,p]=(0,u.useState)(``),[m,h]=(0,u.useState)(null);return(0,u.useEffect)(()=>{let n=!1;return e.accounts.startClaudeLogin().then(({url:e})=>!n&&a(e)).catch(()=>!n&&h(t.claudeNoLink)),()=>{n=!0}},[e,t]),(0,f.jsxs)(`div`,{className:`flex flex-col gap-3 rounded-md border border-border p-3`,children:[m&&(0,f.jsx)(d.Alert,{variant:`danger`,children:m}),(0,f.jsx)(`p`,{className:`text-sm`,children:t.claudeStep1}),(0,f.jsx)(`div`,{children:(0,f.jsx)(d.ActionButton,{icon:`external-link`,label:t.claudeOpen,variant:`primary`,disabled:!i,onClick:()=>i&&window.open(i,`_blank`,`noopener,noreferrer`)})}),(0,f.jsx)(`p`,{className:`text-sm`,children:t.claudeStep2}),(0,f.jsxs)(d.Form,{appearance:`empty`,showNotice:!1,onSubmit:()=>!1,children:[(0,f.jsx)(d.String,{name:`code`,label:t.claudeCode,autoComplete:`off`,onChange:({value:e})=>s(String(e??``))}),(0,f.jsx)(d.String,{name:`label`,label:t.claudeLabel,placeholder:t.claudeLabelPlaceholder,onChange:({value:e})=>p(String(e??``))})]}),(0,f.jsxs)(`div`,{className:`flex gap-2`,children:[(0,f.jsx)(d.LoadingButton,{label:t.claudeFinish,variant:`primary`,disabled:!i||!o.trim(),onClick:async()=>{try{await e.accounts.finishClaudeLogin(o.trim(),l.trim()||void 0),n()}catch(e){h(e instanceof c.RunnerError&&e.code===`refused`?t.claudeRefused:v(t.error,{error:e instanceof c.RunnerError?e.code:String(e)}))}}}),(0,f.jsx)(d.ActionButton,{label:t.cancel,variant:`outline-secondary`,onClick:r})]})]})}function C({client:e,t,onDone:n,onCancel:r}){let[i,a]=(0,u.useState)(``),[o,s]=(0,u.useState)(``),[l,p]=(0,u.useState)(null);return(0,f.jsxs)(`div`,{className:`flex flex-col gap-3 rounded-md border border-border p-3`,children:[l&&(0,f.jsx)(d.Alert,{variant:`danger`,children:l}),(0,f.jsxs)(d.Form,{appearance:`empty`,showNotice:!1,onSubmit:()=>!1,children:[(0,f.jsx)(d.Password,{name:`key`,label:t.opencodeKey,autoComplete:`off`,onChange:({value:e})=>a(String(e??``))}),(0,f.jsx)(d.String,{name:`label`,label:t.claudeLabel,onChange:({value:e})=>s(String(e??``))})]}),(0,f.jsxs)(`div`,{className:`flex gap-2`,children:[(0,f.jsx)(d.LoadingButton,{label:t.opencodeAdd,variant:`primary`,disabled:!i.trim(),onClick:async()=>{try{await e.accounts.addKey(`opencode-go`,i.trim(),o.trim()||void 0),n()}catch(e){p(v(t.error,{error:e instanceof c.RunnerError?e.code:String(e)}))}}}),(0,f.jsx)(d.ActionButton,{label:t.cancel,variant:`outline-secondary`,onClick:r})]})]})}function w({title:e,children:t,done:n}){return(0,f.jsxs)(`section`,{className:`flex flex-col gap-2 border-l-2 border-border pl-4`,children:[(0,f.jsxs)(`h4`,{className:`flex items-center gap-2 text-sm font-semibold`,children:[e,n&&(0,f.jsx)(d.Badge,{variant:`success`,children:`✓`})]}),t]})}function T({locale:e,texts:t,onPair:n,lookup:r=e=>l.lookupDomain(e),check:i=l.checkRunner,version:a}){let o=_(e,t),[s,c]=(0,u.useState)(``),[p,m]=(0,u.useState)(null),[h,g]=(0,u.useState)(null),[y,b]=(0,u.useState)(``),[x,S]=(0,u.useState)(!1),[C,T]=(0,u.useState)(null),E=l.isDomain(s),D=`https://${s.trim().toLowerCase()}`,O=l.RUNNER_REQUIREMENTS;return(0,f.jsxs)(`div`,{className:`flex flex-col gap-5`,children:[(0,f.jsx)(w,{title:o.guideServerTitle,children:(0,f.jsx)(`p`,{className:`text-sm`,children:v(o.guideServer,{systems:O.systems.join(`, `),cpus:O.cpus,memory:O.memoryGb,disk:O.diskGb,ports:O.ports.join(`, `)})})}),(0,f.jsxs)(w,{title:o.guideDnsTitle,done:!!p?.ips.length,children:[(0,f.jsx)(`p`,{className:`text-sm`,children:o.guideDns}),(0,f.jsx)(d.Form,{appearance:`empty`,showNotice:!1,onSubmit:()=>!1,children:(0,f.jsx)(d.String,{name:`domain`,label:o.guideDomain,placeholder:`runner.example.com`,autoComplete:`off`,onChange:({value:e})=>{c(String(e??``)),m(null),g(null)}})}),(0,f.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,f.jsx)(d.LoadingButton,{label:o.guideCheckDns,variant:`outline-secondary`,disabled:!E,onClick:async()=>m({ips:await r(s.trim().toLowerCase()).catch(()=>[])})}),p&&(p.ips.length?(0,f.jsx)(d.Alert,{variant:`success`,appearance:`text`,children:v(o.guideDnsOk,{ips:p.ips.join(`, `)})}):(0,f.jsx)(d.Alert,{variant:`warning`,appearance:`text`,children:o.guideDnsMissing}))]})]}),(0,f.jsx)(w,{title:o.guideAccessTitle,children:(0,f.jsx)(`p`,{className:`text-sm`,children:o.guideAccess})}),(0,f.jsxs)(w,{title:o.guideInstallTitle,children:[(0,f.jsx)(`p`,{className:`text-sm`,children:o.guideInstall}),(0,f.jsx)(d.Code,{language:`bash`,showCopy:!0,children:l.installCommand({domain:E?s:`runner.example.com`,...a?{version:a}:{}})}),(0,f.jsx)(`div`,{children:(0,f.jsx)(d.ActionButton,{label:o.guideVerified,variant:`link`,onClick:()=>S(e=>!e)})}),x&&(0,f.jsx)(d.Code,{language:`bash`,showCopy:!0,children:l.verifiedInstallCommands({domain:E?s:`runner.example.com`,...a?{version:a}:{}}).join(`
2
- `)})]}),(0,f.jsxs)(w,{title:o.guidePairTitle,done:h?.ok,children:[(0,f.jsx)(`p`,{className:`text-sm`,children:o.guidePair}),(0,f.jsx)(d.Form,{appearance:`empty`,showNotice:!1,onSubmit:()=>!1,children:(0,f.jsx)(d.String,{name:`code`,label:o.addCode,placeholder:`ABCD-EFGH`,autoComplete:`off`,onChange:({value:e})=>b(String(e??``))})}),h&&(0,f.jsx)(d.Alert,{variant:h.ok?`success`:`warning`,appearance:`text`,children:h.text}),C&&(0,f.jsx)(d.Alert,{variant:`danger`,children:C}),(0,f.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,f.jsx)(d.LoadingButton,{label:o.guideCheckHealth,variant:`outline-secondary`,disabled:!E,onClick:async()=>{let e=await i(D);g(e.ok?{ok:!0,text:v(o.guideHealthOk,{version:e.version,url:D})}:{ok:!1,text:v(o.guideHealthKo,{url:D})})}}),(0,f.jsx)(d.LoadingButton,{label:o.addConnect,variant:`primary`,disabled:!E||y.trim().length<8,onClick:async()=>{try{T(null),await n({url:D,code:y.trim()})}catch(e){T(v(o.error,{error:e.message}))}}})]})]}),(0,f.jsx)(w,{title:o.guideTroubleTitle,children:(0,f.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:o.guideTrouble})})]})}function E({fleet:e,locale:t,texts:n}){let r=_(t,n),[i,a]=(0,u.useState)(null),[o,s]=(0,u.useState)(null),[c,l]=(0,u.useState)(!1),[p,m]=(0,u.useState)(null),[h,g]=(0,u.useState)(null),y=(0,u.useCallback)(async()=>{try{let t=await e.list();a(t);let n=await Promise.all(t.map(t=>e.status(t.id).catch(()=>null)));a(t.map((e,t)=>({...e,status:n[t]}))),e.tenants&&s(await e.tenants.list())}catch(e){g(v(r.error,{error:e.message})),a([])}},[e,r]);(0,u.useEffect)(()=>{y()},[y]);let b=async(t,n)=>{await e.update(t,n),await y()};return(0,f.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,f.jsx)(d.Card,{header:(0,f.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,f.jsx)(`h3`,{className:`flex-1 text-base font-semibold`,children:r.runnersTitle}),(0,f.jsx)(d.ActionButton,{icon:`plus`,label:r.runnersAdd,variant:`primary`,onClick:()=>l(!0)})]}),loading:i===null,loaderMinHeight:120,children:(0,f.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[(0,f.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:r.runnersIntro}),h&&(0,f.jsx)(d.Alert,{variant:`danger`,children:h}),i?.length===0&&(0,f.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:r.runnersEmpty}),i?.map(e=>(0,f.jsxs)(`div`,{className:`flex flex-col gap-2 rounded-md border border-border p-3`,children:[(0,f.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,f.jsx)(`span`,{className:`font-medium`,children:e.name}),(0,f.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:e.url}),e.status===null&&(0,f.jsx)(d.Badge,{variant:`danger`,children:r.runnersUnreachable}),e.status&&(0,f.jsx)(d.Badge,{variant:`secondary`,children:v(r.runnersVersion,{version:e.status.version})}),e.status&&(0,f.jsx)(d.Badge,{variant:`info`,children:v(r.runnersLoad,{chats:e.status.load.chats,max:e.status.load.maxChats})}),e.status&&(0,f.jsx)(d.Badge,{variant:`light`,children:v(r.runnersTenants,{count:e.status.tenants.length})}),(0,f.jsx)(`div`,{className:`ml-auto`,children:(0,f.jsx)(d.ActionButton,{icon:`trash`,label:r.runnersRemove,variant:`outline-danger`,onClick:()=>m(e)})})]}),(0,f.jsx)(d.Form,{appearance:`empty`,showNotice:!1,onSubmit:()=>!1,defaultValues:{isDefault:e.isDefault?`true`:``,draining:e.draining?`true`:``},children:(0,f.jsxs)(`div`,{className:`flex flex-wrap gap-4`,children:[(0,f.jsx)(d.Switch,{name:`isDefault`,label:r.runnersDefault,valueChecked:`true`,onChange:({value:t})=>void b(e.id,{isDefault:!!t})}),(0,f.jsx)(d.Switch,{name:`draining`,label:r.runnersDraining,valueChecked:`true`,onChange:({value:t})=>void b(e.id,{draining:!!t})})]})})]},e.id))]})}),e.tenants&&i&&i.length>0&&(0,f.jsx)(d.Card,{title:r.distributionTitle,loading:o===null,loaderMinHeight:80,children:(0,f.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,f.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:r.distributionIntro}),(0,f.jsx)(d.Form,{appearance:`empty`,showNotice:!1,onSubmit:()=>!1,defaultValues:Object.fromEntries((o??[]).map(e=>[`runner_${e.id}`,e.runnerId??``])),children:(o??[]).map(t=>(0,f.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,f.jsx)(`span`,{className:`min-w-40 flex-1 text-sm`,children:t.name}),(0,f.jsx)(d.Select,{name:`runner_${t.id}`,title:r.distributionRunner,placeholderOption:{label:r.distributionNone,value:``},options:i.map(e=>({label:e.name,value:e.id})),onChange:({value:n})=>{n&&e.tenants.assign(t.id,String(n)).then(y)}})]},t.id))})]})}),c&&(0,f.jsx)(k,{fleet:e,t:r,locale:t,onClose:()=>l(!1),onAdded:async()=>{l(!1),await y()}}),p&&(0,f.jsx)(d.ModalYesNo,{title:r.runnersRemove,danger:!0,onClose:()=>m(null),onYes:async()=>(await e.remove(p.id).catch(e=>g(v(r.error,{error:e.message}))),m(null),await y(),!0),children:v(r.runnersRemoveConfirm,{name:p.name})})]})}function D({target:e,children:t}){return e?(0,p.createPortal)(t,e):null}var O=e=>{try{return new URL(e).hostname}catch{return e}};function k({fleet:e,t,locale:n,onClose:r,onAdded:i}){let[a,o]=(0,u.useState)(`choose`),[s,c]=(0,u.useState)(null),[l,p]=(0,u.useState)(null),m=(0,u.useCallback)(e=>c(v(t.error,{error:e.message})),[t]);return(0,f.jsx)(d.Modal,{title:t.addTitle,size:`lg`,onClose:r,footer:a===`choose`||a===`guided`?!1:(0,f.jsx)(`div`,{ref:p,className:`flex w-full flex-wrap items-center justify-end gap-3`}),children:(0,f.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[s&&(0,f.jsx)(d.Alert,{variant:`danger`,children:s}),a===`choose`&&(0,f.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-3`,children:[e.install&&(0,f.jsx)(A,{title:t.addAutomatic,hint:t.addAutomaticHint,onClick:()=>o(`automatic`)}),(0,f.jsx)(A,{title:t.addGuided,hint:t.addGuidedHint,onClick:()=>o(`guided`)}),(0,f.jsx)(A,{title:t.addExisting,hint:t.addExistingHint,onClick:()=>o(`existing`)})]}),a!==`choose`&&(0,f.jsx)(`div`,{children:(0,f.jsx)(d.ActionButton,{icon:`arrow-left`,label:t.addBack,variant:`link`,onClick:()=>{o(`choose`),c(null)}})}),a===`automatic`&&e.install&&(0,f.jsx)(I,{t,footer:l,localKeys:!!e.localKeys,install:(t,n,r)=>e.install({name:t,domain:t,access:n},r),onDone:i,onError:m}),a===`guided`&&(0,f.jsx)(T,{locale:n,texts:t,onPair:async({url:t,code:n})=>{await i(await e.add({name:O(t),url:t,code:n}))}}),a===`existing`&&(0,f.jsx)(P,{t,footer:l,pairing:e.startPairing&&e.pairingStatus?{start:e.startPairing.bind(e),status:e.pairingStatus.bind(e)}:void 0,onAdded:i,onError:m,onClearError:()=>c(null),onConnect:async(t,n)=>{try{await i(await e.add({name:O(t),url:t,code:n}))}catch(e){m(e)}}})]})})}function A({title:e,hint:t,onClick:n}){return(0,f.jsxs)(`button`,{type:`button`,onClick:n,className:`rounded-lg border border-border p-4 text-left transition-colors hover:border-primary hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring`,children:[(0,f.jsx)(`span`,{className:`block font-medium`,children:e}),(0,f.jsx)(`span`,{className:`mt-1 block text-sm text-muted-foreground`,children:t})]})}var j=e=>(/^https?:\/\//.test(e.trim())?e.trim():`https://${e.trim()}`).replace(/\/+$/,``),M=e=>new Date(e).toLocaleTimeString(void 0,{hour:`2-digit`,minute:`2-digit`}),N=5;function P({t:e,footer:t,pairing:n,onAdded:r,onError:i,onClearError:a,onConnect:o}){let[s,c]=(0,u.useState)(``),[l,p]=(0,u.useState)(``),[m,h]=(0,u.useState)(!n),[g,_]=(0,u.useState)(null),[y,b]=(0,u.useState)(null);return(0,u.useEffect)(()=>{if(!g||!n)return;let e=!1,t=0,a,o=async()=>{try{let i=await n.status(g.id);if(t=0,e)return;if(i.status===`approved`){await r(i.runner);return}if(i.status!==`pending`){b(i.status),_(null);return}}catch(n){t+=1,!e&&t>=N&&i(n)}e||(a=setTimeout(()=>void o(),2e3))};return a=setTimeout(()=>void o(),2e3),()=>{e=!0,clearTimeout(a)}},[g,n,r,i]),g?(0,f.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[(0,f.jsx)(`h4`,{className:`font-semibold`,children:e.pairWaitingTitle}),(0,f.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:e.pairWaitingHint}),(0,f.jsx)(`div`,{className:`rounded-lg border border-border p-4 text-center font-mono text-3xl font-semibold tracking-widest`,children:g.code}),(0,f.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:v(e.pairWaiting,{at:M(g.expiresAt)})}),(0,f.jsx)(D,{target:t,children:(0,f.jsx)(d.ActionButton,{icon:`external-link`,label:e.pairOpen,variant:`primary`,onClick:()=>window.open(g.approveUrl,`_blank`,`noopener`)})})]}):(0,f.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[y&&(0,f.jsx)(d.Alert,{variant:y===`denied`?`danger`:`warning`,children:y===`denied`?e.pairDenied:e.pairExpired}),(0,f.jsxs)(d.Form,{appearance:`empty`,showNotice:!1,onSubmit:()=>!1,defaultValues:{url:s,code:l},children:[(0,f.jsx)(d.String,{name:`url`,label:e.addUrl,placeholder:`https://runner.example.com`,onChange:({value:e})=>c(String(e??``))}),m&&(0,f.jsx)(d.String,{name:`code`,label:e.addCode,placeholder:`ABCD-EFGH`,autoComplete:`off`,onChange:({value:e})=>p(String(e??``))})]}),(0,f.jsxs)(D,{target:t,children:[n&&(0,f.jsx)(d.ActionButton,{label:m?e.pairWithApproval:e.pairWithCode,variant:`link`,onClick:()=>h(e=>!e)}),m?(0,f.jsx)(d.LoadingButton,{label:e.addConnect,variant:`primary`,disabled:!s.trim()||l.trim().length<8,onClick:()=>o(j(s),l.trim())}):(0,f.jsx)(d.LoadingButton,{label:y?e.pairAgain:e.pairNext,variant:`primary`,disabled:!s.trim(),onClick:async()=>{b(null),a();try{let e=j(s);_(await n.start({name:O(e),url:e}))}catch(e){i(e)}}})]})]})}var F=[`check`,`docker`,`files`,`start`,`agent`,`health`,`pair`,`tls`,`done`];function I({t:e,footer:t,localKeys:n,install:r,onDone:i,onError:a}){let[o,s]=(0,u.useState)({host:``,port:`22`,username:n?``:`root`,auth:n?`local`:`key`,privateKey:``,password:``,domain:``}),[c,l]=(0,u.useState)([]),[p,m]=(0,u.useState)(null),[h,g]=(0,u.useState)(!1),_=e=>({value:t})=>s(n=>({...n,[e]:String(t??``)})),v=o.host.trim()&&o.domain.trim()&&(o.auth===`local`||o.username.trim())&&(o.auth===`local`||(o.auth===`key`?o.privateKey.trim():o.password));return(0,f.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[!h&&(0,f.jsxs)(d.Form,{appearance:`empty`,showNotice:!1,onSubmit:()=>!1,defaultValues:o,children:[(0,f.jsx)(d.String,{name:`domain`,label:e.guideDomain,placeholder:`runner.example.com`,onChange:_(`domain`)}),(0,f.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-3`,children:[(0,f.jsx)(d.String,{name:`host`,label:e.addHost,placeholder:`203.0.113.10`,onChange:_(`host`)}),(0,f.jsx)(d.String,{name:`port`,label:e.addPort,onChange:_(`port`)}),(0,f.jsx)(d.String,{name:`username`,label:e.addUser,onChange:_(`username`)})]}),(0,f.jsx)(d.Select,{name:`auth`,label:e.addAuth,options:[...n?[{label:e.addLocalKey,value:`local`}]:[],{label:e.addKey,value:`key`},{label:e.addPassword,value:`password`}],onChange:_(`auth`)}),o.auth===`local`&&(0,f.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:e.addLocalKeyHint}),o.auth===`local`?null:o.auth===`key`?(0,f.jsx)(d.TextArea,{name:`privateKey`,label:e.addKey,placeholder:`-----BEGIN OPENSSH PRIVATE KEY-----`,onChange:_(`privateKey`)}):(0,f.jsx)(d.Password,{name:`password`,label:e.addPassword,autoComplete:`off`,onChange:_(`password`)})]}),(0,f.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:e.addCredentialsNote}),h&&(0,f.jsx)(`div`,{className:`flex flex-wrap gap-1`,children:F.map(e=>(0,f.jsx)(d.Badge,{variant:p===e?`primary`:F.indexOf(e)<F.indexOf(p??`check`)?`success`:`light`,children:e},e))}),c.length>0&&(0,f.jsx)(`pre`,{className:`max-h-64 overflow-auto rounded-md bg-muted p-2 text-xs`,children:c.slice(-200).join(`
3
- `)}),(0,f.jsx)(D,{target:t,children:(0,f.jsx)(d.LoadingButton,{label:h?e.addInstalling:e.addInstall,variant:`primary`,disabled:!v||h,onClick:async()=>{g(!0),l([]);try{await i(await r(o.domain.trim().toLowerCase(),{host:o.host.trim(),port:Number(o.port)||22,username:o.username.trim(),...o.auth===`key`?{privateKey:o.privateKey}:o.auth===`password`?{password:o.password}:{}},({line:e,phase:t})=>{t&&m(t),/^[A-Z_]+=/.test(e)||l(t=>[...t,e])}))}catch(e){a(e)}finally{g(!1)}}})})]})}var L=e=>(e/1024**3).toFixed(1),R=e=>new Date(e).toLocaleString(void 0,{dateStyle:`short`,timeStyle:`short`});function z({client:e,locale:t,texts:n,onSignOut:r,approve:i}){let a=_(t,n),[o,s]=(0,u.useState)(null),[l,p]=(0,u.useState)(null),[m,h]=(0,u.useState)(null),[g,y]=(0,u.useState)({id:``,name:``}),[b,x]=(0,u.useState)(null),S=(0,u.useCallback)(async()=>{try{s(await e.platform.status()),p(null)}catch(e){p(v(a.error,{error:e instanceof c.RunnerError?e.code:String(e)}))}},[e,a]);return(0,u.useEffect)(()=>{S()},[S]),(0,f.jsxs)(`div`,{className:`mx-auto flex max-w-4xl flex-col gap-4 p-4`,children:[(0,f.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,f.jsx)(`h1`,{className:`flex-1 text-xl font-semibold`,children:a.consoleTitle}),r&&(0,f.jsx)(d.ActionButton,{icon:`log-out`,label:a.consoleSignOut,variant:`outline-secondary`,onClick:r})]}),l&&(0,f.jsx)(d.Alert,{variant:`danger`,children:l}),(0,f.jsx)(H,{client:e,t:a,approve:i,onAnswered:S}),(0,f.jsx)(d.Card,{title:a.consoleStatus,loading:!o&&!l,loaderMinHeight:100,children:o&&(0,f.jsx)(d.DescriptionList,{items:[{label:`Version`,value:o.version},{label:`URL`,value:o.url},{label:`Chats`,value:`${o.load.chats} / ${o.load.maxChats}`},{label:`Machine`,value:v(a.consoleMachine,{memory:L(o.machine.availableBytes),total:L(o.machine.totalBytes),cpus:o.machine.cpus})},{label:`Agent`,value:o.agentImage}]})}),(0,f.jsx)(d.Card,{title:a.consolePairing,children:(0,f.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,f.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:a.consolePairingHint}),m&&(0,f.jsx)(d.Code,{showCopy:!0,children:m.code}),m&&(0,f.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:v(a.consoleCode,{code:m.code,at:R(m.expiresAt)})}),(0,f.jsx)(`div`,{children:(0,f.jsx)(d.LoadingButton,{label:a.consoleNewCode,variant:`outline-primary`,onClick:async()=>h(await e.createPairing())})})]})}),(0,f.jsx)(d.Card,{title:a.consoleTenants,children:(0,f.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[b&&(0,f.jsx)(d.Alert,{variant:`warning`,onClose:()=>x(null),children:(0,f.jsx)(`span`,{className:`break-all`,children:v(a.consoleKeyShown,{key:b})})}),o?.tenants.map(n=>(0,f.jsx)(B,{client:e,tenant:n,t:a,locale:t,onKey:x,onChange:S},n.id)),(0,f.jsx)(d.Form,{appearance:`empty`,showNotice:!1,onSubmit:()=>!1,children:(0,f.jsxs)(`div`,{className:`grid gap-2 sm:grid-cols-[1fr_1fr_auto] sm:items-end`,children:[(0,f.jsx)(d.String,{name:`tenantId`,label:a.consoleTenantId,placeholder:`acme`,onChange:({value:e})=>y(t=>({...t,id:String(e??``)}))}),(0,f.jsx)(d.String,{name:`tenantName`,label:a.consoleTenantName,placeholder:`Acme`,onChange:({value:e})=>y(t=>({...t,name:String(e??``)}))}),(0,f.jsx)(d.LoadingButton,{label:a.consoleCreate,variant:`primary`,disabled:!/^[a-z0-9][a-z0-9-]{0,62}$/.test(g.id),onClick:async()=>{try{let t=await e.platform.createTenant(g.id,{name:g.name||void 0});t.key&&x(t.key),await S()}catch(e){p(v(a.error,{error:e instanceof c.RunnerError?e.code:String(e)}))}}})]})})]})})]})}function B({client:e,tenant:t,t:n,locale:r,onKey:i,onChange:a}){let[o,s]=(0,u.useState)(!1),[c,l]=(0,u.useState)(null),[p,m]=(0,u.useState)(!1),h=(0,u.useMemo)(()=>e.as({tenant:t.id}),[e,t.id]),g=(0,u.useCallback)(async()=>l(await e.platform.keys(t.id)),[e,t.id]);return(0,u.useEffect)(()=>{o&&g()},[o,g]),(0,f.jsxs)(`div`,{className:`rounded-md border border-border p-3`,children:[(0,f.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,f.jsxs)(`button`,{type:`button`,className:`flex-1 text-left font-medium`,onClick:()=>s(e=>!e),children:[t.name,` `,(0,f.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[`(`,t.id,`)`]})]}),t.usersWithAccounts!==void 0&&(0,f.jsxs)(d.Badge,{variant:`light`,children:[t.usersWithAccounts,` 👤`]}),(0,f.jsx)(d.ActionButton,{icon:`trash`,label:n.consoleRemoveTenant,variant:`outline-danger`,onClick:()=>m(!0)})]}),o&&(0,f.jsxs)(`div`,{className:`mt-3 flex flex-col gap-3`,children:[(0,f.jsx)(`h4`,{className:`text-sm font-semibold`,children:n.consoleKeys}),c?.map(r=>(0,f.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 text-sm`,children:[(0,f.jsx)(`span`,{className:`flex-1`,children:r.name}),r.permissions.map(e=>(0,f.jsx)(d.Badge,{variant:`info`,children:e},e)),(0,f.jsx)(d.ActionButton,{label:n.consoleRevoke,variant:`outline-danger`,onClick:async()=>{await e.platform.revokeKey(t.id,r.id),await g()}})]},r.id)),(0,f.jsx)(`div`,{children:(0,f.jsx)(d.LoadingButton,{label:n.consoleNewKey,variant:`outline-secondary`,onClick:async()=>{i((await e.platform.createKey(t.id,{name:`console`,permissions:[`complete`,`chat`,`chat:tools`,`accounts`,`act-as-user`]})).key),await g()}})}),(0,f.jsx)(`h4`,{className:`text-sm font-semibold`,children:n.consoleAccounts}),(0,f.jsx)(x,{client:h,scope:`tenant`,locale:r,texts:n})]}),p&&(0,f.jsx)(d.ModalYesNo,{title:n.consoleRemoveTenant,danger:!0,onClose:()=>m(!1),onYes:async()=>(await e.platform.removeTenant(t.id),m(!1),await a(),!0),children:v(n.consoleRemoveTenantConfirm,{name:t.name})})]})}var V=e=>e.toUpperCase().replace(/[^A-Z0-9]/g,``);function H({client:e,t,approve:n,onAnswered:r}){let[i,a]=(0,u.useState)(null),[o,s]=(0,u.useState)(null),c=(0,u.useCallback)(async()=>{try{let t=await e.pairingRequests(),r=n?V(n):``;a([...t].sort((e,t)=>Number(V(t.code)===r)-Number(V(e.code)===r)))}catch{a([])}},[e,n]);return(0,u.useEffect)(()=>{c();let e=setInterval(()=>void c(),5e3);return()=>clearInterval(e)},[c]),!n&&!i?.length&&!o?null:(0,f.jsx)(d.Card,{title:t.consoleRequests,loading:i===null,loaderMinHeight:80,children:(0,f.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[(0,f.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:t.consoleRequestsHint}),o&&(0,f.jsx)(d.Alert,{variant:o.variant,children:o.text}),i?.length===0&&!o&&(0,f.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:t.consoleRequestsEmpty}),i?.map(i=>{let a=!!n&&V(i.code)===V(n),o=async n=>{let a=await e.answerPairing(i.code,n);s(n?{variant:`success`,text:v(t.consoleApproved,{name:a.name})}:{variant:`info`,text:t.consoleDenied}),await c(),await r()};return(0,f.jsxs)(`div`,{className:`flex flex-col gap-2 rounded-md border p-3 ${a?`border-primary`:`border-border`}`,children:[a&&(0,f.jsx)(d.Badge,{variant:`primary`,children:t.consoleRequestMatch}),(0,f.jsx)(`div`,{className:`font-mono text-2xl font-semibold tracking-widest`,children:i.code}),(0,f.jsx)(`p`,{className:`text-sm`,children:v(t.consoleRequestFrom,{name:i.name,from:i.from??`?`,at:R(i.createdAt)})}),(0,f.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,f.jsx)(d.LoadingButton,{label:t.consoleApprove,variant:`primary`,onClick:()=>o(!0)}),(0,f.jsx)(d.LoadingButton,{label:t.consoleDeny,variant:`outline-danger`,onClick:()=>o(!1)})]})]},i.code)})]})})}exports.AddRunner=k,exports.InstallGuide=T,exports.RunnerAccounts=x,exports.RunnerConsole=z,exports.RunnersSettings=E,exports.fill=v,exports.runnerTexts=g,exports.textsFor=_;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,s)=>(s=n==null?{}:e(i(n)),o(r||!n||!n.__esModule||!a.call(n,`default`)?t(s,`default`,{value:n,enumerable:!0}):s,n));const c=require("./client.js"),l=require("./steps.js");let u=require("react");u=s(u,1);let d=require("@llmnative/react"),f=require("react/jsx-runtime"),p=require("react-dom");var m={accountsTitleUser:`My subscriptions`,accountsTitleTenant:`Subscriptions of the tenant`,accountsIntroUser:`Connect your own subscription: it is used only for your requests. Without one, the API keys of the workspace are used.`,accountsIntroTenant:`Accounts used by everyone of the tenant, after their own.`,accountsEmpty:`No subscription connected.`,accountsNoCredit:`Limit reached, back at {at}`,accountsConnected:`Connected {at}`,accountsRemove:`Disconnect`,accountsRemoveConfirm:`Disconnect {name}? Its token is deleted from the runner.`,claudeConnect:`Connect Claude`,claudeStep1:`Open the page of Anthropic and sign in with your Claude account (Pro or Max).`,claudeOpen:`Open the page of Anthropic`,claudeStep2:`Anthropic shows a code: paste it here.`,claudeCode:`Code`,claudeLabel:`Name (optional)`,claudeLabelPlaceholder:`Personal Max`,claudeFinish:`Connect`,claudeRefused:`Anthropic did not accept the code: start again.`,claudeNoLink:`The runner could not start the sign-in. Try again in a minute.`,opencodeConnect:`Add OpenCode Go`,opencodeKey:`API key of OpenCode Go`,opencodeAdd:`Add`,keyConnect:`Add a key`,keyProvider:`Provider`,keyLabel:`API key of {provider}`,termsNote:`A Pro or Max subscription is personal: connect only your own.`,guideTitle:`Install a runner by hand`,guideServerTitle:`1. A VPS`,guideServer:`Any provider works. It needs {systems}, at least {cpus} cores, {memory} GB of memory and {disk} GB of disk, with ports {ports} open.`,guideDnsTitle:`2. The domain`,guideDns:`In the DNS of your domain, create a record A for the runner (e.g. runner.example.com) with the IP address of the VPS.`,guideDomain:`Domain of the runner`,guideCheckDns:`Check`,guideDnsOk:`The domain points to {ips}.`,guideDnsMissing:`The domain does not point anywhere yet: DNS changes can take some minutes.`,guideAccessTitle:`3. Enter the VPS`,guideAccess:`From a terminal: ssh root@<IP of the VPS>. Or open the web console of your provider.`,guideInstallTitle:`4. Run the installer`,guideInstall:`Paste this command and press Enter. It takes 3–10 minutes.`,guideVerified:`Prefer to check the script first?`,guideCopy:`Copy`,guideCopied:`Copied`,guidePairTitle:`5. Connect it`,guidePair:`At the end the installer prints a pairing code (valid 15 minutes). Paste it here.`,guideCheckHealth:`Check the runner`,guideHealthOk:`The runner {version} answers at {url}.`,guideHealthKo:`No runner answers at {url} yet: check the domain and that ports 80 and 443 are open.`,guideTroubleTitle:`If something goes wrong`,guideTrouble:`"port is used": another web server is running (stop it). "certificate": the domain does not point to the VPS yet. Run the command again at any time: nothing is lost.`,runnersTitle:`Runners`,runnersIntro:`The servers where Claude Code and opencode run. Each tenant uses one of them.`,runnersEmpty:`No runner yet.`,runnersAdd:`Add a runner`,runnersDefault:`Default for new tenants`,runnersDraining:`Draining (no new chats)`,runnersRemove:`Remove`,runnersRemoveConfirm:`Remove {name}? Its tenants must be moved first.`,runnersLoad:`{chats} of {max} chats`,runnersTenants:`{count} tenants`,runnersUnreachable:`Not reachable`,runnersVersion:`Version {version}`,distributionTitle:`Tenants`,distributionIntro:`Which runner each tenant uses. Moving a tenant asks its people to connect their subscriptions again.`,distributionRunner:`Runner`,distributionNone:`None`,addTitle:`Add a runner`,addAutomatic:`Install it for me`,addAutomaticHint:`Give the access to a new VPS: the runner is installed and connected by itself.`,addGuided:`Guide me`,addGuidedHint:`Step by step instructions to install it by hand.`,addExisting:`It is already installed`,addExistingHint:`Its address: you approve on the runner.`,addName:`Name`,addNamePlaceholder:`Runner Europe 1`,addUrl:`Address`,addCode:`Pairing code`,addConnect:`Connect`,addHost:`IP address of the VPS`,addPort:`SSH port`,addUser:`User`,addAuth:`Access`,addKey:`Private SSH key`,addLocalKey:`The SSH key of this computer`,addLocalKeyHint:`The key ~/.ssh/config gives this host (or ~/.ssh/id_ed25519), and its user when it says one: leave the user empty to take it from there.`,addPassword:`Password`,addInstall:`Install`,addInstalling:`Installing…`,addCredentialsNote:`The access is used only for this installation and is not kept.`,addBack:`Back`,addDone:`The runner is connected.`,error:`Something went wrong: {error}`,consoleTitle:`Runner console`,consoleSignIn:`Sign in`,consoleToken:`Admin token`,consoleTokenHint:`On the VPS: docker compose -f /opt/llmnative-runner/compose.yaml exec runner node src/cli.ts admin-token`,consoleSignOut:`Sign out`,consoleStatus:`Status`,consoleMachine:`{memory} GB of memory free of {total}, {cpus} cores`,consolePairing:`Connect a platform`,consolePairingHint:`A code to connect this runner to a CMS or a studio (15 minutes, once).`,consoleNewCode:`New pairing code`,consoleCode:`Code: {code} (until {at})`,consoleTenants:`Tenants`,consoleNewTenant:`New tenant`,consoleTenantId:`Id (lowercase, digits, -)`,consoleTenantName:`Name`,consoleCreate:`Create`,consoleKeys:`Keys`,consoleNewKey:`New key`,consoleKeyShown:`The key, shown this once: {key}`,consoleRevoke:`Revoke`,consoleRemoveTenant:`Remove tenant`,consoleRemoveTenantConfirm:`Remove {name}, its keys and chats?`,consoleAccounts:`Accounts`,pairNext:`Continue`,pairWaitingTitle:`Approve on the runner`,pairWaitingHint:`Open the runner and approve the request: check that it shows this same code.`,pairOpen:`Open the runner to approve`,pairWaiting:`Waiting for the approval… (until {at})`,pairDenied:`The request was refused on the runner.`,pairExpired:`The request expired: ask again.`,pairAgain:`Ask again`,pairWithCode:`I have a pairing code`,pairWithApproval:`Approve on the runner instead`,consoleRequests:`Requests to connect`,consoleRequestsHint:`A platform asked to connect to this runner. Approve only if you asked from there and the code is the one it shows.`,consoleRequestsEmpty:`No requests waiting.`,consoleRequestFrom:`{name}, from {from}, asked at {at}`,consoleRequestProject:`For the project «{project}»: it will see only its tenants ({project}, {project}-…).`,consoleRequestAll:`Without a project: it will see every tenant of this runner.`,consolePlatforms:`Connected platforms`,consolePlatformsHint:`Who connected this runner. A platform of a project sees only the tenants of its project; one without a project (connected before 1.2) sees them all: give it its project.`,consolePlatformsEmpty:`No platform connected.`,consolePlatformAll:`every tenant`,consolePlatformProject:`Project`,consolePlatformSave:`Save`,consolePlatformRevokeConfirm:`Disconnect {name}? It will no longer reach this runner.`,consoleRequestMatch:`The request you opened`,consoleApprove:`Approve`,consoleDeny:`Refuse`,consoleApproved:`Approved: {name} is connected.`,consoleDenied:`Refused.`,consoleRemember:`Remember on this browser`,close:`Close`,cancel:`Cancel`},h={accountsTitleUser:`I miei abbonamenti`,accountsTitleTenant:`Abbonamenti del tenant`,accountsIntroUser:`Collega il tuo abbonamento: lo usano solo le tue richieste. Senza, si usano le API key del workspace.`,accountsIntroTenant:`Account usati da tutti nel tenant, dopo i loro.`,accountsEmpty:`Nessun abbonamento collegato.`,accountsNoCredit:`Limite raggiunto, torna alle {at}`,accountsConnected:`Collegato il {at}`,accountsRemove:`Scollega`,accountsRemoveConfirm:`Scollegare {name}? Il token viene cancellato dal runner.`,claudeConnect:`Collega Claude`,claudeStep1:`Apri la pagina di Anthropic ed entra con il tuo account Claude (Pro o Max).`,claudeOpen:`Apri la pagina di Anthropic`,claudeStep2:`Anthropic mostra un codice: incollalo qui.`,claudeCode:`Codice`,claudeLabel:`Nome (facoltativo)`,claudeLabelPlaceholder:`Max personale`,claudeFinish:`Collega`,claudeRefused:`Anthropic non ha accettato il codice: ricomincia.`,claudeNoLink:`Il runner non è riuscito ad avviare l'accesso. Riprova tra un minuto.`,opencodeConnect:`Aggiungi OpenCode Go`,opencodeKey:`API key di OpenCode Go`,opencodeAdd:`Aggiungi`,keyConnect:`Aggiungi una chiave`,keyProvider:`Provider`,keyLabel:`API key di {provider}`,termsNote:`Un abbonamento Pro o Max è personale: collega solo il tuo.`,guideTitle:`Installa un runner a mano`,guideServerTitle:`1. Una VPS`,guideServer:`Va bene qualunque fornitore. Servono {systems}, almeno {cpus} core, {memory} GB di memoria e {disk} GB di disco, con le porte {ports} aperte.`,guideDnsTitle:`2. Il dominio`,guideDns:`Nel DNS del tuo dominio crea un record A per il runner (es. runner.example.com) con l'indirizzo IP della VPS.`,guideDomain:`Dominio del runner`,guideCheckDns:`Controlla`,guideDnsOk:`Il dominio punta a {ips}.`,guideDnsMissing:`Il dominio non punta ancora da nessuna parte: le modifiche al DNS possono richiedere qualche minuto.`,guideAccessTitle:`3. Entra nella VPS`,guideAccess:`Da un terminale: ssh root@<IP della VPS>. Oppure apri la console web del fornitore.`,guideInstallTitle:`4. Lancia l'installazione`,guideInstall:`Incolla questo comando e premi Invio. Ci vogliono 3–10 minuti.`,guideVerified:`Preferisci controllare lo script prima?`,guideCopy:`Copia`,guideCopied:`Copiato`,guidePairTitle:`5. Collegalo`,guidePair:`Alla fine l'installazione stampa un codice di abbinamento (valido 15 minuti). Incollalo qui.`,guideCheckHealth:`Controlla il runner`,guideHealthOk:`Il runner {version} risponde su {url}.`,guideHealthKo:`Nessun runner risponde ancora su {url}: controlla il dominio e che le porte 80 e 443 siano aperte.`,guideTroubleTitle:`Se qualcosa non va`,guideTrouble:`"port is used": c'è già un altro server web (fermalo). "certificate": il dominio non punta ancora alla VPS. Puoi rilanciare il comando quando vuoi: non si perde niente.`,runnersTitle:`Runner`,runnersIntro:`I server dove girano Claude Code e opencode. Ogni tenant ne usa uno.`,runnersEmpty:`Nessun runner.`,runnersAdd:`Aggiungi un runner`,runnersDefault:`Predefinito per i nuovi tenant`,runnersDraining:`In svuotamento (niente chat nuove)`,runnersRemove:`Rimuovi`,runnersRemoveConfirm:`Rimuovere {name}? Prima vanno spostati i suoi tenant.`,runnersLoad:`{chats} chat su {max}`,runnersTenants:`{count} tenant`,runnersUnreachable:`Non raggiungibile`,runnersVersion:`Versione {version}`,distributionTitle:`Tenant`,distributionIntro:`Quale runner usa ogni tenant. Spostare un tenant chiede alle sue persone di ricollegare gli abbonamenti.`,distributionRunner:`Runner`,distributionNone:`Nessuno`,addTitle:`Aggiungi un runner`,addAutomatic:`Installalo tu`,addAutomaticHint:`Dai l'accesso a una VPS nuova: il runner si installa e si collega da solo.`,addGuided:`Guidami`,addGuidedHint:`Istruzioni passo passo per installarlo a mano.`,addExisting:`È già installato`,addExistingHint:`Il suo indirizzo: approvi sul runner.`,addName:`Nome`,addNamePlaceholder:`Runner Europa 1`,addUrl:`Indirizzo`,addCode:`Codice di abbinamento`,addConnect:`Collega`,addHost:`Indirizzo IP della VPS`,addPort:`Porta SSH`,addUser:`Utente`,addAuth:`Accesso`,addKey:`Chiave SSH privata`,addLocalKey:`La chiave SSH di questo computer`,addLocalKeyHint:`La chiave che ~/.ssh/config indica per questo host (o ~/.ssh/id_ed25519), e il suo utente se lo indica: lascia vuoto l'utente per prenderlo da lì.`,addPassword:`Password`,addInstall:`Installa`,addInstalling:`Installazione in corso…`,addCredentialsNote:`L'accesso serve solo per questa installazione e non viene salvato.`,addBack:`Indietro`,addDone:`Il runner è collegato.`,error:`Qualcosa è andato storto: {error}`,consoleTitle:`Console del runner`,consoleSignIn:`Entra`,consoleToken:`Token di amministrazione`,consoleTokenHint:`Sulla VPS: docker compose -f /opt/llmnative-runner/compose.yaml exec runner node src/cli.ts admin-token`,consoleSignOut:`Esci`,consoleStatus:`Stato`,consoleMachine:`{memory} GB di memoria liberi su {total}, {cpus} core`,consolePairing:`Collega una piattaforma`,consolePairingHint:`Un codice per collegare questo runner a un CMS o a uno studio (15 minuti, una volta).`,consoleNewCode:`Nuovo codice di abbinamento`,consoleCode:`Codice: {code} (fino alle {at})`,consoleTenants:`Tenant`,consoleNewTenant:`Nuovo tenant`,consoleTenantId:`Id (minuscole, cifre, -)`,consoleTenantName:`Nome`,consoleCreate:`Crea`,consoleKeys:`Chiavi`,consoleNewKey:`Nuova chiave`,consoleKeyShown:`La chiave, mostrata solo ora: {key}`,consoleRevoke:`Revoca`,consoleRemoveTenant:`Rimuovi tenant`,consoleRemoveTenantConfirm:`Rimuovere {name}, le sue chiavi e le sue chat?`,consoleAccounts:`Account`,pairNext:`Continua`,pairWaitingTitle:`Approva sul runner`,pairWaitingHint:`Apri il runner e approva la richiesta: controlla che mostri questo stesso codice.`,pairOpen:`Apri il runner per approvare`,pairWaiting:`In attesa dell'approvazione… (fino alle {at})`,pairDenied:`La richiesta è stata rifiutata sul runner.`,pairExpired:`La richiesta è scaduta: chiedi di nuovo.`,pairAgain:`Chiedi di nuovo`,pairWithCode:`Ho un codice di abbinamento`,pairWithApproval:`Approva sul runner invece`,consoleRequests:`Richieste di collegamento`,consoleRequestsHint:`Una piattaforma ha chiesto di collegarsi a questo runner. Approva solo se l'hai chiesto tu da lì e il codice è quello che mostra.`,consoleRequestsEmpty:`Nessuna richiesta in attesa.`,consoleRequestFrom:`{name}, da {from}, alle {at}`,consoleRequestProject:`Per il progetto «{project}»: vedrà solo i suoi tenant ({project}, {project}-…).`,consoleRequestAll:`Senza progetto: vedrà tutti i tenant di questo runner.`,consolePlatforms:`Piattaforme collegate`,consolePlatformsHint:`Chi ha collegato questo runner. Una piattaforma di un progetto vede solo i tenant del suo progetto; una senza progetto (collegata prima della 1.2) li vede tutti: assegnale il suo progetto.`,consolePlatformsEmpty:`Nessuna piattaforma collegata.`,consolePlatformAll:`tutti i tenant`,consolePlatformProject:`Progetto`,consolePlatformSave:`Salva`,consolePlatformRevokeConfirm:`Scollegare {name}? Non raggiungerà più questo runner.`,consoleRequestMatch:`La richiesta che hai aperto`,consoleApprove:`Approva`,consoleDeny:`Rifiuta`,consoleApproved:`Approvata: {name} è collegato.`,consoleDenied:`Rifiutata.`,consoleRemember:`Ricorda su questo browser`,close:`Chiudi`,cancel:`Annulla`},g={en:m,it:h};function _(e,t){let n=e&&e.toLowerCase().startsWith(`it`)?h:m;return t?{...n,...t}:n}var v=(e,t)=>e.replace(/\{(\w+)\}/g,(e,n)=>n in t?String(t[n]):e),y={"claude-code":`Claude Code`,"opencode-go":`OpenCode Go`,opencode:`OpenCode Zen`,anthropic:`Anthropic`,openai:`OpenAI`,gemini:`Gemini`,mistral:`Mistral`,deepseek:`DeepSeek`,openrouter:`OpenRouter`},b=[`claude-code`,`opencode-go`],x=e=>new Date(e).toLocaleString(void 0,{dateStyle:`medium`,timeStyle:`short`});function S({client:e,scope:t,locale:n,texts:r,onChange:i,providers:a}){let o=_(n,r),s=a??(t===`tenant`?[...b,`opencode`,...c.RUNNER_KEY_PROVIDERS]:b),l=s.filter(e=>e!==`claude-code`),[p,m]=(0,u.useState)(null),[h,g]=(0,u.useState)(null),[S,T]=(0,u.useState)(null),[E,D]=(0,u.useState)(null),O=(0,u.useCallback)(async()=>{try{let{accounts:t}=await e.accounts.list();return m(t),g(null),t}catch(e){return g(e instanceof c.RunnerError?e.code:String(e)),m([]),[]}},[e]);(0,u.useEffect)(()=>{O()},[O]);let k=async()=>{T(null);let e=await O();i?.(e)};return(0,f.jsxs)(d.Card,{title:t===`user`?o.accountsTitleUser:o.accountsTitleTenant,loading:p===null,loaderMinHeight:120,children:[(0,f.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[(0,f.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:t===`user`?o.accountsIntroUser:o.accountsIntroTenant}),h&&(0,f.jsx)(d.Alert,{variant:`danger`,children:v(o.error,{error:h})}),p?.length===0&&!h&&(0,f.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:o.accountsEmpty}),p?.map(e=>(0,f.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 rounded-md border border-border p-3`,children:[(0,f.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,f.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,f.jsx)(`span`,{className:`font-medium`,children:e.label??y[e.provider]??e.provider}),(0,f.jsx)(d.Badge,{variant:`secondary`,children:y[e.provider]??e.provider}),e.noCreditUntil&&(0,f.jsx)(d.Badge,{variant:`warning`,children:v(o.accountsNoCredit,{at:x(e.noCreditUntil)})})]}),(0,f.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:v(o.accountsConnected,{at:x(e.at)})})]}),(0,f.jsx)(d.ActionButton,{icon:`unlink`,label:o.accountsRemove,variant:`outline-danger`,onClick:()=>D(e)})]},`${e.provider}/${e.id}`)),S===`claude`&&(0,f.jsx)(C,{client:e,t:o,onDone:k,onCancel:()=>T(null)}),S===`key`&&(0,f.jsx)(w,{client:e,t:o,providers:l,onDone:k,onCancel:()=>T(null)}),!S&&(0,f.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[s.includes(`claude-code`)&&(0,f.jsx)(d.ActionButton,{icon:`plus`,label:o.claudeConnect,variant:`primary`,onClick:()=>T(`claude`)}),l.length>0&&(0,f.jsx)(d.ActionButton,{icon:`plus`,label:l.length===1&&l[0]===`opencode-go`?o.opencodeConnect:o.keyConnect,variant:`outline-secondary`,onClick:()=>T(`key`)})]}),(0,f.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:o.termsNote})]}),E&&(0,f.jsx)(d.ModalYesNo,{title:o.accountsRemove,danger:!0,onClose:()=>D(null),onYes:async()=>(await e.accounts.remove(E.provider,E.id).catch(()=>!1),D(null),await k(),!0),children:v(o.accountsRemoveConfirm,{name:E.label??y[E.provider]??E.provider})})]})}function C({client:e,t,onDone:n,onCancel:r}){let[i,a]=(0,u.useState)(null),[o,s]=(0,u.useState)(``),[l,p]=(0,u.useState)(``),[m,h]=(0,u.useState)(null);return(0,u.useEffect)(()=>{let n=!1;return e.accounts.startClaudeLogin().then(({url:e})=>!n&&a(e)).catch(()=>!n&&h(t.claudeNoLink)),()=>{n=!0}},[e,t]),(0,f.jsxs)(`div`,{className:`flex flex-col gap-3 rounded-md border border-border p-3`,children:[m&&(0,f.jsx)(d.Alert,{variant:`danger`,children:m}),(0,f.jsx)(`p`,{className:`text-sm`,children:t.claudeStep1}),(0,f.jsx)(`div`,{children:(0,f.jsx)(d.ActionButton,{icon:`external-link`,label:t.claudeOpen,variant:`primary`,disabled:!i,onClick:()=>i&&window.open(i,`_blank`,`noopener,noreferrer`)})}),(0,f.jsx)(`p`,{className:`text-sm`,children:t.claudeStep2}),(0,f.jsxs)(d.Form,{appearance:`empty`,showNotice:!1,onSubmit:()=>!1,children:[(0,f.jsx)(d.String,{name:`code`,label:t.claudeCode,autoComplete:`off`,onChange:({value:e})=>s(String(e??``))}),(0,f.jsx)(d.String,{name:`label`,label:t.claudeLabel,placeholder:t.claudeLabelPlaceholder,onChange:({value:e})=>p(String(e??``))})]}),(0,f.jsxs)(`div`,{className:`flex gap-2`,children:[(0,f.jsx)(d.LoadingButton,{label:t.claudeFinish,variant:`primary`,disabled:!i||!o.trim(),onClick:async()=>{try{await e.accounts.finishClaudeLogin(o.trim(),l.trim()||void 0),n()}catch(e){h(e instanceof c.RunnerError&&e.code===`refused`?t.claudeRefused:v(t.error,{error:e instanceof c.RunnerError?e.code:String(e)}))}}}),(0,f.jsx)(d.ActionButton,{label:t.cancel,variant:`outline-secondary`,onClick:r})]})]})}function w({client:e,t,providers:n,onDone:r,onCancel:i}){let[a,o]=(0,u.useState)(n[0]),[s,l]=(0,u.useState)(``),[p,m]=(0,u.useState)(``),[h,g]=(0,u.useState)(null);return(0,f.jsxs)(`div`,{className:`flex flex-col gap-3 rounded-md border border-border p-3`,children:[h&&(0,f.jsx)(d.Alert,{variant:`danger`,children:h}),(0,f.jsxs)(d.Form,{appearance:`empty`,showNotice:!1,onSubmit:()=>!1,children:[n.length>1&&(0,f.jsx)(d.Select,{name:`provider`,label:t.keyProvider,defaultValue:a,options:n.map(e=>({label:y[e]??e,value:e})),onChange:({value:e})=>o(String(e??n[0]))}),(0,f.jsx)(d.Password,{name:`key`,label:v(t.keyLabel,{provider:y[a]??a}),autoComplete:`off`,onChange:({value:e})=>l(String(e??``))}),(0,f.jsx)(d.String,{name:`label`,label:t.claudeLabel,onChange:({value:e})=>m(String(e??``))})]}),(0,f.jsxs)(`div`,{className:`flex gap-2`,children:[(0,f.jsx)(d.LoadingButton,{label:t.opencodeAdd,variant:`primary`,disabled:!s.trim(),onClick:async()=>{try{await e.accounts.addKey(a,s.trim(),p.trim()||void 0),r()}catch(e){g(v(t.error,{error:e instanceof c.RunnerError?e.code:String(e)}))}}}),(0,f.jsx)(d.ActionButton,{label:t.cancel,variant:`outline-secondary`,onClick:i})]})]})}function T({title:e,children:t,done:n}){return(0,f.jsxs)(`section`,{className:`flex flex-col gap-2 border-l-2 border-border pl-4`,children:[(0,f.jsxs)(`h4`,{className:`flex items-center gap-2 text-sm font-semibold`,children:[e,n&&(0,f.jsx)(d.Badge,{variant:`success`,children:`✓`})]}),t]})}function E({locale:e,texts:t,onPair:n,lookup:r=e=>l.lookupDomain(e),check:i=l.checkRunner,version:a}){let o=_(e,t),[s,c]=(0,u.useState)(``),[p,m]=(0,u.useState)(null),[h,g]=(0,u.useState)(null),[y,b]=(0,u.useState)(``),[x,S]=(0,u.useState)(!1),[C,w]=(0,u.useState)(null),E=l.isDomain(s),D=`https://${s.trim().toLowerCase()}`,O=l.RUNNER_REQUIREMENTS;return(0,f.jsxs)(`div`,{className:`flex flex-col gap-5`,children:[(0,f.jsx)(T,{title:o.guideServerTitle,children:(0,f.jsx)(`p`,{className:`text-sm`,children:v(o.guideServer,{systems:O.systems.join(`, `),cpus:O.cpus,memory:O.memoryGb,disk:O.diskGb,ports:O.ports.join(`, `)})})}),(0,f.jsxs)(T,{title:o.guideDnsTitle,done:!!p?.ips.length,children:[(0,f.jsx)(`p`,{className:`text-sm`,children:o.guideDns}),(0,f.jsx)(d.Form,{appearance:`empty`,showNotice:!1,onSubmit:()=>!1,children:(0,f.jsx)(d.String,{name:`domain`,label:o.guideDomain,placeholder:`runner.example.com`,autoComplete:`off`,onChange:({value:e})=>{c(String(e??``)),m(null),g(null)}})}),(0,f.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,f.jsx)(d.LoadingButton,{label:o.guideCheckDns,variant:`outline-secondary`,disabled:!E,onClick:async()=>m({ips:await r(s.trim().toLowerCase()).catch(()=>[])})}),p&&(p.ips.length?(0,f.jsx)(d.Alert,{variant:`success`,appearance:`text`,children:v(o.guideDnsOk,{ips:p.ips.join(`, `)})}):(0,f.jsx)(d.Alert,{variant:`warning`,appearance:`text`,children:o.guideDnsMissing}))]})]}),(0,f.jsx)(T,{title:o.guideAccessTitle,children:(0,f.jsx)(`p`,{className:`text-sm`,children:o.guideAccess})}),(0,f.jsxs)(T,{title:o.guideInstallTitle,children:[(0,f.jsx)(`p`,{className:`text-sm`,children:o.guideInstall}),(0,f.jsx)(d.Code,{language:`bash`,showCopy:!0,children:l.installCommand({domain:E?s:`runner.example.com`,...a?{version:a}:{}})}),(0,f.jsx)(`div`,{children:(0,f.jsx)(d.ActionButton,{label:o.guideVerified,variant:`link`,onClick:()=>S(e=>!e)})}),x&&(0,f.jsx)(d.Code,{language:`bash`,showCopy:!0,children:l.verifiedInstallCommands({domain:E?s:`runner.example.com`,...a?{version:a}:{}}).join(`
2
+ `)})]}),(0,f.jsxs)(T,{title:o.guidePairTitle,done:h?.ok,children:[(0,f.jsx)(`p`,{className:`text-sm`,children:o.guidePair}),(0,f.jsx)(d.Form,{appearance:`empty`,showNotice:!1,onSubmit:()=>!1,children:(0,f.jsx)(d.String,{name:`code`,label:o.addCode,placeholder:`ABCD-EFGH`,autoComplete:`off`,onChange:({value:e})=>b(String(e??``))})}),h&&(0,f.jsx)(d.Alert,{variant:h.ok?`success`:`warning`,appearance:`text`,children:h.text}),C&&(0,f.jsx)(d.Alert,{variant:`danger`,children:C}),(0,f.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,f.jsx)(d.LoadingButton,{label:o.guideCheckHealth,variant:`outline-secondary`,disabled:!E,onClick:async()=>{let e=await i(D);g(e.ok?{ok:!0,text:v(o.guideHealthOk,{version:e.version,url:D})}:{ok:!1,text:v(o.guideHealthKo,{url:D})})}}),(0,f.jsx)(d.LoadingButton,{label:o.addConnect,variant:`primary`,disabled:!E||y.trim().length<8,onClick:async()=>{try{w(null),await n({url:D,code:y.trim()})}catch(e){w(v(o.error,{error:e.message}))}}})]})]}),(0,f.jsx)(T,{title:o.guideTroubleTitle,children:(0,f.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:o.guideTrouble})})]})}function D({fleet:e,locale:t,texts:n}){let r=_(t,n),[i,a]=(0,u.useState)(null),[o,s]=(0,u.useState)(null),[c,l]=(0,u.useState)(!1),[p,m]=(0,u.useState)(null),[h,g]=(0,u.useState)(null),y=(0,u.useCallback)(async()=>{try{let t=await e.list();a(t);let n=await Promise.all(t.map(t=>e.status(t.id).catch(()=>null)));a(t.map((e,t)=>({...e,status:n[t]}))),e.tenants&&s(await e.tenants.list())}catch(e){g(v(r.error,{error:e.message})),a([])}},[e,r]);(0,u.useEffect)(()=>{y()},[y]);let b=async(t,n)=>{await e.update(t,n),await y()};return(0,f.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,f.jsx)(d.Card,{header:(0,f.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,f.jsx)(`h3`,{className:`flex-1 text-base font-semibold`,children:r.runnersTitle}),(0,f.jsx)(d.ActionButton,{icon:`plus`,label:r.runnersAdd,variant:`primary`,onClick:()=>l(!0)})]}),loading:i===null,loaderMinHeight:120,children:(0,f.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[(0,f.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:r.runnersIntro}),h&&(0,f.jsx)(d.Alert,{variant:`danger`,children:h}),i?.length===0&&(0,f.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:r.runnersEmpty}),i?.map(e=>(0,f.jsxs)(`div`,{className:`flex flex-col gap-2 rounded-md border border-border p-3`,children:[(0,f.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,f.jsx)(`span`,{className:`font-medium`,children:e.name}),(0,f.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:e.url}),e.status===null&&(0,f.jsx)(d.Badge,{variant:`danger`,children:r.runnersUnreachable}),e.status&&(0,f.jsx)(d.Badge,{variant:`secondary`,children:v(r.runnersVersion,{version:e.status.version})}),e.status&&(0,f.jsx)(d.Badge,{variant:`info`,children:v(r.runnersLoad,{chats:e.status.load.chats,max:e.status.load.maxChats})}),e.status&&(0,f.jsx)(d.Badge,{variant:`light`,children:v(r.runnersTenants,{count:e.status.tenants.length})}),(0,f.jsx)(`div`,{className:`ml-auto`,children:(0,f.jsx)(d.ActionButton,{icon:`trash`,label:r.runnersRemove,variant:`outline-danger`,onClick:()=>m(e)})})]}),(0,f.jsx)(d.Form,{appearance:`empty`,showNotice:!1,onSubmit:()=>!1,defaultValues:{isDefault:e.isDefault?`true`:``,draining:e.draining?`true`:``},children:(0,f.jsxs)(`div`,{className:`flex flex-wrap gap-4`,children:[(0,f.jsx)(d.Switch,{name:`isDefault`,label:r.runnersDefault,valueChecked:`true`,onChange:({value:t})=>void b(e.id,{isDefault:!!t})}),(0,f.jsx)(d.Switch,{name:`draining`,label:r.runnersDraining,valueChecked:`true`,onChange:({value:t})=>void b(e.id,{draining:!!t})})]})})]},e.id))]})}),e.tenants&&i&&i.length>0&&(0,f.jsx)(d.Card,{title:r.distributionTitle,loading:o===null,loaderMinHeight:80,children:(0,f.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,f.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:r.distributionIntro}),(0,f.jsx)(d.Form,{appearance:`empty`,showNotice:!1,onSubmit:()=>!1,defaultValues:Object.fromEntries((o??[]).map(e=>[`runner_${e.id}`,e.runnerId??``])),children:(o??[]).map(t=>(0,f.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,f.jsx)(`span`,{className:`min-w-40 flex-1 text-sm`,children:t.name}),(0,f.jsx)(d.Select,{name:`runner_${t.id}`,title:r.distributionRunner,placeholderOption:{label:r.distributionNone,value:``},options:i.map(e=>({label:e.name,value:e.id})),onChange:({value:n})=>{n&&e.tenants.assign(t.id,String(n)).then(y)}})]},t.id))})]})}),c&&(0,f.jsx)(A,{fleet:e,t:r,locale:t,onClose:()=>l(!1),onAdded:async()=>{l(!1),await y()}}),p&&(0,f.jsx)(d.ModalYesNo,{title:r.runnersRemove,danger:!0,onClose:()=>m(null),onYes:async()=>(await e.remove(p.id).catch(e=>g(v(r.error,{error:e.message}))),m(null),await y(),!0),children:v(r.runnersRemoveConfirm,{name:p.name})})]})}function O({target:e,children:t}){return e?(0,p.createPortal)(t,e):null}var k=e=>{try{return new URL(e).hostname}catch{return e}};function A({fleet:e,t,locale:n,onClose:r,onAdded:i}){let[a,o]=(0,u.useState)(`choose`),[s,c]=(0,u.useState)(null),[l,p]=(0,u.useState)(null),m=(0,u.useCallback)(e=>c(v(t.error,{error:e.message})),[t]);return(0,f.jsx)(d.Modal,{title:t.addTitle,size:`lg`,onClose:r,footer:a===`choose`||a===`guided`?!1:(0,f.jsx)(`div`,{ref:p,className:`flex w-full flex-wrap items-center justify-end gap-3`}),children:(0,f.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[s&&(0,f.jsx)(d.Alert,{variant:`danger`,children:s}),a===`choose`&&(0,f.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-3`,children:[e.install&&(0,f.jsx)(j,{title:t.addAutomatic,hint:t.addAutomaticHint,onClick:()=>o(`automatic`)}),(0,f.jsx)(j,{title:t.addGuided,hint:t.addGuidedHint,onClick:()=>o(`guided`)}),(0,f.jsx)(j,{title:t.addExisting,hint:t.addExistingHint,onClick:()=>o(`existing`)})]}),a!==`choose`&&(0,f.jsx)(`div`,{children:(0,f.jsx)(d.ActionButton,{icon:`arrow-left`,label:t.addBack,variant:`link`,onClick:()=>{o(`choose`),c(null)}})}),a===`automatic`&&e.install&&(0,f.jsx)(L,{t,footer:l,localKeys:!!e.localKeys,install:(t,n,r)=>e.install({name:t,domain:t,access:n},r),onDone:i,onError:m}),a===`guided`&&(0,f.jsx)(E,{locale:n,texts:t,onPair:async({url:t,code:n})=>{await i(await e.add({name:k(t),url:t,code:n}))}}),a===`existing`&&(0,f.jsx)(F,{t,footer:l,pairing:e.startPairing&&e.pairingStatus?{start:e.startPairing.bind(e),status:e.pairingStatus.bind(e)}:void 0,onAdded:i,onError:m,onClearError:()=>c(null),onConnect:async(t,n)=>{try{await i(await e.add({name:k(t),url:t,code:n}))}catch(e){m(e)}}})]})})}function j({title:e,hint:t,onClick:n}){return(0,f.jsxs)(`button`,{type:`button`,onClick:n,className:`rounded-lg border border-border p-4 text-left transition-colors hover:border-primary hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring`,children:[(0,f.jsx)(`span`,{className:`block font-medium`,children:e}),(0,f.jsx)(`span`,{className:`mt-1 block text-sm text-muted-foreground`,children:t})]})}var M=e=>(/^https?:\/\//.test(e.trim())?e.trim():`https://${e.trim()}`).replace(/\/+$/,``),N=e=>new Date(e).toLocaleTimeString(void 0,{hour:`2-digit`,minute:`2-digit`}),P=5;function F({t:e,footer:t,pairing:n,onAdded:r,onError:i,onClearError:a,onConnect:o}){let[s,c]=(0,u.useState)(``),[l,p]=(0,u.useState)(``),[m,h]=(0,u.useState)(!n),[g,_]=(0,u.useState)(null),[y,b]=(0,u.useState)(null);return(0,u.useEffect)(()=>{if(!g||!n)return;let e=!1,t=0,a,o=async()=>{try{let i=await n.status(g.id);if(t=0,e)return;if(i.status===`approved`){await r(i.runner);return}if(i.status!==`pending`){b(i.status),_(null);return}}catch(n){t+=1,!e&&t>=P&&i(n)}e||(a=setTimeout(()=>void o(),2e3))};return a=setTimeout(()=>void o(),2e3),()=>{e=!0,clearTimeout(a)}},[g,n,r,i]),g?(0,f.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[(0,f.jsx)(`h4`,{className:`font-semibold`,children:e.pairWaitingTitle}),(0,f.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:e.pairWaitingHint}),(0,f.jsx)(`div`,{className:`rounded-lg border border-border p-4 text-center font-mono text-3xl font-semibold tracking-widest`,children:g.code}),(0,f.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:v(e.pairWaiting,{at:N(g.expiresAt)})}),(0,f.jsx)(O,{target:t,children:(0,f.jsx)(d.ActionButton,{icon:`external-link`,label:e.pairOpen,variant:`primary`,onClick:()=>window.open(g.approveUrl,`_blank`,`noopener`)})})]}):(0,f.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[y&&(0,f.jsx)(d.Alert,{variant:y===`denied`?`danger`:`warning`,children:y===`denied`?e.pairDenied:e.pairExpired}),(0,f.jsxs)(d.Form,{appearance:`empty`,showNotice:!1,onSubmit:()=>!1,defaultValues:{url:s,code:l},children:[(0,f.jsx)(d.String,{name:`url`,label:e.addUrl,placeholder:`https://runner.example.com`,onChange:({value:e})=>c(String(e??``))}),m&&(0,f.jsx)(d.String,{name:`code`,label:e.addCode,placeholder:`ABCD-EFGH`,autoComplete:`off`,onChange:({value:e})=>p(String(e??``))})]}),(0,f.jsxs)(O,{target:t,children:[n&&(0,f.jsx)(d.ActionButton,{label:m?e.pairWithApproval:e.pairWithCode,variant:`link`,onClick:()=>h(e=>!e)}),m?(0,f.jsx)(d.LoadingButton,{label:e.addConnect,variant:`primary`,disabled:!s.trim()||l.trim().length<8,onClick:()=>o(M(s),l.trim())}):(0,f.jsx)(d.LoadingButton,{label:y?e.pairAgain:e.pairNext,variant:`primary`,disabled:!s.trim(),onClick:async()=>{b(null),a();try{let e=M(s);_(await n.start({name:k(e),url:e}))}catch(e){i(e)}}})]})]})}var I=[`check`,`docker`,`files`,`start`,`agent`,`health`,`pair`,`tls`,`done`];function L({t:e,footer:t,localKeys:n,install:r,onDone:i,onError:a}){let[o,s]=(0,u.useState)({host:``,port:`22`,username:n?``:`root`,auth:n?`local`:`key`,privateKey:``,password:``,domain:``}),[c,l]=(0,u.useState)([]),[p,m]=(0,u.useState)(null),[h,g]=(0,u.useState)(!1),_=e=>({value:t})=>s(n=>({...n,[e]:String(t??``)})),v=o.host.trim()&&o.domain.trim()&&(o.auth===`local`||o.username.trim())&&(o.auth===`local`||(o.auth===`key`?o.privateKey.trim():o.password));return(0,f.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[!h&&(0,f.jsxs)(d.Form,{appearance:`empty`,showNotice:!1,onSubmit:()=>!1,defaultValues:o,children:[(0,f.jsx)(d.String,{name:`domain`,label:e.guideDomain,placeholder:`runner.example.com`,onChange:_(`domain`)}),(0,f.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-3`,children:[(0,f.jsx)(d.String,{name:`host`,label:e.addHost,placeholder:`203.0.113.10`,onChange:_(`host`)}),(0,f.jsx)(d.String,{name:`port`,label:e.addPort,onChange:_(`port`)}),(0,f.jsx)(d.String,{name:`username`,label:e.addUser,onChange:_(`username`)})]}),(0,f.jsx)(d.Select,{name:`auth`,label:e.addAuth,options:[...n?[{label:e.addLocalKey,value:`local`}]:[],{label:e.addKey,value:`key`},{label:e.addPassword,value:`password`}],onChange:_(`auth`)}),o.auth===`local`&&(0,f.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:e.addLocalKeyHint}),o.auth===`local`?null:o.auth===`key`?(0,f.jsx)(d.TextArea,{name:`privateKey`,label:e.addKey,placeholder:`-----BEGIN OPENSSH PRIVATE KEY-----`,onChange:_(`privateKey`)}):(0,f.jsx)(d.Password,{name:`password`,label:e.addPassword,autoComplete:`off`,onChange:_(`password`)})]}),(0,f.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:e.addCredentialsNote}),h&&(0,f.jsx)(`div`,{className:`flex flex-wrap gap-1`,children:I.map(e=>(0,f.jsx)(d.Badge,{variant:p===e?`primary`:I.indexOf(e)<I.indexOf(p??`check`)?`success`:`light`,children:e},e))}),c.length>0&&(0,f.jsx)(`pre`,{className:`max-h-64 overflow-auto rounded-md bg-muted p-2 text-xs`,children:c.slice(-200).join(`
3
+ `)}),(0,f.jsx)(O,{target:t,children:(0,f.jsx)(d.LoadingButton,{label:h?e.addInstalling:e.addInstall,variant:`primary`,disabled:!v||h,onClick:async()=>{g(!0),l([]);try{await i(await r(o.domain.trim().toLowerCase(),{host:o.host.trim(),port:Number(o.port)||22,username:o.username.trim(),...o.auth===`key`?{privateKey:o.privateKey}:o.auth===`password`?{password:o.password}:{}},({line:e,phase:t})=>{t&&m(t),/^[A-Z_]+=/.test(e)||l(t=>[...t,e])}))}catch(e){a(e)}finally{g(!1)}}})})]})}var R=e=>(e/1024**3).toFixed(1),z=e=>new Date(e).toLocaleString(void 0,{dateStyle:`short`,timeStyle:`short`});function B({client:e,locale:t,texts:n,onSignOut:r,approve:i}){let a=_(t,n),[o,s]=(0,u.useState)(null),[l,p]=(0,u.useState)(null),[m,h]=(0,u.useState)(null),[g,y]=(0,u.useState)({id:``,name:``}),[b,x]=(0,u.useState)(null),S=(0,u.useCallback)(async()=>{try{s(await e.platform.status()),p(null)}catch(e){p(v(a.error,{error:e instanceof c.RunnerError?e.code:String(e)}))}},[e,a]);return(0,u.useEffect)(()=>{S()},[S]),(0,f.jsxs)(`div`,{className:`mx-auto flex max-w-4xl flex-col gap-4 p-4`,children:[(0,f.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,f.jsx)(`h1`,{className:`flex-1 text-xl font-semibold`,children:a.consoleTitle}),r&&(0,f.jsx)(d.ActionButton,{icon:`log-out`,label:a.consoleSignOut,variant:`outline-secondary`,onClick:r})]}),l&&(0,f.jsx)(d.Alert,{variant:`danger`,children:l}),(0,f.jsx)(W,{client:e,t:a,approve:i,onAnswered:S}),(0,f.jsx)(d.Card,{title:a.consoleStatus,loading:!o&&!l,loaderMinHeight:100,children:o&&(0,f.jsx)(d.DescriptionList,{items:[{label:`Version`,value:o.version},{label:`URL`,value:o.url},{label:`Chats`,value:`${o.load.chats} / ${o.load.maxChats}`},{label:`Machine`,value:v(a.consoleMachine,{memory:R(o.machine.availableBytes),total:R(o.machine.totalBytes),cpus:o.machine.cpus})},{label:`Agent`,value:o.agentImage}]})}),(0,f.jsx)(d.Card,{title:a.consolePairing,children:(0,f.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,f.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:a.consolePairingHint}),m&&(0,f.jsx)(d.Code,{showCopy:!0,children:m.code}),m&&(0,f.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:v(a.consoleCode,{code:m.code,at:z(m.expiresAt)})}),(0,f.jsx)(`div`,{children:(0,f.jsx)(d.LoadingButton,{label:a.consoleNewCode,variant:`outline-primary`,onClick:async()=>h(await e.createPairing())})})]})}),(0,f.jsx)(V,{client:e,t:a}),(0,f.jsx)(d.Card,{title:a.consoleTenants,children:(0,f.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[b&&(0,f.jsx)(d.Alert,{variant:`warning`,onClose:()=>x(null),children:(0,f.jsx)(`span`,{className:`break-all`,children:v(a.consoleKeyShown,{key:b})})}),o?.tenants.map(n=>(0,f.jsx)(H,{client:e,tenant:n,t:a,locale:t,onKey:x,onChange:S},n.id)),(0,f.jsx)(d.Form,{appearance:`empty`,showNotice:!1,onSubmit:()=>!1,children:(0,f.jsxs)(`div`,{className:`grid gap-2 sm:grid-cols-[1fr_1fr_auto] sm:items-end`,children:[(0,f.jsx)(d.String,{name:`tenantId`,label:a.consoleTenantId,placeholder:`acme`,onChange:({value:e})=>y(t=>({...t,id:String(e??``)}))}),(0,f.jsx)(d.String,{name:`tenantName`,label:a.consoleTenantName,placeholder:`Acme`,onChange:({value:e})=>y(t=>({...t,name:String(e??``)}))}),(0,f.jsx)(d.LoadingButton,{label:a.consoleCreate,variant:`primary`,disabled:!/^[a-z0-9][a-z0-9-]{0,62}$/.test(g.id),onClick:async()=>{try{let t=await e.platform.createTenant(g.id,{name:g.name||void 0});t.key&&x(t.key),await S()}catch(e){p(v(a.error,{error:e instanceof c.RunnerError?e.code:String(e)}))}}})]})})]})})]})}function V({client:e,t}){let[n,r]=(0,u.useState)(null),[i,a]=(0,u.useState)({}),[o,s]=(0,u.useState)(null),c=(0,u.useCallback)(async()=>r(await e.platform.platformKeys()),[e]);return(0,u.useEffect)(()=>{c()},[c]),(0,f.jsxs)(d.Card,{title:t.consolePlatforms,loading:!n,loaderMinHeight:60,children:[(0,f.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[(0,f.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:t.consolePlatformsHint}),n&&!n.length&&(0,f.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:t.consolePlatformsEmpty}),n?.map(n=>{let r=i[n.id]??n.project??``;return(0,f.jsx)(d.Form,{appearance:`empty`,showNotice:!1,onSubmit:()=>!1,children:(0,f.jsxs)(`div`,{className:`grid gap-2 rounded-md border border-border p-3 sm:grid-cols-[1fr_12rem_auto] sm:items-end`,children:[(0,f.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,f.jsx)(`span`,{className:`font-medium`,children:n.name}),(0,f.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[z(n.createdAt),` · `,n.project??t.consolePlatformAll]})]}),(0,f.jsx)(d.String,{name:`project-${n.id}`,label:t.consolePlatformProject,value:r,placeholder:`crm`,onChange:({value:e})=>a(t=>({...t,[n.id]:String(e??``).trim()}))}),(0,f.jsxs)(`div`,{className:`flex gap-2`,children:[(0,f.jsx)(d.LoadingButton,{label:t.consolePlatformSave,variant:`outline-primary`,disabled:r===(n.project??``)||r!==``&&!/^[a-z0-9]{1,32}$/.test(r),onClick:async()=>{await e.setKeyProject(n.id,r||null),await c()}}),(0,f.jsx)(d.ActionButton,{icon:`trash`,label:t.consoleRevoke,variant:`outline-danger`,onClick:()=>s(n)})]})]})},n.id)})]}),o&&(0,f.jsx)(d.ModalYesNo,{title:t.consoleRevoke,danger:!0,onClose:()=>s(null),onYes:async()=>(await e.platform.revokePlatformKey(o.id),s(null),await c(),!0),children:v(t.consolePlatformRevokeConfirm,{name:o.name})})]})}function H({client:e,tenant:t,t:n,locale:r,onKey:i,onChange:a}){let[o,s]=(0,u.useState)(!1),[c,l]=(0,u.useState)(null),[p,m]=(0,u.useState)(!1),h=(0,u.useMemo)(()=>e.as({tenant:t.id}),[e,t.id]),g=(0,u.useCallback)(async()=>l(await e.platform.keys(t.id)),[e,t.id]);return(0,u.useEffect)(()=>{o&&g()},[o,g]),(0,f.jsxs)(`div`,{className:`rounded-md border border-border p-3`,children:[(0,f.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,f.jsxs)(`button`,{type:`button`,className:`flex-1 text-left font-medium`,onClick:()=>s(e=>!e),children:[t.name,` `,(0,f.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[`(`,t.id,`)`]})]}),t.usersWithAccounts!==void 0&&(0,f.jsxs)(d.Badge,{variant:`light`,children:[t.usersWithAccounts,` 👤`]}),(0,f.jsx)(d.ActionButton,{icon:`trash`,label:n.consoleRemoveTenant,variant:`outline-danger`,onClick:()=>m(!0)})]}),o&&(0,f.jsxs)(`div`,{className:`mt-3 flex flex-col gap-3`,children:[(0,f.jsx)(`h4`,{className:`text-sm font-semibold`,children:n.consoleKeys}),c?.map(r=>(0,f.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 text-sm`,children:[(0,f.jsx)(`span`,{className:`flex-1`,children:r.name}),r.permissions.map(e=>(0,f.jsx)(d.Badge,{variant:`info`,children:e},e)),(0,f.jsx)(d.ActionButton,{label:n.consoleRevoke,variant:`outline-danger`,onClick:async()=>{await e.platform.revokeKey(t.id,r.id),await g()}})]},r.id)),(0,f.jsx)(`div`,{children:(0,f.jsx)(d.LoadingButton,{label:n.consoleNewKey,variant:`outline-secondary`,onClick:async()=>{i((await e.platform.createKey(t.id,{name:`console`,permissions:[`complete`,`chat`,`chat:tools`,`accounts`,`act-as-user`]})).key),await g()}})}),(0,f.jsx)(`h4`,{className:`text-sm font-semibold`,children:n.consoleAccounts}),(0,f.jsx)(S,{client:h,scope:`tenant`,locale:r,texts:n})]}),p&&(0,f.jsx)(d.ModalYesNo,{title:n.consoleRemoveTenant,danger:!0,onClose:()=>m(!1),onYes:async()=>(await e.platform.removeTenant(t.id),m(!1),await a(),!0),children:v(n.consoleRemoveTenantConfirm,{name:t.name})})]})}var U=e=>e.toUpperCase().replace(/[^A-Z0-9]/g,``);function W({client:e,t,approve:n,onAnswered:r}){let[i,a]=(0,u.useState)(null),[o,s]=(0,u.useState)(null),c=(0,u.useCallback)(async()=>{try{let t=await e.pairingRequests(),r=n?U(n):``;a([...t].sort((e,t)=>Number(U(t.code)===r)-Number(U(e.code)===r)))}catch{a([])}},[e,n]);return(0,u.useEffect)(()=>{c();let e=setInterval(()=>void c(),5e3);return()=>clearInterval(e)},[c]),!n&&!i?.length&&!o?null:(0,f.jsx)(d.Card,{title:t.consoleRequests,loading:i===null,loaderMinHeight:80,children:(0,f.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[(0,f.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:t.consoleRequestsHint}),o&&(0,f.jsx)(d.Alert,{variant:o.variant,children:o.text}),i?.length===0&&!o&&(0,f.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:t.consoleRequestsEmpty}),i?.map(i=>{let a=!!n&&U(i.code)===U(n),o=async n=>{let a=await e.answerPairing(i.code,n);s(n?{variant:`success`,text:v(t.consoleApproved,{name:a.name})}:{variant:`info`,text:t.consoleDenied}),await c(),await r()};return(0,f.jsxs)(`div`,{className:`flex flex-col gap-2 rounded-md border p-3 ${a?`border-primary`:`border-border`}`,children:[a&&(0,f.jsx)(d.Badge,{variant:`primary`,children:t.consoleRequestMatch}),(0,f.jsx)(`div`,{className:`font-mono text-2xl font-semibold tracking-widest`,children:i.code}),(0,f.jsx)(`p`,{className:`text-sm`,children:v(t.consoleRequestFrom,{name:i.name,from:i.from??`?`,at:z(i.createdAt)})}),(0,f.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:i.project?v(t.consoleRequestProject,{project:i.project}):t.consoleRequestAll}),(0,f.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,f.jsx)(d.LoadingButton,{label:t.consoleApprove,variant:`primary`,onClick:()=>o(!0)}),(0,f.jsx)(d.LoadingButton,{label:t.consoleDeny,variant:`outline-danger`,onClick:()=>o(!1)})]})]},i.code)})]})})}exports.AddRunner=A,exports.InstallGuide=E,exports.RunnerAccounts=S,exports.RunnerConsole=B,exports.RunnersSettings=D,exports.fill=v,exports.runnerTexts=g,exports.textsFor=_;
4
4
  //# sourceMappingURL=ui.js.map