alran 0.9.0 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ALRAN_TOOLS_NOTICES.md +11 -0
- package/README.md +11 -16
- package/assets/agents/alran/skills/alran-code-product/SKILL.md +3 -3
- package/assets/agents/alran/skills/alran-code-product/references/account-models.md +19 -16
- package/chunks/{account-commands-JZ6NXTTK.js → account-commands-GW7N3MYC.js} +1 -1
- package/chunks/{anthropic-MN33DP4E.js → anthropic-63VE6MAE.js} +1 -1
- package/chunks/{application-ITGAJ4HC.js → application-WPPTE6LU.js} +1 -1
- package/chunks/{auth-command-V3RVPLZO.js → auth-command-36RMNQZW.js} +1 -1
- package/chunks/azure-openai-responses-OIP3KVKJ.js +2 -0
- package/chunks/chunk-2K5H5GA7.js +2 -0
- package/chunks/chunk-3GGKARES.js +2 -0
- package/chunks/chunk-5RIMHTEU.js +207 -0
- package/chunks/{chunk-EYK25HWR.js → chunk-5Y76VFHY.js} +1 -1
- package/chunks/{chunk-QIN5ZBE2.js → chunk-6DOVXX7W.js} +1 -1
- package/chunks/{chunk-E3GLGDGC.js → chunk-6PFI65C6.js} +1 -1
- package/chunks/{chunk-4PDIO3M6.js → chunk-6UXSIWCB.js} +1 -1
- package/chunks/{chunk-OQNU3VPS.js → chunk-C6LAAFG2.js} +2 -2
- package/chunks/{chunk-33CNY6GP.js → chunk-CUG7F2FN.js} +1 -1
- package/chunks/chunk-DFMYLGVU.js +249 -0
- package/chunks/{chunk-IIE366LR.js → chunk-G5MOGPZ3.js} +490 -485
- package/chunks/{chunk-FC4M2B7E.js → chunk-IC6A323Q.js} +1 -1
- package/chunks/{chunk-4X22UJQH.js → chunk-IN2Z5SSJ.js} +1 -1
- package/chunks/chunk-JSTSFMGK.js +70 -0
- package/chunks/{chunk-WWNUAU4P.js → chunk-LCC45PCZ.js} +1 -1
- package/chunks/{chunk-7QLAXRD2.js → chunk-MPQ6G7LH.js} +254 -254
- package/chunks/{chunk-FUERW2DW.js → chunk-MUXNNOSQ.js} +1 -1
- package/chunks/{chunk-44VPC5LA.js → chunk-NBONSNQZ.js} +1 -1
- package/chunks/chunk-NMKRNU5O.js +2 -0
- package/chunks/chunk-NVPGGFT3.js +2 -0
- package/chunks/chunk-NZXJAHTO.js +9 -0
- package/chunks/{chunk-6255CZPL.js → chunk-PCL2CVVE.js} +1 -1
- package/chunks/chunk-PXH4SBCS.js +3 -0
- package/chunks/chunk-RLJVY75P.js +28 -0
- package/chunks/{chunk-WYANV3IX.js → chunk-RLND4AYL.js} +1 -1
- package/chunks/chunk-TJC4LPRQ.js +2 -0
- package/chunks/chunk-U4PFHJ7Z.js +27 -0
- package/chunks/chunk-V2SB4U4D.js +2 -0
- package/chunks/chunk-VGKKKM2W.js +6 -0
- package/chunks/{chunk-XFCC2CI2.js → chunk-VUISZDXX.js} +1 -1
- package/chunks/chunk-XVGPB7TW.js +21 -0
- package/chunks/{chunk-CJM7ZJ6W.js → chunk-ZDI22NOK.js} +1 -1
- package/chunks/{data-dir-LDVKDCJ2.js → data-dir-OEPRRIOO.js} +1 -1
- package/chunks/{dist-2BRD4JFU.js → dist-VKYZJYR6.js} +1 -1
- package/chunks/{dist-EXKHRFQO.js → dist-WGTMUM3E.js} +1 -1
- package/chunks/{ffi-OUPK6AY6.js → ffi-EFLUAAVX.js} +1 -1
- package/chunks/{ffi-M5UP5J6C.js → ffi-QKKA5HYI.js} +1 -1
- package/chunks/{google-UJAPMFAB.js → google-RCR46TTQ.js} +1 -1
- package/chunks/{google-vertex-VLSF55PW.js → google-vertex-Y26T7YYR.js} +1 -1
- package/chunks/{install-source-JTIUC4G4.js → install-source-63OVVBMK.js} +1 -1
- package/chunks/launcher-2UG3JPYF.js +63 -0
- package/chunks/lifecycle-5IPJRP2V.js +2 -0
- package/chunks/{main-TQGGRHTS.js → main-7SGOQBHZ.js} +2 -2
- package/chunks/{mistral-ZJZUEF2X.js → mistral-NEBDKUEI.js} +1 -1
- package/chunks/{module-6F3E5H7Y-BN7QWGYB.js → module-6F3E5H7Y-FIMLNSCK.js} +1 -1
- package/chunks/{module-asyncify-R6PWJ6ZV-P4FWSBAY.js → module-asyncify-R6PWJ6ZV-Q2HJ3NOC.js} +1 -1
- package/chunks/{multipart-parser-L6M455MS.js → multipart-parser-JVSLI2CL.js} +1 -1
- package/chunks/{network-proxy-U72JCK2I.js → network-proxy-AJO7ZW3O.js} +1 -1
- package/chunks/openai-codex-responses-L2CIGCKO.js +2 -0
- package/chunks/openai-completions-C4PHW6MD.js +2 -0
- package/chunks/openai-responses-5NVFOW4Y.js +2 -0
- package/chunks/{openrouter-G2EHY5BD.js → openrouter-BKUGQT7Z.js} +1 -1
- package/chunks/{otel-OHXIZ666.js → otel-DRJM2PIX.js} +1 -1
- package/chunks/plugin-command-CIDTOPNB.js +2 -0
- package/chunks/provider-command-UZ7KQFAC.js +2 -0
- package/chunks/run-acp-command-AKDLHKMR.js +59 -0
- package/chunks/{run-exec-command-5ADSQR2Z.js → run-exec-command-UXTPS7LC.js} +1 -1
- package/chunks/{skills-command-XXXEZAG6.js → skills-command-57TF53NO.js} +1 -1
- package/chunks/src-5PSNGHHD.js +2 -0
- package/chunks/{src-IBHIRTD7.js → src-YZ26EVSY.js} +1 -1
- package/chunks/telemetry-3NXMCOVD.js +2 -0
- package/chunks/{telemetry-command-COQG2AKK.js → telemetry-command-CMDERYNN.js} +1 -1
- package/chunks/{tools-WDBB2JKV.js → tools-CRJR35HS.js} +1 -1
- package/chunks/{undici-TUGHZJSA.js → undici-O4OQVZ6I.js} +1 -1
- package/chunks/{update-NB6OD572.js → update-ACFAGV6F.js} +1 -1
- package/cli.js +2 -3
- package/embedded/alran-tools/cli.mjs +1 -5
- package/embedded/alran-tools/manifest.json +1 -1
- package/image-preview-worker.js +1 -1
- package/matrix-mcp-stdio.js +1 -1
- package/package.json +1 -1
- package/quickjs-worker.js +1 -1
- package/chunks/azure-openai-responses-OWHMUNKC.js +0 -2
- package/chunks/chunk-C3CMJAAV.js +0 -3
- package/chunks/chunk-ENHOPPS7.js +0 -16
- package/chunks/chunk-FSNYOJPJ.js +0 -2
- package/chunks/chunk-FXOH6TEQ.js +0 -21
- package/chunks/chunk-GRXX6I72.js +0 -2
- package/chunks/chunk-GSYHBK5Q.js +0 -6
- package/chunks/chunk-IWK7PZP7.js +0 -207
- package/chunks/chunk-KCLRJQ53.js +0 -59
- package/chunks/chunk-M7GW4VMR.js +0 -27
- package/chunks/chunk-QFUV5PX6.js +0 -2
- package/chunks/chunk-TW23QKAD.js +0 -3
- package/chunks/chunk-U7U3DJHF.js +0 -2
- package/chunks/chunk-WTAJMYF2.js +0 -249
- package/chunks/chunk-YLQXZBEL.js +0 -2
- package/chunks/chunk-Z6BHCXKT.js +0 -25
- package/chunks/chunk-Z6HBNJCA.js +0 -8
- package/chunks/launcher-FCZ3EDBF.js +0 -61
- package/chunks/lifecycle-GY435YMF.js +0 -2
- package/chunks/openai-codex-responses-FPCDNRL5.js +0 -2
- package/chunks/openai-completions-D32YW6KL.js +0 -2
- package/chunks/openai-responses-ZCGSENM4.js +0 -2
- package/chunks/plugin-command-OSAFHS7C.js +0 -2
- package/chunks/provider-command-SKTCHD4E.js +0 -2
- package/chunks/run-acp-command-SG2BDMFJ.js +0 -2
- package/chunks/src-DNIDEMVV.js +0 -2
- package/chunks/telemetry-J7ZLGF5X.js +0 -2
- /package/chunks/{chunk-EOR6EDNR.js → chunk-2AYWJZ72.js} +0 -0
- /package/chunks/{chunk-YPV2X2RG.js → chunk-4XP5XUIZ.js} +0 -0
- /package/chunks/{chunk-NWB7LFOK.js → chunk-5DQTVSQV.js} +0 -0
- /package/chunks/{chunk-OIQ336YE.js → chunk-EJN3SE5B.js} +0 -0
- /package/chunks/{chunk-A7GMJNA2.js → chunk-K5DTFR6D.js} +0 -0
- /package/chunks/{chunk-ZQOALVGL.js → chunk-R44C5DM6.js} +0 -0
- /package/chunks/{chunk-PNXZWSWT.js → chunk-UJCAE7SG.js} +0 -0
- /package/chunks/{chunk-J3KCPYZT.js → chunk-W5ZOLW7T.js} +0 -0
- /package/chunks/{chunk-XAGZ6ZEU.js → chunk-XLVABFJC.js} +0 -0
- /package/chunks/{chunk-N5SVBCUB.js → chunk-XSEU4WQD.js} +0 -0
- /package/chunks/{chunk-CSOUJVKM.js → chunk-Z5HOCNTZ.js} +0 -0
- /package/chunks/{emscripten-module-ZS3PMSDF.js → emscripten-module-3WGSFZYF.js} +0 -0
- /package/chunks/{emscripten-module-XPTEOIWW.js → emscripten-module-74WUXTHL.js} +0 -0
- /package/chunks/{emscripten-module-WYNDFH3N.js → emscripten-module-MCN4Y3N4.js} +0 -0
- /package/chunks/{emscripten-module-RD6P2XH5.js → emscripten-module-NEAT5LGD.js} +0 -0
- /package/chunks/{ffi-ORLOPBB3.js → ffi-JIGPPPF7.js} +0 -0
- /package/chunks/{ffi-IO7WZQNG.js → ffi-RLX77WFG.js} +0 -0
- /package/chunks/{pdfjs-SHZAF7PF.js → pdfjs-2UOWBGC2.js} +0 -0
- /package/chunks/{photon_rs-C52RL4CI.js → photon_rs-MVWYTYTO.js} +0 -0
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { createRequire as __alran_cR } from "module"; import { basename as __alran_basename, dirname as __alran_dirname, join as __alran_join } from "path"; import { fileURLToPath as __alran_fileURLToPath, pathToFileURL as __alran_pathToFileURL } from "url"; const __alran_tuiCurrentModuleDir = __alran_dirname(__alran_fileURLToPath(import.meta.url)); const __alran_tuiPackageRoot = __alran_basename(__alran_tuiCurrentModuleDir) === "chunks" ? __alran_dirname(__alran_tuiCurrentModuleDir) : __alran_tuiCurrentModuleDir; const __alran_tuiPackageEntryUrl = __alran_pathToFileURL(__alran_join(__alran_tuiPackageRoot, "cli.js")).href; const require = __alran_cR(__alran_tuiPackageEntryUrl); const __dirname = __alran_tuiPackageRoot;
|
|
2
|
-
import{a as p}from"./chunk-
|
|
2
|
+
import{a as p}from"./chunk-5DQTVSQV.js";import{e as l}from"./chunk-XQK7JM66.js";var u=l(p(),1);var s=l(p(),1);var E=["localhost","127.0.0.1","::1"];var O=new Set(["http:","https:"]);var x=new Set(["socks5:","socks5h:","socks:"]);var m="http://, https://, socks5://, or socks5h://";var k="SOCKS5 proxy support is experimental and subject to change";var _="ExperimentalWarning";var f=5e3;var C="Set HTTPS_PROXY and HTTP_PROXY to your proxy app's http:// port, or set ALL_PROXY to a socks5:// or socks5h:// URL.";function w(r=process.env,e={}){const n=D(d(r,"ALL_PROXY","all_proxy"),e.writeWarning);const t=d(r,"HTTP_PROXY","http_proxy")??n;const i=d(r,"HTTPS_PROXY","https_proxy")??n??t;if(!t&&!i)return{mode:"direct"};h(t);h(i);return{mode:"proxy",httpProxy:t?.value??"",httpsProxy:i?.value??"",noProxy:U(d(r,"NO_PROXY","no_proxy")?.value)}}function V(r={}){const e=w(r.environment,{writeWarning:r.writeWarning??W});const n=r.createProxyDispatcher??(i=>new c(i));const t=e.mode==="direct"?new s.Agent({allowH2:false}):n({httpProxy:e.httpProxy,httpsProxy:e.httpsProxy,noProxy:e.noProxy});(r.setGlobalDispatcher??u.setGlobalDispatcher)(t);(r.installFetch??$)();return e}function I(r=process.env){const e=w(r);return e.mode==="proxy"?new c(e):new s.Agent({allowH2:false})}function y(r){let e;try{e=new URL(r)}catch{return void 0}if(!e.host)return void 0;const n=e.username||e.password?`${e.password?"***:***":"***"}@`:"";return`${e.protocol}//${n}${e.host}`}function b(r,e=process){const n=e.emitWarning;const t=function i(...o){if(L(o))return;Reflect.apply(n,this,o)};e.emitWarning=t;try{return r()}finally{e.emitWarning=n}}function L(r){const[e,n]=r;const t=typeof e==="string"?e:e instanceof Error?e.message:void 0;if(t!==k)return false;const i=typeof n==="string"?n:typeof n==="object"&&n!==null?n.type:e instanceof Error?e.name:void 0;return i===_}function W(r){process.stderr.write(`${r}
|
|
3
3
|
`)}function d(r,...e){for(const n of e){const t=r[n]?.trim();if(t)return{name:n,value:t}}return void 0}function v(r){let e;try{e=new URL(r)}catch{return{kind:"unsupported",reason:"invalid-url"}}if(!e.hostname)return{kind:"unsupported",reason:"invalid-url"};const n=O.has(e.protocol)?"http":x.has(e.protocol)?"socks5":void 0;if(!n){return{kind:"unsupported",reason:"protocol",protocol:e.protocol,redacted:y(r)}}if(!R(e)){return{kind:"unsupported",reason:"credentials",redacted:y(r)}}return{kind:n}}function R(r){try{return{username:decodeURIComponent(r.username),password:decodeURIComponent(r.password)}}catch{return void 0}}function D(r,e){if(!r)return void 0;const n=v(r.value);if(n.kind!=="unsupported")return r;e?.(`Warning: ignoring ${S(r.name,n)} because ${N(n)}; it will not be used. ${C}`);return void 0}function h(r){if(!r)return;const e=v(r.value);if(e.kind!=="unsupported")return;if(e.reason==="credentials"){throw new Error(`${S(r.name,e)} has a user name or password that is not valid percent-encoding. Encode reserved characters, for example % as %25.`)}throw new Error(`${r.name} must be an ${m} URL.`)}function S(r,e){return e.redacted?`${r}=${e.redacted}`:r}function N(r){if(r.reason==="credentials"){return"its user name or password is not valid percent-encoding (encode % as %25)"}if(!r.protocol)return"it is not a valid proxy URL";return`${r.protocol}// proxies are not supported (use ${m})`}function U(r){const e=[];for(const n of(r??"").split(",")){const t=n.trim();if(t&&!e.includes(t))e.push(t)}for(const n of E){if(!e.includes(n))e.push(n)}return e.join(",")}function $(){u.install?.()}function P(r){const e=new URL(r);if(x.has(e.protocol))return A(e);return new s.ProxyAgent({uri:r,allowH2:false,proxyTls:{allowH2:false},proxyTunnel:true})}function A(r){const e=R(r);if(!e)throw new Error("Proxy user name or password is not valid percent-encoding.");const n=new URL(r.href);n.username="";n.password="";if(n.protocol==="socks5h:")n.protocol="socks5:";const t={connectTimeout:f,connect:X((0,s.buildConnector)({timeout:f})),...e.username?{username:e.username}:{},...e.password?{password:e.password}:{}};return b(()=>new s.Socks5ProxyAgent(n,t))}function X(r){return(e,n)=>r({...e,hostname:g(e.hostname),...e.host===void 0?{}:{host:g(e.host)}},n)}function g(r){return r.startsWith("[")&&r.endsWith("]")?r.slice(1,-1):r}var c=class extends s.Dispatcher{#e=new s.Agent({allowH2:false});#r;#n;#t;#o;constructor(e){super();this.#r=e.httpProxy?P(e.httpProxy):this.#e;this.#n=e.httpsProxy?e.httpsProxy===e.httpProxy?this.#r:P(e.httpsProxy):this.#e;this.#t=[...new Set([this.#e,this.#r,this.#n])];this.#o=e.noProxy}dispatch(e,n){const t=new URL(e.origin??"");if(H(t,this.#o)){return this.#e.dispatch(e,n)}const i=t.protocol==="https:"?this.#n:this.#r;return i.dispatch(e,n)}close(e){const n=Promise.all(this.#t.map(t=>t.close())).then(()=>void 0);if(!e)return n;void n.then(e,e)}destroy(e,n){const t=typeof e==="function"?null:e??null;const i=typeof e==="function"?e:n;const o=Promise.all(this.#t.map(a=>a.destroy(t))).then(()=>void 0);if(!i)return o;void o.then(i,i)}};function H(r,e){const n=T(r.hostname);const t=Number(r.port)||(r.protocol==="https:"?443:80);for(const i of e.split(/[\s,]+/u)){const o=Y(i);if(!o)continue;if(o.hostname==="*")return true;if(o.port!==void 0&&o.port!==t)continue;if(n===o.hostname)return true;if(o.includeSubdomains&&n.endsWith(`.${o.hostname}`))return true}return false}function Y(r){let e=r.trim().toLowerCase();if(!e)return void 0;if(e==="*")return{hostname:"*",includeSubdomains:true};let n;if(e.startsWith("[")){const o=e.indexOf("]");if(o>0){const a=e.slice(o+1);if(/^:\d+$/u.test(a))n=Number(a.slice(1));e=e.slice(1,o)}}else if(e.split(":").length===2){const[o,a]=e.split(":");if(o&&/^\d+$/u.test(a??"")){e=o;n=Number(a)}}const t=e.startsWith(".")||e.startsWith("*");e=e.replace(/^\*?\./u,"");const i=T(e);return i?{hostname:i,port:n,includeSubdomains:t}:void 0}function T(r){return r.toLowerCase().replace(/^\[|\]$/gu,"")}export{w as a,V as b,I as c,y as d,b as e,H as f};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __alran_cR } from "module"; import { basename as __alran_basename, dirname as __alran_dirname, join as __alran_join } from "path"; import { fileURLToPath as __alran_fileURLToPath, pathToFileURL as __alran_pathToFileURL } from "url"; const __alran_tuiCurrentModuleDir = __alran_dirname(__alran_fileURLToPath(import.meta.url)); const __alran_tuiPackageRoot = __alran_basename(__alran_tuiCurrentModuleDir) === "chunks" ? __alran_dirname(__alran_tuiCurrentModuleDir) : __alran_tuiCurrentModuleDir; const __alran_tuiPackageEntryUrl = __alran_pathToFileURL(__alran_join(__alran_tuiPackageRoot, "cli.js")).href; const require = __alran_cR(__alran_tuiPackageEntryUrl); const __dirname = __alran_tuiPackageRoot;
|
|
2
|
-
import{a as y,c as A,d as p}from"./chunk-LZJYNT32.js";import{b as se}from"./chunk-GP52JZMY.js";import{a as re,b as $,c as ne,e as te,f as L,h as ae,i as ie}from"./chunk-
|
|
2
|
+
import{a as y,c as A,d as p}from"./chunk-LZJYNT32.js";import{b as se}from"./chunk-GP52JZMY.js";import{a as re,b as $,c as ne,e as te,f as L,h as ae,i as ie}from"./chunk-IN2Z5SSJ.js";import{b as z,d as H,f as X,h as b,i as G,k as x,l as Y,m as Z,n as W,o as Q,q,r as ee}from"./chunk-PCL2CVVE.js";import{a as U,b as I,c as j,d as F,e as K,f as V}from"./chunk-ZQKVUPKA.js";import{a as _e}from"./chunk-R44C5DM6.js";import{o as S}from"./chunk-VUISZDXX.js";import{e as Be}from"./chunk-XQK7JM66.js";var ge=Be(_e(),1);import{createHash as Je}from"node:crypto";import{existsSync as k,mkdirSync as ce,readFileSync as v,renameSync as de,rmSync as pe,writeFileSync as ue}from"node:fs";import{homedir as De}from"node:os";import c from"node:path";var je="https://cdn.ottili.one/alran-code";var Fe="ALRAN_UPDATE_SOURCE";var Ke=8e3;var R=class{currentVersion;installRoot;releaseBaseUrl;publicKey;environment;dependencies;constructor(e){this.currentVersion=I(e.currentVersion);this.installRoot=e.installRoot??C(e.environment);this.releaseBaseUrl=(e.releaseBaseUrl??(e.environment??process.env)[Fe]?.trim()??je).replace(/\/+$/u,"");if(!/^https:\/\//u.test(this.releaseBaseUrl)&&!/^http:\/\/(127\.0\.0\.1|localhost)(:|\/|$)/u.test(this.releaseBaseUrl)){throw new Error(`Alran update source must be https: ${this.releaseBaseUrl}`)}this.publicKey=e.publicKey;this.environment=e.environment??process.env;this.dependencies={fetchBytes:Xe,installArtifact:Ge,validateInstalledVersion:Ye,...e.dependencies}}async check(e={}){A(e.signal);p(e,"checking",true);const n=e.channel?U(e.channel):ze(this.installRoot);const t=e.version?I(e.version):void 0;const a=t?`${this.releaseBaseUrl}/releases/${encodeURIComponent(t)}/manifest.json`:`${this.releaseBaseUrl}/channels/${n}.json`;const s=this.publicKey??He(this.installRoot,this.environment);const i=oe(e.timeoutMs);const o=new AbortController;const l=le(e.signal,o);let f=false;const d=setTimeout(()=>{f=true;o.abort(new Error(`Alran update check timed out after ${i}ms.`))},i);d.unref?.();try{const[u,h]=await Promise.all([this.dependencies.fetchBytes(a,{signal:o.signal,proxyEnvironment:this.environment}),this.dependencies.fetchBytes(`${a}.sig`,{signal:o.signal,proxyEnvironment:this.environment})]);const g=j(u,h.toString("utf8"),s);if(!t&&g.channel!==n){throw new Error(`Signed Alran release channel mismatch: expected ${n}, got ${g.channel}.`)}if(t&&g.version!==t){throw new Error(`Signed Alran release version mismatch: expected ${t}, got ${g.version}.`)}K(g,F());const m=V(this.currentVersion,g.version);return{status:m<0?"available":m>0?"ahead":"current",channel:n,currentVersion:this.currentVersion,latestVersion:g.version,manifest:g}}catch(u){if(e.signal?.aborted)throw new y;if(f){throw new Error(`Alran update check timed out after ${i}ms.`,{cause:u})}throw u}finally{clearTimeout(d);l()}}async apply(e={}){const n=await this.check(e);if(n.status==="current"){return{...n,applied:false,installRoot:this.installRoot}}if(n.status==="ahead"&&!e.version){throw new Error(`Installed Alran ${this.currentVersion} is newer than ${n.channel} ${n.latestVersion}; pass --to to downgrade explicitly.`)}const t=oe(e.timeoutMs);A(e.signal);p(e,"downloading",true);const a=new AbortController;const s=le(e.signal,a);let i=false;const o=setTimeout(()=>{i=true;a.abort(new Error(`Alran artifact download timed out after ${t}ms.`))},t);o.unref?.();let l;try{l=await this.dependencies.fetchBytes(n.manifest.installArtifact.url,{signal:a.signal,proxyEnvironment:this.environment})}catch(m){if(e.signal?.aborted)throw new y;if(i){throw new Error(`Alran artifact download timed out after ${t}ms.`,{cause:m})}throw m}finally{clearTimeout(o);s()}A(e.signal);Ze(l,n.manifest);const f=c.join(this.installRoot,"versions");const d=c.join(f,n.latestVersion);const u=c.join(f,`.staging-${n.latestVersion}-${process.pid}-${Date.now()}`);const h=c.join(u,`alran-alran-${n.latestVersion}.tgz`);ce(u,{recursive:true});let g=false;try{p(e,"staging",true);A(e.signal);ue(h,l,{mode:384});A(e.signal);p(e,"installing",false);await this.dependencies.installArtifact({artifact:h,prefix:u,registry:n.manifest.registry,proxyEnvironment:this.environment});A(e.signal);S(()=>pe(h,{force:true}));p(e,"validating",false);await this.dependencies.validateInstalledVersion(u,n.latestVersion);A(e.signal);p(e,"activating",false);if(k(d)){await this.dependencies.validateInstalledVersion(d,n.latestVersion);T(u)}else{S(()=>de(u,d));g=true}We(this.installRoot,n.latestVersion);p(e,"completed",false);return{...n,applied:true,installRoot:this.installRoot}}catch(m){T(u);if(g&&Qe(this.installRoot)!==n.latestVersion){T(d)}if(m instanceof y||e.signal?.aborted){throw new y}throw new Error(`Alran ${n.latestVersion} was not activated; the previous version is unchanged: ${me(m)}`,{cause:m})}}};function C(r=process.env){if(r.ALRAN_INSTALL_ROOT)return c.resolve(r.ALRAN_INSTALL_ROOT);if(process.platform==="win32"){const n=r.LOCALAPPDATA;if(!n)throw new Error("LOCALAPPDATA is required to resolve the Alran install root.");return c.join(n,"AlranCode")}const e=r.XDG_DATA_HOME||c.join(De(),".local","share");return c.join(e,"alran-code")}function ze(r){const e=c.join(r,"update.json");if(!k(e))return"stable";let n;try{n=JSON.parse(v(e,"utf8"))}catch(t){throw new Error(`Alran update channel config is invalid: ${me(t)}`)}if(typeof n!=="object"||n===null||!("channel"in n)||typeof n.channel!=="string"){throw new Error("Alran update channel config is missing channel.")}return U(n.channel)}function He(r,e){const n=e.ALRAN_RELEASE_PUBLIC_KEY_FILE;if(n)return v(c.resolve(n),"utf8");const t=c.join(r,"install.json");if(!k(t)){throw new Error("Alran update trust root is missing. Install with the official Shell/PowerShell installer first.")}const a=JSON.parse(v(t,"utf8"));if(typeof a.publicKey!=="string"||!a.publicKey.includes("BEGIN PUBLIC KEY")){throw new Error("Alran installer metadata does not contain a valid release public key.")}return a.publicKey}function oe(r){if(r===void 0)return Ke;if(!Number.isSafeInteger(r)||r<100||r>6e4){throw new Error("Alran update timeout must be an integer between 100 and 60000 milliseconds.")}return r}async function Xe(r,e={}){const[{default:n},{createTuiNetworkDispatcher:t}]=await Promise.all([import("./undici-O4OQVZ6I.js"),import("./network-proxy-AJO7ZW3O.js")]);const a=t(e.proxyEnvironment);try{const s=await n.fetch(r,{signal:e.signal,dispatcher:a,redirect:"error"});if(!s.ok){throw new Error(`Alran release server returned HTTP ${s.status} for ${r}`)}return Buffer.from(await s.arrayBuffer())}finally{await a.close()}}async function Ge(r){const e=process.platform==="win32"?"npm.cmd":"npm";await fe(e,["install","--global","--prefix",r.prefix,r.artifact,"--registry",r.registry,"--no-audit","--no-fund","--package-lock=false"],r.proxyEnvironment,true)}async function Ye(r,e){let n=c.join(r,"bin","alran");let t=["--version"];if(process.platform==="win32"){const s=re(r,b().packageName);const i=JSON.parse(v(c.join(s,"package.json"),"utf8"));const o=ie(i.bin,"alran");if(!o||!k(c.join(r,"alran.cmd"))){throw new Error(`Installed Alran launcher is missing or invalid at ${r}.`)}n=process.execPath;t=[c.join(s,o),"--version"]}const a=await fe(n,t,process.env,true);if(a.trim()!==e){throw new Error(`Installed Alran version mismatch: expected ${e}, got ${a.trim()}`)}}function fe(r,e,n,t=false){return new Promise((a,s)=>{let i=false;const o=(0,ge.default)(r,e,{env:n,shell:false,stdio:t?["ignore","pipe","pipe"]:"inherit",windowsHide:true});const l=[];const f=[];o.stdout?.on("data",d=>l.push(d));o.stderr?.on("data",d=>f.push(d));o.once("error",d=>{if(i)return;i=true;s(d)});o.once("close",(d,u)=>{if(i)return;i=true;if(d===0)return a(Buffer.concat(l).toString("utf8"));const h=Buffer.concat(f).toString("utf8").trim();s(new Error(`${r} failed (${u?`signal ${u}`:`exit ${String(d)}`})${h?`: ${h}`:""}`))})})}function le(r,e){if(!r)return()=>void 0;const n=()=>e.abort(r.reason);if(r.aborted)n();else r.addEventListener("abort",n,{once:true});return()=>r.removeEventListener("abort",n)}function Ze(r,e){if(r.length!==e.installArtifact.size){throw new Error(`Alran artifact checksum/size verification failed: expected ${e.installArtifact.size} bytes, got ${r.length}.`)}const n=Je("sha256").update(r).digest("hex");if(n!==e.installArtifact.sha256){throw new Error("Alran artifact checksum verification failed.")}}function We(r,e){ce(r,{recursive:true});const n=c.join(r,"current");const t=`${n}.tmp-${process.pid}-${Date.now()}`;ue(t,`${e}
|
|
3
3
|
`,{mode:384});S(()=>de(t,n))}function T(r){pe(r,{recursive:true,force:true,maxRetries:4,retryDelay:50})}function Qe(r){const e=c.join(r,"current");if(!k(e))return void 0;return v(e,"utf8").trim()||void 0}function me(r){return r instanceof Error?r.message:String(r)}function Sr(r=process.env){return"A staged Alran update will activate after this process exits."}function Vr(r=process.env){return"Alran update was staged, but its activation journal could not be scheduled."}function he(r){return"Alran npm prefix updater received a non-prefix plan."}function Ae(r){return"Alran npm prefix ownership metadata is missing."}function Pe(r,e={}){if(e.blockingSessionCount===void 0){return`Alran ${r} is already staged. Restarting will resume activation after running Alran sessions exit.`}const n=Math.max(0,Math.trunc(e.blockingSessionCount));if(n>0){return`Alran ${r} is already staged. Activation will wait for ${String(n)} other Alran ${n===1?"session":"sessions"} to exit.`}return`Alran ${r} is already staged. It will activate after this process exits.`}function xe(r,e={}){if(e.blockingSessionCount===void 0){return`Alran ${r} is already active. Restarting will finish update cleanup after running Alran sessions exit.`}const n=Math.max(0,Math.trunc(e.blockingSessionCount));if(n>0){return`Alran ${r} is already active. Update cleanup will wait for ${String(n)} other Alran ${n===1?"session":"sessions"} to exit.`}return`Alran ${r} is already active. Restarting will finish update cleanup.`}function ye(r,e,n){return`Alran update staged ${r}; expected ${e}.`}function ve(r,e=process.env){const n=e.LC_ALL||e.LC_MESSAGES||e.LANG;return se(n,"update.versionedInstalled").replace("{version}",r)}function ke(r,e,n){return`Alran ${r} was not staged; the active installation is unchanged: ${e}`}import{randomUUID as N}from"node:crypto";import{chmodSync as qe,existsSync as O,mkdirSync as M,readdirSync as er,readFileSync as J,renameSync as be,rmSync as B,writeFileSync as $e}from"node:fs";import P from"node:path";var D="releases";var Re="current";var rr=".alran-update.lock";var nr=2;function Ne(r,e,n=process.platform){const t=E(n);return t.join(r,D,`.staging-${e}-${process.pid}-${N()}`)}function Me(r){M(r,{recursive:true,mode:448})}function Ue(r){const e=P.join(r,rr);M(e,{recursive:true,mode:448});const n=`${String(process.pid)}-${N()}.claim`;const t=P.join(e,n);$e(t,"choosing\n",{flag:"wx",mode:384});try{const s=Math.max(0,...Ee(e).map(o=>o.ticket??0))+1;w(t,`${String(s)}
|
|
4
4
|
`,384);const i=Ee(e).some(o=>o.name!==n&&(o.ticket===void 0||o.ticket<s||o.ticket===s&&(o.pid<process.pid||o.pid===process.pid&&o.name.localeCompare(n)<0)));if(i)throw new Error("Another Alran update is already running.")}catch(s){B(t,{force:true});throw s}let a=false;return()=>{if(a)return;a=true;B(t,{force:true})}}function Ie(r,e=process.platform){const n=E(e);const t=n.join(r.activePrefix,D);const a=Le(r.stagingPrefix,r,e);tr(r.stagingPrefix,a,r.runtimeExecutable,e);we(r.stagingPrefix,r,e);M(t,{recursive:true,mode:448});let s=r.expectedVersion;let i=n.join(t,s);if(O(i)){s=`${r.expectedVersion}-repair-${N()}`;i=n.join(t,s)}be(r.stagingPrefix,i);we(i,r,e);sr(r,e);if(!ir(r.activePrefix,e)){ar(r.activePrefix,e)}w(n.join(r.activePrefix,Re),`${s}
|
|
5
5
|
`,384);return i}function Le(r,e,n){const t=$(r,e.packageName,n);if(t.version!==e.expectedVersion){throw new Error(`Alran release contains ${t.version}; expected ${e.expectedVersion}.`)}return t}function we(r,e,n){const t=Le(r,e,n);const a=Te(r,t,e.runtimeExecutable,n);for(const[s,i]of a){if(J(s,"utf8")!==i){throw new Error(`Alran release launcher is invalid: ${s}`)}}}function tr(r,e,n,t){for(const[a,s]of Te(r,e,n,t)){w(a,s,448)}}function Te(r,e,n,t){const a=E(t);const s=new Map;if(!O(n)){throw new Error("Alran versioned launcher runtime is missing.")}for(const i of _(e)){if(!i.binEntry){throw new Error(`Alran versioned ${i.name} package entry is missing.`)}const o=a.join(e.packageRoot,...i.binEntry.split("/"));const l=a.relative(r,o);if(!l||l.startsWith("..")||a.isAbsolute(l)||!O(o)){throw new Error(`Alran versioned ${i.name} launcher path is invalid.`)}if(t==="win32"){s.set(a.join(r,`${i.releaseLauncher}.cmd`),`@ECHO off\r
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { createRequire as __alran_cR } from "module"; import { basename as __alran_basename, dirname as __alran_dirname, join as __alran_join } from "path"; import { fileURLToPath as __alran_fileURLToPath, pathToFileURL as __alran_pathToFileURL } from "url"; const __alran_tuiCurrentModuleDir = __alran_dirname(__alran_fileURLToPath(import.meta.url)); const __alran_tuiPackageRoot = __alran_basename(__alran_tuiCurrentModuleDir) === "chunks" ? __alran_dirname(__alran_tuiCurrentModuleDir) : __alran_tuiCurrentModuleDir; const __alran_tuiPackageEntryUrl = __alran_pathToFileURL(__alran_join(__alran_tuiPackageRoot, "cli.js")).href; const require = __alran_cR(__alran_tuiPackageEntryUrl); const __dirname = __alran_tuiPackageRoot;
|
|
2
|
+
function f(n){return typeof n==="object"&&n!==null&&!Array.isArray(n)}function c(n){if(!f(n)||n.type!=="null")return false;return Object.keys(n).every(t=>t==="type"||t==="description"||t==="title")}function l(n){if(!f(n)||"anyOf"in n||"oneOf"in n||"allOf"in n)return false;if("enum"in n||"const"in n)return false;const{type:t}=n;if(typeof t==="string")return t!=="null";return Array.isArray(t)&&t.length>0&&t.every(e=>typeof e==="string"&&e!=="null")}function p(n){const{anyOf:t,...e}=n;if(!Array.isArray(t)||t.length!==2)return void 0;const r=t.find(l);const i=t.some(c);if(!r||!i)return void 0;const o=Array.isArray(r.type)?r.type:[r.type];return{...r,...e,type:[...o,"null"]}}function a(n){return u(n)}function u(n){if(Array.isArray(n)){let i=false;const o=n.map(s=>{const y=u(s);if(y!==s)i=true;return y});return i?o:n}if(!f(n))return n;const t={};let e=false;for(const[i,o]of Object.entries(n)){const s=u(o);if(s!==o)e=true;t[i]=s}const r=p(t);if(r)return r;return e?t:n}export{a};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { createRequire as __alran_cR } from "module"; import { basename as __alran_basename, dirname as __alran_dirname, join as __alran_join } from "path"; import { fileURLToPath as __alran_fileURLToPath, pathToFileURL as __alran_pathToFileURL } from "url"; const __alran_tuiCurrentModuleDir = __alran_dirname(__alran_fileURLToPath(import.meta.url)); const __alran_tuiPackageRoot = __alran_basename(__alran_tuiCurrentModuleDir) === "chunks" ? __alran_dirname(__alran_tuiCurrentModuleDir) : __alran_tuiCurrentModuleDir; const __alran_tuiPackageEntryUrl = __alran_pathToFileURL(__alran_join(__alran_tuiPackageRoot, "cli.js")).href; const require = __alran_cR(__alran_tuiPackageEntryUrl); const __dirname = __alran_tuiPackageRoot;
|
|
2
|
+
import{a as R}from"./chunk-QKBN5CGI.js";import{a as b}from"./chunk-NMKRNU5O.js";import{b as _}from"./chunk-W5ZOLW7T.js";import{d as T,i as v,l as C}from"./chunk-VLXX22YO.js";import{a as y}from"./chunk-7XYOYZX2.js";function O(i,s){const r={v:1,id:i};if(s)r.phase=s;return JSON.stringify(r)}function A(i){if(!i)return void 0;if(i.startsWith("{")){try{const s=JSON.parse(i);if(s.v===1&&typeof s.id==="string"){if(s.phase==="commentary"||s.phase==="final_answer"){return{id:s.id,phase:s.phase}}return{id:s.id}}}catch{}}return{id:i}}function U(i,s,r,f){const p=[];const l=e=>{const t=e.replace(/[^a-zA-Z0-9_-]/g,"_");const o=t.length>64?t.slice(0,64):t;return o.replace(/_+$/,"")};const m=e=>{const t=`fc_${R(e)}`;return t.length>64?t.slice(0,64):t};const h=(e,t,o)=>{if(!r.has(i.provider))return l(e);if(!e.includes("|"))return l(e);const[x,u]=e.split("|");const c=l(x);const a=o.provider!==i.provider||o.api!==i.api;let d=a?m(u):l(u);if(!d.startsWith("fc_")){d=l(`fc_${d}`)}return`${c}|${d}`};const I=C(s.messages,i,h);const S=f?.includeSystemPrompt??true;if(S&&s.systemPrompt){const e=i.compat;const t=i.reasoning&&e?.supportsDeveloperRole!==false?"developer":"system";p.push({role:t,content:y(s.systemPrompt)})}let n=0;for(const e of I){if(e.role==="user"){if(typeof e.content==="string"){p.push({role:"user",content:[{type:"input_text",text:y(e.content)}]})}else{const t=e.content.map(o=>{if(o.type==="text"){return{type:"input_text",text:y(o.text)}}return{type:"input_image",detail:"auto",image_url:`data:${o.mimeType};base64,${o.data}`}});if(t.length===0)continue;p.push({role:"user",content:t})}}else if(e.role==="assistant"){const t=[];const o=e;const x=o.model!==i.id&&o.provider===i.provider&&o.api===i.api;let u=0;for(const c of e.content){if(c.type==="thinking"){if(c.thinkingSignature){const a=JSON.parse(c.thinkingSignature);t.push(a)}}else if(c.type==="text"){const a=c;const d=A(a.textSignature);const k=u===0?`msg_pi_${n}`:`msg_pi_${n}_${u}`;u++;let g=d?.id;if(!g){g=k}else if(g.length>64){g=`msg_${R(g)}`}t.push({type:"message",role:"assistant",content:[{type:"output_text",text:y(a.text),annotations:[]}],status:"completed",id:g,phase:d?.phase})}else if(c.type==="toolCall"){const a=c;const[d,k]=a.id.split("|");let g=k;if(x&&g?.startsWith("fc_")){g=void 0}t.push({type:"function_call",id:g,call_id:d,name:a.name,arguments:JSON.stringify(a.arguments)})}}if(t.length===0)continue;p.push(...t)}else if(e.role==="toolResult"){const t=e.content.filter(a=>a.type==="text").map(a=>a.text).join("\n");const o=e.content.some(a=>a.type==="image");const x=t.length>0;const[u]=e.toolCallId.split("|");let c;if(o&&i.input.includes("image")){const a=[];if(x){a.push({type:"input_text",text:y(t)})}for(const d of e.content){if(d.type==="image"){a.push({type:"input_image",detail:"auto",image_url:`data:${d.mimeType};base64,${d.data}`})}}c=a}else{c=y(x?t:"(see attached image)")}p.push({type:"function_call_output",call_id:u,output:c})}n++}return p}function V(i,s){const r=s?.strict===void 0?false:s.strict;return i.map(f=>({type:"function",name:f.name,description:f.description,parameters:b(f.parameters),strict:r}))}async function W(i,s,r,f,p){const l=new Map;const m=(n,e)=>{const t=l.get(n);return t?.type===e?t:void 0};const h=(n,e)=>{if(e.type==="reasoning"){const t={type:"thinking",thinking:""};s.content.push(t);const o={type:"thinking",block:t,contentIndex:s.content.length-1};l.set(n,o);r.push({type:"thinking_start",contentIndex:o.contentIndex,partial:s});return o}if(e.type==="message"){const t={type:"text",text:""};s.content.push(t);const o={type:"text",block:t,contentIndex:s.content.length-1};l.set(n,o);r.push({type:"text_start",contentIndex:o.contentIndex,partial:s});return o}if(e.type==="function_call"){const t={type:"toolCall",id:`${e.call_id}|${e.id}`,name:e.name,arguments:{},partialJson:e.arguments||""};s.content.push(t);const o={type:"toolCall",block:t,contentIndex:s.content.length-1};l.set(n,o);r.push({type:"toolcall_start",contentIndex:o.contentIndex,partial:s});return o}return void 0};const I=(n,e)=>{return l.get(n)??h(n,e)};const S=v(i,p?.onProviderStreamEvent,f);for await(const n of S){if(n.type==="response.created"){s.responseId=n.response.id}else if(n.type==="response.output_item.added"){h(n.output_index,n.item)}else if(n.type==="response.reasoning_summary_text.delta"){const e=m(n.output_index,"thinking");if(!e)continue;e.block.thinking+=n.delta;r.push({type:"thinking_delta",contentIndex:e.contentIndex,delta:n.delta,partial:s})}else if(n.type==="response.reasoning_summary_part.done"){const e=m(n.output_index,"thinking");if(!e)continue;e.block.thinking+="\n\n";r.push({type:"thinking_delta",contentIndex:e.contentIndex,delta:"\n\n",partial:s})}else if(n.type==="response.reasoning_text.delta"){const e=m(n.output_index,"thinking");if(!e)continue;e.block.thinking+=n.delta;r.push({type:"thinking_delta",contentIndex:e.contentIndex,delta:n.delta,partial:s})}else if(n.type==="response.output_text.delta"){const e=m(n.output_index,"text");if(!e)continue;e.block.text+=n.delta;r.push({type:"text_delta",contentIndex:e.contentIndex,delta:n.delta,partial:s})}else if(n.type==="response.refusal.delta"){const e=m(n.output_index,"text");if(!e)continue;e.block.text+=n.delta;r.push({type:"text_delta",contentIndex:e.contentIndex,delta:n.delta,partial:s})}else if(n.type==="response.function_call_arguments.delta"){const e=m(n.output_index,"toolCall");if(!e)continue;e.block.partialJson+=n.delta;e.block.arguments=_(e.block.partialJson);r.push({type:"toolcall_delta",contentIndex:e.contentIndex,delta:n.delta,partial:s})}else if(n.type==="response.function_call_arguments.done"){const e=m(n.output_index,"toolCall");if(!e)continue;const t=e.block.partialJson;e.block.partialJson=n.arguments;e.block.arguments=_(e.block.partialJson);if(n.arguments.startsWith(t)){const o=n.arguments.slice(t.length);if(o.length>0){r.push({type:"toolcall_delta",contentIndex:e.contentIndex,delta:o,partial:s})}}}else if(n.type==="response.output_item.done"){const e=n.item;const t=I(n.output_index,e);if(e.type==="reasoning"&&t?.type==="thinking"){const o=e.summary?.map(u=>u.text).join("\n\n")||"";const x=e.content?.map(u=>u.text).join("\n\n")||"";t.block.thinking=o||x||t.block.thinking;t.block.thinkingSignature=JSON.stringify(e);r.push({type:"thinking_end",contentIndex:t.contentIndex,content:t.block.thinking,partial:s});l.delete(n.output_index)}else if(e.type==="message"&&t?.type==="text"){t.block.text=e.content?.map(o=>o.type==="output_text"?o.text:o.refusal).join("")||"";t.block.textSignature=O(e.id,e.phase??void 0);r.push({type:"text_end",contentIndex:t.contentIndex,content:t.block.text,partial:s});l.delete(n.output_index)}else if(e.type==="function_call"&&t?.type==="toolCall"){t.block.arguments=_(e.arguments||t.block.partialJson||"{}");delete t.block.partialJson;r.push({type:"toolcall_end",contentIndex:t.contentIndex,toolCall:t.block,partial:s});l.delete(n.output_index)}}else if(n.type==="response.completed"){const e=n.response;if(e?.id){s.responseId=e.id}if(e?.usage){const t=e.usage.input_tokens_details?.cached_tokens||0;s.usage={input:(e.usage.input_tokens||0)-t,output:e.usage.output_tokens||0,cacheRead:t,cacheWrite:0,totalTokens:e.usage.total_tokens||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}T(f,s.usage);if(p?.applyServiceTierPricing){const t=p.resolveServiceTier?p.resolveServiceTier(e?.service_tier,p.serviceTier):e?.service_tier??p.serviceTier;p.applyServiceTierPricing(s.usage,t)}s.stopReason=P(e?.status);if(s.content.some(t=>t.type==="toolCall")&&s.stopReason==="stop"){s.stopReason="toolUse"}}else if(n.type==="error"){throw new Error(`Error Code ${n.code}: ${n.message}`||"Unknown error")}else if(n.type==="response.failed"){const e=n.response?.error;const t=n.response?.incomplete_details;const o=e?`${e.code||"unknown"}: ${e.message||"no message"}`:t?.reason?`incomplete: ${t.reason}`:"Unknown error (no error details in response)";throw new Error(o)}}}function P(i){if(!i)return"stop";switch(i){case"completed":return"stop";case"incomplete":return"length";case"failed":case"cancelled":return"error";case"in_progress":case"queued":return"stop";default:{const s=i;throw new Error(`Unhandled stop reason: ${s}`)}}}export{U as a,V as b,W as c};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { createRequire as __alran_cR } from "module"; import { basename as __alran_basename, dirname as __alran_dirname, join as __alran_join } from "path"; import { fileURLToPath as __alran_fileURLToPath, pathToFileURL as __alran_pathToFileURL } from "url"; const __alran_tuiCurrentModuleDir = __alran_dirname(__alran_fileURLToPath(import.meta.url)); const __alran_tuiPackageRoot = __alran_basename(__alran_tuiCurrentModuleDir) === "chunks" ? __alran_dirname(__alran_tuiCurrentModuleDir) : __alran_tuiCurrentModuleDir; const __alran_tuiPackageEntryUrl = __alran_pathToFileURL(__alran_join(__alran_tuiPackageRoot, "cli.js")).href; const require = __alran_cR(__alran_tuiPackageEntryUrl); const __dirname = __alran_tuiPackageRoot;
|
|
2
|
+
import{a as Q}from"./chunk-3GGKARES.js";import{b as f}from"./chunk-6UXSIWCB.js";import{b as E,c as R,d as O,e as y,f as b,g as $,h as U,i as D,j as N,k as B,l as j,m as T,n as S,p as z,q as M,t as F,u as H}from"./chunk-5RIMHTEU.js";import{c as k}from"./chunk-5Y76VFHY.js";import{Sb as P,Za as _,eb as Y,fb as V,hb as I,ib as J,jb as G,la as W,lb as v,pb as q,qb as X}from"./chunk-XVGPB7TW.js";import{randomBytes as ie}from"node:crypto";import{createInterface as ge}from"node:readline/promises";import{cwd as me,stderr as ye,stdin as x,stdout as Z}from"node:process";import{isAbsolute as le,resolve as ce}from"node:path";import{spawn as de}from"node:child_process";import{fileURLToPath as ue}from"node:url";function h(e){return r=>pe(r,e)}function pe(e,r){const n=fe(e,r);const[t,o]=process.platform==="darwin"?["open",[n]]:process.platform==="win32"?["rundll32",["url.dll,FileProtocolHandler",n]]:["xdg-open",[n]];return new Promise((i,s)=>{const l=de(t,o,{detached:true,stdio:"ignore",windowsHide:true});l.once("error",s);l.once("spawn",()=>{l.unref();i()})})}function fe(e,r){if(/^https?:\/\//iu.test(e))return e;if(/^file:\/\//iu.test(e))return ue(e);return le(e)?e:ce(r,e)}async function he(e,r={}){const n=r.fetchImpl??fetch;let t;try{t=r.baseUrl??Y()}catch(o){return{kind:"unconfirmed",detail:o instanceof Error?o.message:String(o)}}try{const o=await n(`${t.replace(/\/+$/u,"")}/models`,{headers:{authorization:`Bearer ${e}`,accept:"application/json"},signal:AbortSignal.timeout(r.timeoutMs??8e3)});if(o.status===401)return{kind:"rejected",detail:"HTTP 401: invalid or revoked key"};if(o.ok){const i=await o.json().catch(()=>null);return{kind:"verified",models:Array.isArray(i?.data)?i.data.length:0}}return{kind:"unconfirmed",detail:`HTTP ${o.status}`}}catch(o){const i=o instanceof Error?o.name:"";return{kind:"unconfirmed",detail:i==="TimeoutError"?"no answer in time":"the platform could not be reached"}}}async function we(e){const r=e.trim();if(!I(r)){throw new Error(`Invalid Ottili API key: expected a key starting with "${_}".`)}await P(n=>{n.alran_api={...n.alran_api??{},apiKey:r};n.alranModelSource="alran_api_key"})}async function ve(){await P(e=>{if(!e.alran_api){e.alranModelSource=void 0;return}const r={...e.alran_api};delete r.apiKey;e.alran_api=Object.keys(r).length>0?r:void 0;e.alranModelSource=void 0})}async function Ae(e,r){if(!x.isTTY){r("Reading the Ottili API key from stdin\u2026\n");const t=[];for await(const o of x)t.push(Buffer.from(o));return Buffer.concat(t).toString("utf8").trim()}const n=ge({input:x,output:Z,terminal:true});try{e("Paste your Ottili API key: ");const t=await n.question("");e("\n");return t.trim()}finally{n.close()}}async function ee(e={}){const r=e.write??(s=>Z.write(s));const n=e.writeError??(s=>ye.write(s));const t=e.consoleUrl??G();n(`Open this page to create an Ottili API key:
|
|
3
|
+
${t}
|
|
4
|
+
`);if(e.openBrowser!==false){const s=e.openExternalTarget??h(me());try{await s(t)}catch{n("Couldn't open the default browser. Open the URL above manually.\n")}}const o=await(e.readApiKey??(()=>Ae(r,n)))();if(!I(o)){throw new Error(`Invalid Ottili API key: expected a key starting with "${_}".`)}const i=await(e.verifyKey??(s=>he(s)))(o);if(i.kind==="rejected"){throw new Error(`The Ottili AI Platform rejected this API key (${i.detail}). Nothing was saved. Create a new key at ${t}.`)}await(e.storeKey??we)(o);return{apiKey:o,consoleUrl:t,message:i.kind==="verified"?`Signed in to the Ottili AI Platform with your Ottili API key. The platform accepted it${i.models>0?` (${i.models} model${i.models===1?"":"s"} available)`:""}.`:`Your Ottili API key was saved, but the platform could not confirm it (${i.detail}). It is used for the next request; run \`alran status\` to see whether the platform answers.`}}async function re(e={}){await(e.clearKey??ve)();return"Signed out of the Ottili AI Platform. The stored API key was removed."}import{hostname as Ee}from"node:os";var Oe="urn:ietf:params:oauth:grant-type:device_code";var d=class extends Error{constructor(n,t){super(n);this.code=t;this.name="DeviceLoginError"}code};var be=15e3;var Te=4;var Se=1;var _e=(e,r)=>new Promise((n,t)=>{if(r?.aborted)return t(r.reason);const o=setTimeout(()=>{r?.removeEventListener("abort",i);n()},e);const i=()=>{clearTimeout(o);t(r?.reason)};r?.addEventListener("abort",i,{once:true})});function ne(e=process.env,r=process.platform){const n=e.ALRAN_LOGIN_FLOW?.trim().toLowerCase();if(n==="device")return true;if(n==="browser")return false;if(e.SSH_CONNECTION||e.SSH_TTY||e.SSH_CLIENT)return true;if(r==="linux"&&!e.DISPLAY&&!e.WAYLAND_DISPLAY)return true;return false}function Ie(e){const r=Math.max(1,Math.round(e.expires_in/60));return["","To sign in, open this page in a browser on any device:",` ${e.verification_uri}`,"",`and enter the code: ${e.user_code}`,...e.verification_uri_complete?["",`or open it directly: ${e.verification_uri_complete}`]:[],"",`The code is valid for ${r} minutes. Waiting for you to confirm\u2026 (Ctrl+C to cancel)`,""].join("\n")}async function te(e,r,n,t){const o=AbortSignal.timeout(be);const i=await e(r,{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify(n),signal:t?AbortSignal.any([t,o]):o});let s={};try{s=await i.json()}catch{}return{status:i.status,body:s&&typeof s==="object"?s:{}}}function Pe(e){const r=o=>typeof e[o]==="string"?e[o]:"";const n=(o,i)=>typeof e[o]==="number"&&Number.isFinite(e[o])?e[o]:i;const t={device_code:r("device_code"),user_code:r("user_code"),verification_uri:r("verification_uri"),verification_uri_complete:r("verification_uri_complete")||void 0,expires_in:n("expires_in",600),interval:Math.max(Se,n("interval",5))};if(!t.device_code||!t.user_code||!/^https?:\/\//u.test(t.verification_uri)){throw new d("The sign-in service answered without a device code.","refused")}return t}function ke(e){const r=t=>typeof e[t]==="string"?e[t].trim():"";const n={sessionId:r("session_id"),companyId:r("company_id"),subjectId:r("subject_id"),baseUrl:r("platform_base_url").replace(/\/+$/u,"")};if(!n.sessionId||!n.companyId||!n.subjectId||!/^https?:\/\//u.test(n.baseUrl)){throw new d("The sign-in service answered without a session.","refused")}return n}async function oe(e){const r=e.fetchImpl??fetch;const n=e.sleep??_e;const t=e.now??Date.now;const o=e.gatewayBaseUrl.replace(/\/+$/u,"");let i;try{const a=await te(r,`${o}/auth/device`,{client:"alran-code",device_name:e.deviceName??xe()},e.signal);if(a.status===404){throw new d("This Ottili AI Platform does not offer the device sign-in yet. Use `alran auth login --no-device`, or `alran auth login --api-key`.","refused")}if(a.status===429)throw new d("Too many sign-in attempts. Wait a minute and try again.","unavailable");if(a.status!==200)throw new d(`The sign-in service refused the request (HTTP ${a.status}).`,"refused");i=Pe(a.body)}catch(a){if(a instanceof d)throw a;if(e.signal?.aborted)throw new d("Sign-in cancelled.","aborted");throw new d(`Cannot reach the Ottili AI Platform at ${o}. Check the connection and try again.`,"unavailable")}e.write(Ie(i));const s=t()+i.expires_in*1e3;let l=i.interval;let c=0;for(;;){try{await n(l*1e3,e.signal)}catch{throw new d("Sign-in cancelled.","aborted")}if(t()>s)throw new d("The code expired before it was confirmed. Run `alran auth login` again.","expired");let a;try{a=await te(r,`${o}/auth/device/token`,{grant_type:Oe,device_code:i.device_code},e.signal);c=0}catch{if(e.signal?.aborted)throw new d("Sign-in cancelled.","aborted");c+=1;if(c>=Te){throw new d(`Lost the connection to the Ottili AI Platform at ${o}. Run \`alran auth login\` again.`,"unavailable")}continue}if(a.status===200)return ke(a.body);const u=typeof a.body.error==="string"?a.body.error:"";if(u==="authorization_pending")continue;if(u==="slow_down"){l=typeof a.body.interval==="number"&&a.body.interval>l?a.body.interval:l+5;continue}if(u==="access_denied")throw new d("Sign-in was cancelled in the browser.","denied");if(u==="expired_token")throw new d("The code expired before it was confirmed. Run `alran auth login` again.","expired");if(a.status===429){l+=5;continue}throw new d(`The sign-in service answered with an error (${u||`HTTP ${a.status}`}).`,"refused")}}function xe(){try{return Ee().slice(0,64)}catch{return"unknown device"}}function L(){return v(k().buildEnv)}async function sr(e={}){const r=e.writeError??(t=>process.stderr.write(t));if(e.provider==="keycloak"){return $e({region:e.region,openBrowser:e.openBrowser!==false,openExternalTarget:e.openExternalTarget,writeError:r})}if(e.provider==="platform"){if(e.device??ne()){return Re({platformEnv:e.platformEnv??L(),writeError:r,...e.deviceAuthorization?{overrides:e.deviceAuthorization}:{}})}return Ue({platformEnv:e.platformEnv??L(),openBrowser:e.openBrowser!==false,openExternalTarget:e.openExternalTarget,writeError:r})}const n=await ee({...e.readApiKey?{readApiKey:e.readApiKey}:{},...e.storeKey?{storeKey:e.storeKey}:{},...e.verifyKey?{verifyKey:e.verifyKey}:{},consoleUrl:e.consoleUrl??J(b(L())),...e.openExternalTarget?{openExternalTarget:e.openExternalTarget}:{},openBrowser:e.openBrowser!==false,writeError:r});return n.message}function Le(){const e=k({runtimeRegion:W()});const r=[{buildEnv:e.buildEnv,region:e.region},{buildEnv:"prod",region:e.region},{buildEnv:"prod",region:"en"}];const n=new Set;return r.filter(t=>{const o=`${t.buildEnv}/${t.region}`;if(n.has(o))return false;n.add(o);return true})}function Ce(e,r){return Q({dataDir:e,...r,oauthEndpoints:z(process.env,r)})}async function Ke(e,r){const n=`${r.buildEnv}/${r.region}`;try{const t=await e.logout({revoke:true});if(t.status==="anonymous")return void 0;const o=await e.logout({revoke:false});return o.status==="anonymous"?`Could not revoke the ${n} OAuth grant at the server; the token was removed from this machine and expires on its own.`:`Could not remove the ${n} OAuth credential from this machine.`}catch(t){return`Could not clear the ${n} OAuth credential (${t instanceof Error?t.message:String(t)}).`}}async function lr(e={}){const r=f();const n=e.writeError??(i=>process.stderr.write(i));for(const i of X(v())){q(r,i)}const t=e.sharedAuthLogoutFor??(i=>Ce(r,i));const o=[];for(const i of Le()){let s;try{s=t(i)}catch(c){o.push(`Could not open the ${i.buildEnv}/${i.region} OAuth credential (${c instanceof Error?c.message:String(c)}).`);continue}const l=await Ke(s,i);if(l)o.push(l)}for(const i of o)n(`${i}
|
|
5
|
+
`);return re({...e.clearKey?{clearKey:e.clearKey}:{}})}async function Re(e){const r=new AbortController;const n=()=>r.abort(new Error("interrupted"));process.once("SIGINT",n);let t;try{t=await oe({gatewayBaseUrl:V(e.platformEnv),write:e.writeError,signal:r.signal,...e.overrides})}finally{process.removeListener("SIGINT",n)}const o=`${f()}/auth/platform/${e.platformEnv}`;const{mkdir:i}=await import("node:fs/promises");await i(o,{recursive:true});await ae(o,t);return`Signed in to the Ottili AI Platform (${e.platformEnv==="prod"?"production":"development"}) with a device code.`}async function $e(e){const r=e.writeError??(u=>process.stderr.write(u));const n=e.region??"en";const t="prod";const o=C("ALRAN_KEYCLOAK_AUTHORIZATION_ENDPOINT",`https://${y}/realms/alran/protocol/openid-connect/auth`);const i=C("ALRAN_KEYCLOAK_TOKEN_ENDPOINT",`https://${y}/realms/alran/protocol/openid-connect/token`);const s=C("ALRAN_KEYCLOAK_REVOCATION_ENDPOINT",`https://${y}/realms/alran/protocol/openid-connect/revoke`);const l=D({dataDir:f(),buildEnv:t,region:n});const c=new F({namespace:l,credentialStore:H({authHome:l.namespaceHome}),oauthClient:new B({deviceAuthorizationEndpoint:`https://${y}/realms/alran/protocol/openid-connect/auth/device`,tokenEndpoint:i,revocationEndpoint:s}),initialize:()=>N(l)});let a;try{const u=ie(16).toString("base64url");a=new T({port:0,host:"127.0.0.1",baseUrl:"http://127.0.0.1",expectedState:u,onLogin:async p=>{await De(c,p)}});await a.start();const g=a.port;if(g===null){throw new Error("Callback server failed to start.")}const w=`http://127.0.0.1:${g}/callback`;const A=new j({authorizationEndpoint:o,tokenEndpoint:i,revocationEndpoint:s,redirectUri:w,clientId:E,scopes:R,audience:O});a.setClient(A);const m=await a.beginLogin();r(`Open this page to sign in with keycloak:
|
|
6
|
+
${m}
|
|
7
|
+
`);if(e.openBrowser!==false){const p=e.openExternalTarget??h(process.cwd());try{await p(m)}catch{r("Couldn't open the default browser. Open the URL above manually.\n")}}await a.waitForLogin();if((await c.getStatus()).status!=="authenticated"){throw new Error("Keycloak login succeeded but no credential was stored.")}return`Signed in to the Ottili AI Platform with keycloak (${Ne(n)}).`}finally{if(a){try{await a.close()}catch{}}}}async function Ue(e){const r=e.writeError??(a=>process.stderr.write(a));const n=b(e.platformEnv);const t=f();const o=`${t}/auth/platform/${e.platformEnv}`;const{mkdir:i}=await import("node:fs/promises");await i(o,{recursive:true});const s=$(e.platformEnv);const l=U(s);let c;try{const a=ie(16).toString("base64url");c=new T({baseUrl:l.origin,callbackUri:l.uri,platformOidc:{platformBaseUrl:n},onLogin:async p=>{const K=p.platformSession;if(!K){throw new Error("Platform OIDC login succeeded but no session was returned.")}await ae(o,K)}});try{await c.start()}catch(p){if(p.code==="EADDRINUSE"){throw new Error(`Cannot listen on ${l.uri}: the port is already in use. Close the other login, or set ALRAN_OIDC_CALLBACK_URI to a URI registered on the Platform.`)}throw p}const u=c.port;if(u===null){throw new Error("Callback server failed to start.")}const g=c.platformOidcAuthorizeUrl();r(`Open this page to sign in with the Ottili Platform:
|
|
8
|
+
${g}
|
|
9
|
+
`);if(e.openBrowser!==false){const p=e.openExternalTarget??h(process.cwd());try{await p(g)}catch{r("Couldn't open the default browser. Open the URL above manually.\n")}}await c.waitForLogin();const w=await se(o);if(!w){throw new Error("Platform OIDC login succeeded but no session was stored.")}const A=new S(w);const m=await A.get("/v2/version");if(!m.ok){throw new Error(`Platform session stored but /v2/version returned HTTP ${m.status}.`)}return`Signed in to the Ottili AI Platform (${e.platformEnv==="prod"?"production":"development"}).`}finally{if(c){try{await c.close()}catch{}}}}function C(e,r){const n=process.env[e];if(n?.trim())return n.trim();return r}async function De(e,r){const n=Date.now();await e.commitExternalLogin(({generation:t,loginEpoch:o})=>({schemaVersion:M,accessToken:r.accessToken??"",refreshToken:r.refreshToken??"",tokenType:"Bearer",clientId:E,scopes:r.scopes??[],audience:O,expiresAtMs:n+(r.expiresInSec??3600)*1e3,generation:t,loginEpoch:o,...r.subject?{subject:r.subject}:{},...r.accountId?{accountId:r.accountId}:{}}))}async function ae(e,r){const{writePrivateConfigFileSync:n}=await import("./src-5PSNGHHD.js");const{chmod:t}=await import("node:fs/promises");if(process.platform!=="win32")await t(e,448).catch(()=>void 0);const o={...r,via:"oidc",storedAtMs:Date.now()};n(`${e}/platform-session.json`,JSON.stringify(o,null,2))}async function se(e){const{readFile:r}=await import("node:fs/promises");try{const n=await r(`${e}/platform-session.json`,"utf8");const t=JSON.parse(n);return{sessionId:typeof t.sessionId==="string"?t.sessionId:"",companyId:typeof t.companyId==="string"?t.companyId:"",subjectId:typeof t.subjectId==="string"?t.subjectId:"",baseUrl:typeof t.baseUrl==="string"?t.baseUrl:"",via:"oidc",storedAtMs:typeof t.storedAtMs==="number"?t.storedAtMs:0}}catch{return null}}function Ne(e){return e==="cn"?"Alran China":"Alran Global"}async function cr(e=v()){const r=f();const n=`${r}/auth/platform/${e}`;const t=await se(n);if(!t)return null;return new S({sessionId:t.sessionId,companyId:t.companyId,baseUrl:t.baseUrl})}export{h as a,ve as b,ee as c,sr as d,lr as e,cr as f};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __alran_cR } from "module"; import { basename as __alran_basename, dirname as __alran_dirname, join as __alran_join } from "path"; import { fileURLToPath as __alran_fileURLToPath, pathToFileURL as __alran_pathToFileURL } from "url"; const __alran_tuiCurrentModuleDir = __alran_dirname(__alran_fileURLToPath(import.meta.url)); const __alran_tuiPackageRoot = __alran_basename(__alran_tuiCurrentModuleDir) === "chunks" ? __alran_dirname(__alran_tuiCurrentModuleDir) : __alran_tuiCurrentModuleDir; const __alran_tuiPackageEntryUrl = __alran_pathToFileURL(__alran_join(__alran_tuiPackageRoot, "cli.js")).href; const require = __alran_cR(__alran_tuiPackageEntryUrl); const __dirname = __alran_tuiPackageRoot;
|
|
2
|
-
import{b as _}from"./chunk-ZQKVUPKA.js";import{a as T}from"./chunk-ZQOALVGL.js";import{e as M}from"./chunk-XQK7JM66.js";var k=M(T(),1);import{accessSync as L,constants as j,existsSync as N,readFileSync as b,realpathSync as f,statSync as y}from"node:fs";import u from"node:path";var E="https://registry.npmjs.org/";var B=3e4;var v="alran";var $=["@ottili/alran-code","@ottili/code"];function ie(e){return $.includes(e??"")}var x=[v,...$];var C=v;function O(e){const n=u.join(e,"install.json");try{const r=JSON.parse(b(n,"utf8"));return r.product==="alran-code"&&r.updateOwner==="alran-installer"}catch{return false}}async function se(e){const n=e.platform??process.platform;const r={installRoot:e.installRoot,platform:n,packageRoot:e.packageRoot??Y,npmGlobalPrefix:e.npmGlobalPrefix??(()=>D(n==="win32"?"npm.cmd":"npm",["prefix","--global"])),managedInstall:e.managedInstall??O,prefixInstall:e.prefixInstall??W};if(r.managedInstall(r.installRoot))return"managed-installer";if(r.prefixInstall())return"npm-prefix";const o=r.packageRoot();if(!o)return"unsupported";const a=J(o);if(a)return a;try{return G(o,await r.npmGlobalPrefix(),n)}catch{return"unsupported"}}function J(e){const n=e.replaceAll("\\","/").toLocaleLowerCase();const r=U();if(new RegExp(`\\/pnpm\\/global\\/(?:v11\\/[^/]+|[^/]+)\\/node_modules\\/${r}$`,"u").test(n)){return"pnpm-global"}if(new RegExp(`\\/(?:\\.config\\/yarn|\\.yarn)\\/global\\/node_modules\\/${r}$`,"u").test(n)){return"yarn-global"}if(new RegExp(`\\/\\.bun\\/install\\/global\\/node_modules\\/${r}$`,"u").test(n)){return"bun-global"}if(new RegExp(`\\/(?:lib|npm)\\/node_modules\\/${r}$`,"u").test(n)){return"npm-global"}return void 0}function U(){const e=x.map(n=>n.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&").replaceAll("/","\\/"));return`(?:${e.join("|")})`}function w(e=K()??C,n){if(!x.includes(e)){throw new Error(`Unsupported Alran npm package: ${String(e)}`)}const r=n?new URL(n).href:E;if(r!==E){throw new Error(`Unsupported Alran npm registry: ${r}`)}return{packageName:e,registry:r}}function le(e=V(),n=F()){if(n)return n;if(e==="test")return"test";if(e==="staging")return"preview";return"latest"}function G(e,n,r=process.platform){const o=g(e,r);const a=r==="win32"?u.win32:u.posix;const i=re(e)??v;const t=r==="win32"?[a.join(n,"node_modules",i)]:[a.join(n,"lib","node_modules",i),a.join(n,"node_modules",i)];return t.some(s=>g(s,r)===o)?"npm-global":"unsupported"}function ce(e,n,r=process.platform,o=w(),a){const i=["latest","preview","test"].includes(n)?n:_(n);const t=`${o.packageName}@${i}`;const s=["--registry",o.registry];const c=`--registry ${o.registry}`;const l=["--ignore-scripts=false","--include=optional",`--allow-scripts=${o.packageName},better-sqlite3`];const d=l.join(" ");switch(e){case"npm-prefix":{if(!a)throw new Error("Alran npm prefix ownership metadata is missing.");if(a.packageName!==o.packageName||new URL(a.registry).href!==o.registry){throw new Error("Alran npm prefix ownership does not match the installed package.")}return{executable:a.executable,args:["install","--global","--prefix",a.prefix,t,...l,...s],display:`${a.executable} install --global --prefix ${a.prefix} ${t} ${d} ${c}`}}case"npm-global":return{executable:r==="win32"?"npm.cmd":"npm",args:["install","--global",t,...l,...s],display:`npm install --global ${t} ${d} ${c}`};case"pnpm-global":return{executable:r==="win32"?"pnpm.cmd":"pnpm",args:["add","--global",t,...s],display:`pnpm add --global ${t} ${c}`};case"yarn-global":return{executable:r==="win32"?"yarn.cmd":"yarn",args:["global","add",t,...s],display:`yarn global add ${t} ${c}`};case"bun-global":return{executable:r==="win32"?"bun.exe":"bun",args:["add","--global",t,...s],display:`bun add --global ${t} ${c}`}}}async function ue(e,n={}){const r=n.platform??process.platform;const o=n.distribution??w();const a=n.run??((l,d)=>{const p={executable:l,args:d,display:l};const A=n.runtimeExecutable?H(p,n.runtimeExecutable):p;return D(A.executable,A.args,n.environment)});const i=n.npmExecutable??(r==="win32"?"npm.cmd":"npm");const t=await a(i,["view",`${o.packageName}@${e}`,"version","--json","--registry",o.registry,"--fetch-timeout",String(B)]);let s;try{s=JSON.parse(t)}catch{s=t.trim()}if(Array.isArray(s)){if(s.length!==1){throw new Error("Alran registry returned an invalid latest version.")}s=s[0]}if(typeof s!=="string"){throw new Error("Alran registry returned an invalid latest version.")}const c=_(s);if(e==="latest"&&c.includes("-")){throw new Error("Alran latest must resolve to a stable semantic version.")}return c}function V(){if(false)return void 0;return"prod"}function F(){if(false)return void 0;return"latest"}function H(e,n){const r=f(e.executable);const o=u.dirname(r);const a=[...u.basename(r)==="npm-cli.js"?[r]:[],u.join(o,"node_modules","npm","bin","npm-cli.js"),u.join(o,"..","lib","node_modules","npm","bin","npm-cli.js")];const i=a.find(t=>N(t)&&y(t).isFile())??z(r);if(!i)throw new Error(`Cannot locate npm-cli.js for the owned npm executable: ${e.executable}`);return{...e,executable:n,args:[i,...e.args]}}function z(e){try{const n=y(e);if(!n.isFile()||n.size>64*1024)return void 0;const r=b(e,"utf8").split(/\r?\n/u);if(r[0]!=="#!/bin/sh")return void 0;const o=r.map(l=>l.trim()).filter(l=>/^exec\s/u.test(l));if(o.length===0)return void 0;const a=o.map(l=>/^exec (?:"\$basedir\/node"|node) "\$basedir\/(nodejs\/\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?\/lib\/node_modules\/npm\/bin\/npm-cli\.js)" "\$@"$/u.exec(l)?.[1]);const i=a[0];if(!i||a.some(l=>l!==i))return void 0;const t=u.dirname(e);const s=u.join(t,...i.split("/").slice(0,2));const c=f(u.join(t,i));if(!S(s,c,u)||!y(c).isFile())return void 0;return c}catch{return void 0}}function de(e,n,r=process.platform){const o=r==="win32"?u.win32:u.posix;const a={...e};const i=Object.keys(a).filter(s=>r==="win32"?s.toLowerCase()==="path":s==="PATH").sort();const t=a[i[0]??"PATH"];for(const s of i)delete a[s];a.PATH=[o.dirname(n),t].filter(Boolean).join(o.delimiter);return a}function pe(e,n=process.env,r={}){return new Promise((o,a)=>{let i=false;const t=(0,k.default)(e.executable,[...e.args],{env:n,shell:false,stdio:["ignore","pipe","pipe"],windowsHide:true});const s=[];const c=[];t.stdout?.on("data",l=>{s.push(l);h(r,l)});t.stderr?.on("data",l=>{c.push(l);h(r,l)});t.once("error",l=>{if(i)return;i=true;a(l)});t.once("exit",(l,d)=>{if(i)return;i=true;if(l===0){o();return}const p=Buffer.concat([...c,...s]).toString("utf8").trim();a(new Error(`${e.executable} failed (${d?`signal ${d}`:`exit ${String(l)}`})${p?`: ${p}`:""}`))})})}function h(e,n){try{e.onOutput?.(n.toString("utf8"))}catch{}}function K(e=process.argv[1]){return P(e)?.packageName}function ge(e=process.argv[1]){return P(e)?.version}function W(e=process.argv[1],n=process.platform,r=process.execPath){const o=P(e);if(!o)return void 0;const a=n==="win32"?u.win32:u.posix;let i=o.packageRoot;for(let p=0;p<o.packageName.split("/").length;p+=1){i=a.dirname(i)}if(a.basename(i).toLocaleLowerCase()!=="node_modules")return void 0;const t=a.dirname(i);const s=n!=="win32"&&a.basename(t)==="lib"?a.dirname(t):t;const c=Z(s,o.packageRoot,n,a);if(c){if(c.packageName!==o.packageName)return void 0;return c}if(a.basename(s).toLocaleLowerCase()!==".alran-code")return void 0;const l=a.join(a.dirname(r),n==="win32"?"npm.cmd":"npm");if(!N(l))return void 0;const d=w(o.packageName);return{executable:l,packageName:o.packageName,prefix:s,registry:d.registry}}function Y(e=process.argv[1]){return P(e)?.packageRoot}function P(e){if(!e)return void 0;let n;try{const r=f(e);n=y(r).isDirectory()?r:u.dirname(r)}catch{return void 0}for(;;){const r=u.join(n,"package.json");if(N(r)){try{const a=JSON.parse(b(r,"utf8"));const i=I(a.name);if(i){return{packageName:i,packageRoot:n,...typeof a.version==="string"?{version:a.version}:{}}}}catch{return void 0}}const o=u.dirname(n);if(o===n)return void 0;n=o}}function Z(e,n,r,o){let a=e;for(let i=0;i<3;i+=1){const t=q(a,e,n,r,o);if(t)return t;const s=o.dirname(a);if(s===a)break;a=s}return void 0}function q(e,n,r,o,a){try{const i=b(a.join(e,"install.json"),"utf8").replace(/^\uFEFF/u,"");const t=JSON.parse(i);const s=I(t.packageName);const c=t.schemaVersion===1&&t.layoutVersion===void 0;const l=t.schemaVersion===2&&t.layoutVersion===2&&t.releasesDirectory==="releases"&&t.currentFile==="current";if(!c&&!l||t.product!=="alran-code"||t.updateOwner!=="npm-prefix"||t.packageManager!=="npm"||!s||typeof t.registry!=="string"||t.distTag!=="latest"||typeof t.prefix!=="string"||typeof t.npmExecutable!=="string"){return void 0}const d=w(s,t.registry);if(g(t.prefix,o)!==g(e,o)||new URL(t.registry).href!==d.registry||!N(t.npmExecutable)){return void 0}if(c&&g(n,o)!==g(e,o)){return void 0}if(l){const A=a.join(e,"releases");const m=a.relative(A,n);if(!m||m.startsWith("..")||a.isAbsolute(m)||m.includes(a.sep)||!/^[0-9A-Za-z][0-9A-Za-z._-]*$/u.test(m)||!S(n,r,a)){return void 0}}const p=typeof t.nodeExecutable==="string"&&a.isAbsolute(t.nodeExecutable)?ee(t.nodeExecutable):void 0;return{executable:t.npmExecutable,packageName:s,prefix:e,registry:d.registry,...p?{nodeExecutable:p}:{}}}catch{return void 0}}var X=/^(?<prefix>.+)\/Cellar\/(?<formula>node(?:@\d+(?:\.\d+)*)?)\/[^/]+\/bin\/node$/u;var Q=/^(?<prefix>\/(?:opt\/homebrew|usr\/local|home\/linuxbrew\/\.linuxbrew))\/(?:opt\/(?<formula>node(?:@\d+(?:\.\d+)*)?)\/bin\/node|bin\/node)$/u;function ee(e){const n=ne(e);return R(n)??R(e)}function ne(e){const n=X.exec(e);const r=Q.exec(e);const o=n?.groups?.prefix??r?.groups?.prefix;if(!o)return e;const a=n?.groups?.formula??r?.groups?.formula??"node";const i=`${o}/opt/${a}/bin/node`;if(i===e)return e;try{if(f(i)===f(e))return i}catch{}return e}function R(e){try{if(!y(e).isFile())return void 0;L(e,j.X_OK);return e}catch{return void 0}}function S(e,n,r){const o=r.relative(r.resolve(e),r.resolve(n));return o!==""&&!o.startsWith("..")&&!r.isAbsolute(o)}function I(e){return x.find(n=>n===e)}function re(e){const n=e.replaceAll("\\","/");return x.find(r=>n===r||n.endsWith(`/${r}`))}function g(e,n){let r;try{r=f(e)}catch{r=(n==="win32"?u.win32:u.posix).resolve(e)}return n==="win32"?r.toLocaleLowerCase():r}function D(e,n,r=process.env){return new Promise((o,a)=>{let i=false;const t=(0,k.default)(e,[...n],{env:r,shell:false,stdio:["ignore","pipe","pipe"],windowsHide:true});const s=[];const c=[];t.stdout?.on("data",l=>s.push(l));t.stderr?.on("data",l=>c.push(l));t.once("error",l=>{if(i)return;i=true;a(l)});t.once("exit",(l,d)=>{if(i)return;i=true;if(l===0){o(Buffer.concat(s).toString("utf8").trim());return}const p=Buffer.concat([...c,...s]).toString("utf8").trim();a(new Error(`${e} failed (${d?`signal ${d}`:`exit ${String(l)}`})${p?`: ${p}`:""}`))})})}export{E as a,v as b,$ as c,ie as d,O as e,se as f,J as g,w as h,le as i,G as j,ce as k,ue as l,H as m,de as n,pe as o,K as p,ge as q,W as r,I as s};
|
|
2
|
+
import{b as _}from"./chunk-ZQKVUPKA.js";import{a as T}from"./chunk-R44C5DM6.js";import{e as M}from"./chunk-XQK7JM66.js";var k=M(T(),1);import{accessSync as L,constants as j,existsSync as N,readFileSync as b,realpathSync as f,statSync as y}from"node:fs";import u from"node:path";var E="https://registry.npmjs.org/";var B=3e4;var v="alran";var $=["@ottili/alran-code","@ottili/code"];function ie(e){return $.includes(e??"")}var x=[v,...$];var C=v;function O(e){const n=u.join(e,"install.json");try{const r=JSON.parse(b(n,"utf8"));return r.product==="alran-code"&&r.updateOwner==="alran-installer"}catch{return false}}async function se(e){const n=e.platform??process.platform;const r={installRoot:e.installRoot,platform:n,packageRoot:e.packageRoot??Y,npmGlobalPrefix:e.npmGlobalPrefix??(()=>D(n==="win32"?"npm.cmd":"npm",["prefix","--global"])),managedInstall:e.managedInstall??O,prefixInstall:e.prefixInstall??W};if(r.managedInstall(r.installRoot))return"managed-installer";if(r.prefixInstall())return"npm-prefix";const o=r.packageRoot();if(!o)return"unsupported";const a=J(o);if(a)return a;try{return G(o,await r.npmGlobalPrefix(),n)}catch{return"unsupported"}}function J(e){const n=e.replaceAll("\\","/").toLocaleLowerCase();const r=U();if(new RegExp(`\\/pnpm\\/global\\/(?:v11\\/[^/]+|[^/]+)\\/node_modules\\/${r}$`,"u").test(n)){return"pnpm-global"}if(new RegExp(`\\/(?:\\.config\\/yarn|\\.yarn)\\/global\\/node_modules\\/${r}$`,"u").test(n)){return"yarn-global"}if(new RegExp(`\\/\\.bun\\/install\\/global\\/node_modules\\/${r}$`,"u").test(n)){return"bun-global"}if(new RegExp(`\\/(?:lib|npm)\\/node_modules\\/${r}$`,"u").test(n)){return"npm-global"}return void 0}function U(){const e=x.map(n=>n.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&").replaceAll("/","\\/"));return`(?:${e.join("|")})`}function w(e=K()??C,n){if(!x.includes(e)){throw new Error(`Unsupported Alran npm package: ${String(e)}`)}const r=n?new URL(n).href:E;if(r!==E){throw new Error(`Unsupported Alran npm registry: ${r}`)}return{packageName:e,registry:r}}function le(e=V(),n=F()){if(n)return n;if(e==="test")return"test";if(e==="staging")return"preview";return"latest"}function G(e,n,r=process.platform){const o=g(e,r);const a=r==="win32"?u.win32:u.posix;const i=re(e)??v;const t=r==="win32"?[a.join(n,"node_modules",i)]:[a.join(n,"lib","node_modules",i),a.join(n,"node_modules",i)];return t.some(s=>g(s,r)===o)?"npm-global":"unsupported"}function ce(e,n,r=process.platform,o=w(),a){const i=["latest","preview","test"].includes(n)?n:_(n);const t=`${o.packageName}@${i}`;const s=["--registry",o.registry];const c=`--registry ${o.registry}`;const l=["--ignore-scripts=false","--include=optional",`--allow-scripts=${o.packageName},better-sqlite3`];const d=l.join(" ");switch(e){case"npm-prefix":{if(!a)throw new Error("Alran npm prefix ownership metadata is missing.");if(a.packageName!==o.packageName||new URL(a.registry).href!==o.registry){throw new Error("Alran npm prefix ownership does not match the installed package.")}return{executable:a.executable,args:["install","--global","--prefix",a.prefix,t,...l,...s],display:`${a.executable} install --global --prefix ${a.prefix} ${t} ${d} ${c}`}}case"npm-global":return{executable:r==="win32"?"npm.cmd":"npm",args:["install","--global",t,...l,...s],display:`npm install --global ${t} ${d} ${c}`};case"pnpm-global":return{executable:r==="win32"?"pnpm.cmd":"pnpm",args:["add","--global",t,...s],display:`pnpm add --global ${t} ${c}`};case"yarn-global":return{executable:r==="win32"?"yarn.cmd":"yarn",args:["global","add",t,...s],display:`yarn global add ${t} ${c}`};case"bun-global":return{executable:r==="win32"?"bun.exe":"bun",args:["add","--global",t,...s],display:`bun add --global ${t} ${c}`}}}async function ue(e,n={}){const r=n.platform??process.platform;const o=n.distribution??w();const a=n.run??((l,d)=>{const p={executable:l,args:d,display:l};const A=n.runtimeExecutable?H(p,n.runtimeExecutable):p;return D(A.executable,A.args,n.environment)});const i=n.npmExecutable??(r==="win32"?"npm.cmd":"npm");const t=await a(i,["view",`${o.packageName}@${e}`,"version","--json","--registry",o.registry,"--fetch-timeout",String(B)]);let s;try{s=JSON.parse(t)}catch{s=t.trim()}if(Array.isArray(s)){if(s.length!==1){throw new Error("Alran registry returned an invalid latest version.")}s=s[0]}if(typeof s!=="string"){throw new Error("Alran registry returned an invalid latest version.")}const c=_(s);if(e==="latest"&&c.includes("-")){throw new Error("Alran latest must resolve to a stable semantic version.")}return c}function V(){if(false)return void 0;return"prod"}function F(){if(false)return void 0;return"latest"}function H(e,n){const r=f(e.executable);const o=u.dirname(r);const a=[...u.basename(r)==="npm-cli.js"?[r]:[],u.join(o,"node_modules","npm","bin","npm-cli.js"),u.join(o,"..","lib","node_modules","npm","bin","npm-cli.js")];const i=a.find(t=>N(t)&&y(t).isFile())??z(r);if(!i)throw new Error(`Cannot locate npm-cli.js for the owned npm executable: ${e.executable}`);return{...e,executable:n,args:[i,...e.args]}}function z(e){try{const n=y(e);if(!n.isFile()||n.size>64*1024)return void 0;const r=b(e,"utf8").split(/\r?\n/u);if(r[0]!=="#!/bin/sh")return void 0;const o=r.map(l=>l.trim()).filter(l=>/^exec\s/u.test(l));if(o.length===0)return void 0;const a=o.map(l=>/^exec (?:"\$basedir\/node"|node) "\$basedir\/(nodejs\/\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?\/lib\/node_modules\/npm\/bin\/npm-cli\.js)" "\$@"$/u.exec(l)?.[1]);const i=a[0];if(!i||a.some(l=>l!==i))return void 0;const t=u.dirname(e);const s=u.join(t,...i.split("/").slice(0,2));const c=f(u.join(t,i));if(!S(s,c,u)||!y(c).isFile())return void 0;return c}catch{return void 0}}function de(e,n,r=process.platform){const o=r==="win32"?u.win32:u.posix;const a={...e};const i=Object.keys(a).filter(s=>r==="win32"?s.toLowerCase()==="path":s==="PATH").sort();const t=a[i[0]??"PATH"];for(const s of i)delete a[s];a.PATH=[o.dirname(n),t].filter(Boolean).join(o.delimiter);return a}function pe(e,n=process.env,r={}){return new Promise((o,a)=>{let i=false;const t=(0,k.default)(e.executable,[...e.args],{env:n,shell:false,stdio:["ignore","pipe","pipe"],windowsHide:true});const s=[];const c=[];t.stdout?.on("data",l=>{s.push(l);h(r,l)});t.stderr?.on("data",l=>{c.push(l);h(r,l)});t.once("error",l=>{if(i)return;i=true;a(l)});t.once("exit",(l,d)=>{if(i)return;i=true;if(l===0){o();return}const p=Buffer.concat([...c,...s]).toString("utf8").trim();a(new Error(`${e.executable} failed (${d?`signal ${d}`:`exit ${String(l)}`})${p?`: ${p}`:""}`))})})}function h(e,n){try{e.onOutput?.(n.toString("utf8"))}catch{}}function K(e=process.argv[1]){return P(e)?.packageName}function ge(e=process.argv[1]){return P(e)?.version}function W(e=process.argv[1],n=process.platform,r=process.execPath){const o=P(e);if(!o)return void 0;const a=n==="win32"?u.win32:u.posix;let i=o.packageRoot;for(let p=0;p<o.packageName.split("/").length;p+=1){i=a.dirname(i)}if(a.basename(i).toLocaleLowerCase()!=="node_modules")return void 0;const t=a.dirname(i);const s=n!=="win32"&&a.basename(t)==="lib"?a.dirname(t):t;const c=Z(s,o.packageRoot,n,a);if(c){if(c.packageName!==o.packageName)return void 0;return c}if(a.basename(s).toLocaleLowerCase()!==".alran-code")return void 0;const l=a.join(a.dirname(r),n==="win32"?"npm.cmd":"npm");if(!N(l))return void 0;const d=w(o.packageName);return{executable:l,packageName:o.packageName,prefix:s,registry:d.registry}}function Y(e=process.argv[1]){return P(e)?.packageRoot}function P(e){if(!e)return void 0;let n;try{const r=f(e);n=y(r).isDirectory()?r:u.dirname(r)}catch{return void 0}for(;;){const r=u.join(n,"package.json");if(N(r)){try{const a=JSON.parse(b(r,"utf8"));const i=I(a.name);if(i){return{packageName:i,packageRoot:n,...typeof a.version==="string"?{version:a.version}:{}}}}catch{return void 0}}const o=u.dirname(n);if(o===n)return void 0;n=o}}function Z(e,n,r,o){let a=e;for(let i=0;i<3;i+=1){const t=q(a,e,n,r,o);if(t)return t;const s=o.dirname(a);if(s===a)break;a=s}return void 0}function q(e,n,r,o,a){try{const i=b(a.join(e,"install.json"),"utf8").replace(/^\uFEFF/u,"");const t=JSON.parse(i);const s=I(t.packageName);const c=t.schemaVersion===1&&t.layoutVersion===void 0;const l=t.schemaVersion===2&&t.layoutVersion===2&&t.releasesDirectory==="releases"&&t.currentFile==="current";if(!c&&!l||t.product!=="alran-code"||t.updateOwner!=="npm-prefix"||t.packageManager!=="npm"||!s||typeof t.registry!=="string"||t.distTag!=="latest"||typeof t.prefix!=="string"||typeof t.npmExecutable!=="string"){return void 0}const d=w(s,t.registry);if(g(t.prefix,o)!==g(e,o)||new URL(t.registry).href!==d.registry||!N(t.npmExecutable)){return void 0}if(c&&g(n,o)!==g(e,o)){return void 0}if(l){const A=a.join(e,"releases");const m=a.relative(A,n);if(!m||m.startsWith("..")||a.isAbsolute(m)||m.includes(a.sep)||!/^[0-9A-Za-z][0-9A-Za-z._-]*$/u.test(m)||!S(n,r,a)){return void 0}}const p=typeof t.nodeExecutable==="string"&&a.isAbsolute(t.nodeExecutable)?ee(t.nodeExecutable):void 0;return{executable:t.npmExecutable,packageName:s,prefix:e,registry:d.registry,...p?{nodeExecutable:p}:{}}}catch{return void 0}}var X=/^(?<prefix>.+)\/Cellar\/(?<formula>node(?:@\d+(?:\.\d+)*)?)\/[^/]+\/bin\/node$/u;var Q=/^(?<prefix>\/(?:opt\/homebrew|usr\/local|home\/linuxbrew\/\.linuxbrew))\/(?:opt\/(?<formula>node(?:@\d+(?:\.\d+)*)?)\/bin\/node|bin\/node)$/u;function ee(e){const n=ne(e);return R(n)??R(e)}function ne(e){const n=X.exec(e);const r=Q.exec(e);const o=n?.groups?.prefix??r?.groups?.prefix;if(!o)return e;const a=n?.groups?.formula??r?.groups?.formula??"node";const i=`${o}/opt/${a}/bin/node`;if(i===e)return e;try{if(f(i)===f(e))return i}catch{}return e}function R(e){try{if(!y(e).isFile())return void 0;L(e,j.X_OK);return e}catch{return void 0}}function S(e,n,r){const o=r.relative(r.resolve(e),r.resolve(n));return o!==""&&!o.startsWith("..")&&!r.isAbsolute(o)}function I(e){return x.find(n=>n===e)}function re(e){const n=e.replaceAll("\\","/");return x.find(r=>n===r||n.endsWith(`/${r}`))}function g(e,n){let r;try{r=f(e)}catch{r=(n==="win32"?u.win32:u.posix).resolve(e)}return n==="win32"?r.toLocaleLowerCase():r}function D(e,n,r=process.env){return new Promise((o,a)=>{let i=false;const t=(0,k.default)(e,[...n],{env:r,shell:false,stdio:["ignore","pipe","pipe"],windowsHide:true});const s=[];const c=[];t.stdout?.on("data",l=>s.push(l));t.stderr?.on("data",l=>c.push(l));t.once("error",l=>{if(i)return;i=true;a(l)});t.once("exit",(l,d)=>{if(i)return;i=true;if(l===0){o(Buffer.concat(s).toString("utf8").trim());return}const p=Buffer.concat([...c,...s]).toString("utf8").trim();a(new Error(`${e} failed (${d?`signal ${d}`:`exit ${String(l)}`})${p?`: ${p}`:""}`))})})}export{E as a,v as b,$ as c,ie as d,O as e,se as f,J as g,w as h,le as i,G as j,ce as k,ue as l,H as m,de as n,pe as o,K as p,ge as q,W as r,I as s};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { createRequire as __alran_cR } from "module"; import { basename as __alran_basename, dirname as __alran_dirname, join as __alran_join } from "path"; import { fileURLToPath as __alran_fileURLToPath, pathToFileURL as __alran_pathToFileURL } from "url"; const __alran_tuiCurrentModuleDir = __alran_dirname(__alran_fileURLToPath(import.meta.url)); const __alran_tuiPackageRoot = __alran_basename(__alran_tuiCurrentModuleDir) === "chunks" ? __alran_dirname(__alran_tuiCurrentModuleDir) : __alran_tuiCurrentModuleDir; const __alran_tuiPackageEntryUrl = __alran_pathToFileURL(__alran_join(__alran_tuiPackageRoot, "cli.js")).href; const require = __alran_cR(__alran_tuiPackageEntryUrl); const __dirname = __alran_tuiPackageRoot;
|
|
2
|
+
import{a as V}from"./chunk-U3RMPDXU.js";import{a as q}from"./chunk-XLVABFJC.js";import{a as W,b as j,c as U,d as G}from"./chunk-N6W7ZL26.js";import{a as K}from"./chunk-NMKRNU5O.js";import{b as E}from"./chunk-W5ZOLW7T.js";import{a as B}from"./chunk-3AODGLMF.js";import{d as L,e as N,f as z,h as D,i as $,j as H,l as J}from"./chunk-VLXX22YO.js";import{a as I}from"./chunk-7XYOYZX2.js";function Z(e){return e.type==="text"}function ie(e){return e.type==="thinking"}function Y(e){return e.type==="toolCall"}function le(e){return e.type==="image"}var pe=64;function ce(e){const n=new Set;for(const t of e){if(t.role==="assistant"){for(const o of t.content){if(Y(o)&&o.id)n.add(o.id)}}else if(t.role==="toolResult"&&t.toolCallId){n.add(t.toolCallId)}}return n}function X(e,n){let t=e;for(let o=2;n.has(t);o+=1){const a=`_${o}`;t=`${e.slice(0,Math.max(1,pe-a.length))}${a}`}n.add(t);return t}function ee(e){if(e){return e}if(typeof process!=="undefined"&&process.env.PI_CACHE_RETENTION==="long"){return"long"}return"short"}var ue=(e,n,t)=>{const o=new z;(async()=>{const a={role:"assistant",content:[],api:e.api,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()};try{const p=t?.apiKey;if(!p){throw new Error(`No API key for provider: ${e.provider}`)}const f=F(e);const s=ee(t?.cacheRetention);const r=s==="none"?void 0:t?.sessionId;const u=ge(e,n,p,t?.headers,r,f,t?.fetch);let h=fe(e,n,t,f,s);const C=await t?.onPayload?.(h,e);if(C!==void 0){h=C}const R={...t?.signal?{signal:t.signal}:{},...t?.timeoutMs!==void 0?{timeout:t.timeoutMs}:{},maxRetries:t?.maxRetries??0};const{data:T,response:y}=await u.chat.completions.create(h,R).withResponse();await t?.onResponse?.({status:y.status,headers:B(y.headers)},e);o.push({type:"start",partial:a});let x=null;let l=null;let k=false;const v=new Map;const S=new Map;const b=ce(n.messages);const O=a.content;const _=i=>O.indexOf(i);const ne=i=>{const c=_(i);if(c===-1){return}if(i.type==="text"){o.push({type:"text_end",contentIndex:c,content:i.text,partial:a})}else if(i.type==="thinking"){o.push({type:"thinking_end",contentIndex:c,content:i.thinking,partial:a})}else if(i.type==="toolCall"){i.arguments=E(i.partialArgs);delete i.partialArgs;delete i.streamIndex;o.push({type:"toolcall_end",contentIndex:c,toolCall:i,partial:a})}};const oe=()=>{if(!x){x={type:"text",text:""};O.push(x);o.push({type:"text_start",contentIndex:_(x),partial:a})}return x};const se=i=>{if(!l){l={type:"thinking",thinking:"",thinkingSignature:i};O.push(l);o.push({type:"thinking_start",contentIndex:_(l),partial:a})}return l};const ae=i=>{const c=typeof i.index==="number"?i.index:void 0;let m=c!==void 0?v.get(c):void 0;if(!m&&i.id){const M=S.get(i.id);if(M&&(c===void 0||M.streamIndex===void 0||M.streamIndex===c)){m=M}}if(!m){m={type:"toolCall",id:i.id?X(i.id,b):"",name:i.function?.name||"",arguments:{},partialArgs:"",streamIndex:c};if(c!==void 0){v.set(c,m)}if(i.id){S.set(i.id,m)}O.push(m);o.push({type:"toolcall_start",contentIndex:_(m),partial:a})}if(c!==void 0&&m.streamIndex===void 0){m.streamIndex=c;v.set(c,m)}if(i.id){S.set(i.id,m)}return m};const re=$(T,t?.onProviderStreamEvent,e);for await(const i of re){if(!i||typeof i!=="object")continue;a.responseId||=i.id;if(typeof i.model==="string"&&i.model.length>0&&i.model!==e.id){a.responseModel||=i.model}if(i.usage){a.usage=Q(i.usage,e)}const c=Array.isArray(i.choices)?i.choices[0]:void 0;if(!c)continue;if(!i.usage&&c.usage){a.usage=Q(c.usage,e)}if(c.finish_reason){const m=Ae(c.finish_reason);a.stopReason=m.stopReason;if(m.errorMessage){a.errorMessage=m.errorMessage}k=true}if(c.delta){if(c.delta.content!==null&&c.delta.content!==void 0&&c.delta.content.length>0){const g=oe();g.text+=c.delta.content;o.push({type:"text_delta",contentIndex:_(g),delta:c.delta.content,partial:a})}const m=["reasoning_content","reasoning","reasoning_text"];const M=c.delta;let P=null;for(const g of m){const d=M[g];if(typeof d==="string"&&d.length>0){P=g;break}}if(P){const g=M[P];if(typeof g==="string"&&g.length>0){const d=e.provider==="opencode-go"&&P==="reasoning"?"reasoning_content":P;const A=se(d);A.thinking+=g;o.push({type:"thinking_delta",contentIndex:_(A),delta:g,partial:a})}}if(c?.delta?.tool_calls){for(const g of c.delta.tool_calls){const d=ae(g);if(!d.id&&g.id){d.id=X(g.id,b);S.set(g.id,d)}if(!d.name&&g.function?.name){d.name=g.function.name}let A="";if(g.function?.arguments){A=g.function.arguments;d.partialArgs=(d.partialArgs??"")+g.function.arguments;d.arguments=E(d.partialArgs)}o.push({type:"toolcall_delta",contentIndex:_(d),delta:A,partial:a})}}const w=c.delta.reasoning_details;if(w&&Array.isArray(w)){for(const g of w){if(g.type==="reasoning.encrypted"&&g.id&&g.data){const d=a.content.find(A=>A.type==="toolCall"&&A.id===g.id);if(d){d.thoughtSignature=JSON.stringify(g)}}}}}}for(const i of O){ne(i)}if(t?.signal?.aborted){throw new Error("Request was aborted")}if(a.stopReason==="aborted"){throw new Error("Request was aborted")}if(a.stopReason==="error"){throw new Error(a.errorMessage||"Provider returned an error stop reason")}if(!k){throw new Error("Stream ended without finish_reason")}o.push({type:"done",reason:a.stopReason,message:a});o.end()}catch(p){D(t?.onProviderError,p,e);for(const s of a.content){delete s.index;delete s.partialArgs;delete s.streamIndex}a.stopReason=t?.signal?.aborted?"aborted":"error";a.errorMessage=p instanceof Error?p.message:JSON.stringify(p);const f=p?.error?.metadata?.raw;if(f)a.errorMessage+=`
|
|
3
|
+
${f}`;o.push({type:"error",reason:a.stopReason,error:a});o.end()}})();return o};var Ne=(e,n,t)=>{const o=t?.apiKey;if(!o){throw new Error(`No API key for provider: ${e.provider}`)}const a=H(e,t,o);const p=t?.reasoning?N(e,t.reasoning):void 0;const f=p==="off"?void 0:p;const s=t?.toolChoice;return ue(e,n,{...a,reasoningEffort:f,toolChoice:s})};function ge(e,n,t,o,a,p=F(e),f){const s={...e.headers};if(e.provider==="github-copilot"){const u=U(n.messages);const h=G({messages:n.messages,hasImages:u});Object.assign(s,h)}if(a&&p.sendSessionAffinityHeaders){s.session_id=a;s["x-client-request-id"]=a;s["x-session-affinity"]=a}if(o){Object.assign(s,o)}const r=e.provider==="cloudflare-ai-gateway"?{...s,Authorization:s.Authorization??null,"cf-aig-authorization":`Bearer ${t}`}:s;return new q({apiKey:t,baseURL:W(e.provider)?j(e):e.baseUrl,dangerouslyAllowBrowser:true,...f?{fetch:f}:{},defaultHeaders:r})}function fe(e,n,t,o=F(e),a=ee(t?.cacheRetention)){const p=Te(e,n,o);const f=he(o,a);const s={model:e.id,messages:p,stream:true,prompt_cache_key:e.baseUrl.includes("api.openai.com")&&a!=="none"||a==="long"&&o.supportsLongCacheRetention?V(t?.sessionId):void 0,prompt_cache_retention:a==="long"&&o.supportsLongCacheRetention?"24h":void 0};if(o.supportsUsageInStreaming!==false){s.stream_options={include_usage:true}}if(o.supportsStore){s.store=false}if(t?.maxTokens){if(o.maxTokensField==="max_tokens"){s.max_tokens=t.maxTokens}else{s.max_completion_tokens=t.maxTokens}}if(t?.temperature!==void 0){s.temperature=t.temperature}if(n.tools&&n.tools.length>0){s.tools=xe(n.tools,o);if(o.zaiToolStream){s.tool_stream=true}}if(f){me(p,s.tools,f)}if(t?.toolChoice){s.tool_choice=t.toolChoice}if(o.thinkingFormat==="zai"&&e.reasoning){const r=s;r.thinking={type:t?.reasoningEffort?"enabled":"disabled"}}else if(o.thinkingFormat==="qwen"&&e.reasoning){s.enable_thinking=!!t?.reasoningEffort}else if(o.thinkingFormat==="qwen-chat-template"&&e.reasoning){s.chat_template_kwargs={enable_thinking:!!t?.reasoningEffort,preserve_thinking:true}}else if(o.thinkingFormat==="deepseek"&&e.reasoning){s.thinking={type:t?.reasoningEffort?"enabled":"disabled"};if(t?.reasoningEffort&&o.supportsReasoningEffort){s.reasoning_effort=e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort}}else if(o.thinkingFormat==="openrouter"&&e.reasoning){const r=s;if(t?.reasoningEffort){r.reasoning={effort:e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort}}else if(e.thinkingLevelMap?.off!==null){r.reasoning={effort:e.thinkingLevelMap?.off??"none"}}}else if(o.thinkingFormat==="ant-ling"&&e.reasoning&&t?.reasoningEffort){const r=e.thinkingLevelMap?.[t.reasoningEffort];if(typeof r==="string"){s.reasoning={effort:r}}}else if(o.thinkingFormat==="together"&&e.reasoning){const r=s;r.reasoning={enabled:!!t?.reasoningEffort};if(t?.reasoningEffort&&o.supportsReasoningEffort){r.reasoning_effort=e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort}}else if(o.thinkingFormat==="string-thinking"&&e.reasoning){const r=s;if(t?.reasoningEffort){r.thinking=e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort}else if(e.thinkingLevelMap?.off!==null){r.thinking=e.thinkingLevelMap?.off??"none"}}else if(t?.reasoningEffort&&e.reasoning&&o.supportsReasoningEffort){s.reasoning_effort=e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort}else if(!t?.reasoningEffort&&e.reasoning&&o.supportsReasoningEffort){const r=e.thinkingLevelMap?.off;if(typeof r==="string"){s.reasoning_effort=r}}if(e.compat?.openRouterRouting){s.provider=e.compat.openRouterRouting}if(e.baseUrl.includes("ai-gateway.vercel.sh")&&e.compat?.vercelGatewayRouting){const r=e.compat.vercelGatewayRouting;if(r.only||r.order){const u={};if(r.only)u.only=r.only;if(r.order)u.order=r.order;s.providerOptions={gateway:u}}}return s}function he(e,n){if(e.cacheControlFormat!=="anthropic"||n==="none"){return void 0}const t=n==="long"&&e.supportsLongCacheRetention?"1h":void 0;return{type:"ephemeral",...t?{ttl:t}:{}}}function me(e,n,t){de(e,t);ye(n,t);Ce(e,t)}function de(e,n){for(const t of e){if(t.role==="system"||t.role==="developer"){ke(t,n);return}}}function Ce(e,n){for(let t=e.length-1;t>=0;t--){const o=e[t];if(o.role==="user"||o.role==="assistant"){if(Re(o,n)){return}}}}function ye(e,n){if(!e||e.length===0){return}const t=e[e.length-1];t.cache_control=n}function ke(e,n){return te(e,n)}function Re(e,n){if(e.role==="user"||e.role==="assistant"){return te(e,n)}return false}function te(e,n){const t=e.content;if(typeof t==="string"){if(t.length===0){return false}e.content=[{type:"text",text:t,cache_control:n}];return true}if(!Array.isArray(t)){return false}for(let o=t.length-1;o>=0;o--){const a=t[o];if(a?.type==="text"){const p=a;p.cache_control=n;return true}}return false}function Te(e,n,t){const o=[];const a=s=>{if(s.includes("|")){const[r]=s.split("|");return r.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,40)}if(e.provider==="openai")return s.length>40?s.slice(0,40):s;return s};const p=J(n.messages,e,s=>a(s));if(n.systemPrompt){const s=e.reasoning&&t.supportsDeveloperRole;const r=s?"developer":"system";o.push({role:r,content:I(n.systemPrompt)})}let f=null;for(let s=0;s<p.length;s++){const r=p[s];if(t.requiresAssistantAfterToolResult&&f==="toolResult"&&r.role==="user"){o.push({role:"assistant",content:"I have processed the tool results."})}if(r.role==="user"){if(typeof r.content==="string"){o.push({role:"user",content:I(r.content)})}else{const u=r.content.map(h=>{if(h.type==="text"){return{type:"text",text:I(h.text)}}else{return{type:"image_url",image_url:{url:`data:${h.mimeType};base64,${h.data}`}}}});if(u.length===0)continue;o.push({role:"user",content:u})}}else if(r.role==="assistant"){const u={role:"assistant",content:t.requiresAssistantAfterToolResult?"":null};const h=r.content.filter(Z).filter(l=>l.text.trim().length>0).map(l=>({type:"text",text:I(l.text)}));const C=h.map(l=>l.text).join("");const R=r.content.filter(ie).filter(l=>l.thinking.trim().length>0);if(R.length>0){if(t.requiresThinkingAsText){const l=R.map(k=>I(k.thinking)).join("\n\n");u.content=[{type:"text",text:l},...h]}else{if(C.length>0){u.content=C}let l=R[0].thinkingSignature;if(e.provider==="opencode-go"&&l==="reasoning"){l="reasoning_content"}if(l&&l.length>0){u[l]=R.map(k=>k.thinking).join("\n")}}}else if(C.length>0){u.content=C}const T=r.content.filter(Y);if(T.length>0){u.tool_calls=T.map(k=>({id:k.id,type:"function",function:{name:k.name,arguments:JSON.stringify(k.arguments)}}));const l=T.filter(k=>k.thoughtSignature).map(k=>{try{return JSON.parse(k.thoughtSignature)}catch{return null}}).filter(Boolean);if(l.length>0){u.reasoning_details=l}}if(t.requiresReasoningContentOnAssistantMessages&&e.reasoning&&u.reasoning_content===void 0){u.reasoning_content=""}const y=u.content;const x=y!==null&&y!==void 0&&(typeof y==="string"?y.length>0:y.length>0);if(!x&&!u.tool_calls){continue}o.push(u)}else if(r.role==="toolResult"){const u=[];let h=s;for(;h<p.length&&p[h].role==="toolResult";h++){const C=p[h];const R=C.content.filter(Z).map(l=>l.text).join("\n");const T=C.content.some(l=>l.type==="image");const y=R.length>0;const x={role:"tool",content:I(y?R:"(see attached image)"),tool_call_id:C.toolCallId};if(t.requiresToolResultName&&C.toolName){x.name=C.toolName}o.push(x);if(T&&e.input.includes("image")){for(const l of C.content){if(le(l)){u.push({type:"image_url",image_url:{url:`data:${l.mimeType};base64,${l.data}`}})}}}}s=h-1;if(u.length>0){if(t.requiresAssistantAfterToolResult){o.push({role:"assistant",content:"I have processed the tool results."})}o.push({role:"user",content:[{type:"text",text:"Attached image(s) from tool result:"},...u]});f="user"}else{f="toolResult"}continue}f=r.role}return o}function xe(e,n){return e.map(t=>({type:"function",function:{name:t.name,description:t.description,parameters:K(t.parameters),...n.supportsStrictMode!==false&&{strict:false}}}))}function Q(e,n){const t=e.prompt_tokens||0;const o=e.prompt_tokens_details?.cached_tokens??e.prompt_cache_hit_tokens??0;const a=e.prompt_tokens_details?.cache_write_tokens||0;const p=Math.max(0,t-o-a);const f=e.completion_tokens||0;const s={input:p,output:f,cacheRead:o,cacheWrite:a,totalTokens:p+f+o+a,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};L(n,s);return s}function Ae(e){if(e===null)return{stopReason:"stop"};switch(e){case"stop":case"end":return{stopReason:"stop"};case"length":return{stopReason:"length"};case"function_call":case"tool_calls":return{stopReason:"toolUse"};case"content_filter":return{stopReason:"error",errorMessage:"Provider finish_reason: content_filter"};case"network_error":return{stopReason:"error",errorMessage:"Provider finish_reason: network_error"};default:return{stopReason:"error",errorMessage:`Provider finish_reason: ${e}`}}}function _e(e){const n=e.provider;const t=e.baseUrl;const o=n==="zai"||n==="zai-coding-cn"||t.includes("api.z.ai")||t.includes("open.bigmodel.cn");const a=n==="together"||t.includes("api.together.ai")||t.includes("api.together.xyz");const p=n==="moonshotai"||n==="moonshotai-cn"||t.includes("api.moonshot.");const f=/^https?:\/\/api\.kimi\.(?:com|ai)(?::\d+)?(?:\/|$)/i.test(t);const s=/^https?:\/\/(?:dashscope(?:-intl|-us)?|(?:coding(?:-intl)?|cn-hongkong)\.dashscope)\.aliyuncs\.com(?::\d+)?(?:\/|$)/i.test(t)||/^https?:\/\/[a-z0-9-]+\.(?:cn-beijing|cn-hongkong|ap-southeast-1|ap-northeast-1|eu-central-1|us-east-1)\.maas\.aliyuncs\.com(?::\d+)?(?:\/|$)/i.test(t);const r=/^https?:\/\/api\.siliconflow\.(?:cn|com)(?::\d+)?(?:\/|$)/i.test(t);const u=/^https?:\/\/api\.mistral\.ai(?::\d+)?(?:\/|$)/i.test(t);const h=n==="openrouter"||t.includes("openrouter.ai");const C=n==="cloudflare-workers-ai"||t.includes("api.cloudflare.com");const R=n==="cloudflare-ai-gateway"||t.includes("gateway.ai.cloudflare.com");const T=n==="nvidia"||t.includes("integrate.api.nvidia.com");const y=n==="ant-ling"||t.includes("api.ant-ling.com");const x=T||n==="cerebras"||t.includes("cerebras.ai")||n==="xai"||t.includes("api.x.ai")||a||t.includes("chutes.ai")||t.includes("deepseek.com")||o||p||n==="opencode"||t.includes("opencode.ai")||C||R||y;const l=t.includes("chutes.ai")||p||R||a||T||y;const k=n==="xai"||t.includes("api.x.ai");const v=n==="deepseek"||t.includes("deepseek.com");const S=h&&(e.id.startsWith("anthropic/")||e.id.startsWith("openai/"));const b=n==="openrouter"&&e.id.startsWith("anthropic/")?"anthropic":void 0;return{supportsStore:!x,supportsDeveloperRole:!f&&!s&&!r&&!u&&(S||!x&&!h),supportsReasoningEffort:!k&&!o&&!p&&!a&&!R&&!T&&!y,supportsUsageInStreaming:true,maxTokensField:l?"max_tokens":"max_completion_tokens",requiresToolResultName:false,requiresAssistantAfterToolResult:false,requiresThinkingAsText:false,requiresReasoningContentOnAssistantMessages:v,thinkingFormat:v?"deepseek":o?"zai":a?"together":y?"ant-ling":h?"openrouter":"openai",openRouterRouting:{},vercelGatewayRouting:{},zaiToolStream:false,supportsStrictMode:!p&&!a&&!R&&!T,cacheControlFormat:b,sendSessionAffinityHeaders:false,supportsLongCacheRetention:!(a||C||R||T||y)}}function F(e){const n=_e(e);if(!e.compat)return n;return{supportsStore:e.compat.supportsStore??n.supportsStore,supportsDeveloperRole:e.compat.supportsDeveloperRole??n.supportsDeveloperRole,supportsReasoningEffort:e.compat.supportsReasoningEffort??n.supportsReasoningEffort,supportsUsageInStreaming:e.compat.supportsUsageInStreaming??n.supportsUsageInStreaming,maxTokensField:e.compat.maxTokensField??n.maxTokensField,requiresToolResultName:e.compat.requiresToolResultName??n.requiresToolResultName,requiresAssistantAfterToolResult:e.compat.requiresAssistantAfterToolResult??n.requiresAssistantAfterToolResult,requiresThinkingAsText:e.compat.requiresThinkingAsText??n.requiresThinkingAsText,requiresReasoningContentOnAssistantMessages:e.compat.requiresReasoningContentOnAssistantMessages??n.requiresReasoningContentOnAssistantMessages,thinkingFormat:e.compat.thinkingFormat??n.thinkingFormat,openRouterRouting:e.compat.openRouterRouting??{},vercelGatewayRouting:e.compat.vercelGatewayRouting??n.vercelGatewayRouting,zaiToolStream:e.compat.zaiToolStream??n.zaiToolStream,supportsStrictMode:e.compat.supportsStrictMode??n.supportsStrictMode,cacheControlFormat:e.compat.cacheControlFormat??n.cacheControlFormat,sendSessionAffinityHeaders:e.compat.sendSessionAffinityHeaders??n.sendSessionAffinityHeaders,supportsLongCacheRetention:e.compat.supportsLongCacheRetention??n.supportsLongCacheRetention}}export{ue as a,Ne as b,Te as c};
|