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
package/chunks/chunk-YLQXZBEL.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
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 n(e){return{schemaVersion:1,type:"exec.result",sessionId:e.sessionId,turnId:e.turnId,status:e.status==="awaiting-user-continuation"?"blocked":e.status,answer:e.answer??null,...e.model?{model:{...e.model}}:{},...e.error?{error:{...e.error}}:{},durationMs:e.durationMs}}function o(e){if(!e||typeof e!=="object"||Array.isArray(e))return false;const t=e;const r=t.model===void 0||typeof t.model==="object"&&t.model!==null&&typeof t.model.providerId==="string"&&typeof t.model.modelId==="string"&&(t.model.variant===void 0||typeof t.model.variant==="string");return t.schemaVersion===1&&t.type==="exec.result"&&typeof t.sessionId==="string"&&typeof t.turnId==="string"&&typeof t.durationMs==="number"&&r&&(t.status==="succeeded"||t.status==="failed"||t.status==="blocked"||t.status==="timeout"||t.status==="cancelled"||t.status==="limit_exceeded")}function a(e){return e.coordinator.execute(e.request,t=>{if(e.isActive())e.onSessionEvent(t)},e.onRunAccepted,e.onResult?t=>e.onResult?.(n(t)):void 0)}var u={help:{name:"help",description:"Show available commands"},new:{name:"new",description:"Start a fresh session in the current workspace"},model:{name:"model",description:"Choose a model"},status:{name:"status",description:"Show account and model status"},doctor:{name:"doctor",description:"Check the local config file"},context:{name:"context",description:"Show the Runtime-owned context snapshot"},skills:{name:"skills",description:"List built-in and user Skills"},mcp:{name:"mcp",description:"Inspect MCP capabilities and project configuration"},usage:{name:"usage",description:"Show session usage"},compact:{name:"compact",description:"Shorten the active conversation"},export:{name:"export",description:"Export the current Session as Markdown"}};export{u as a,o as b,a as c};
|
package/chunks/chunk-Z6BHCXKT.js
DELETED
|
@@ -1,25 +0,0 @@
|
|
|
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 N}from"./chunk-4PDIO3M6.js";import{Ab as L,Fa as C,Vb as M,b as _,eb as S,kb as O,ob as x,pb as R,qb as g,rb as T,tb as b,ub as k,xb as D,zb as E}from"./chunk-FXOH6TEQ.js";import{randomUUID as z}from"node:crypto";var l=Object.freeze({ok:0,error:1,authRequired:2,rateLimited:3,unreachable:4,credits:5});var d=class extends Error{constructor(t,o,a){super(t);this.exitCode=o;this.code=a;this.name="AlranAccountError"}exitCode;code};function V(){return{dataDir:N(),platformEnv:O(),environment:process.env,fetchImpl:fetch,out:e=>process.stdout.write(e),err:e=>process.stderr.write(e),now:()=>new Date,login:async({openBrowser:e,apiKey:n,device:t})=>{const{runTuiLogin:o}=await import("./auth-command-V3RVPLZO.js");return o({openBrowser:e,provider:n?"api-key":"platform",...t===void 0?{}:{device:t}})},clearLocalCredentials:async()=>{const{runTuiLogout:e}=await import("./auth-command-V3RVPLZO.js");await e({})},setDefaultModel:async e=>{await M({modelKey:e})},readDefaultModel:()=>{try{return C().defaultModel}catch{return void 0}}}}function v(e){const n=g(e.dataDir,e.platformEnv);if(!n){throw new d("Not signed in. Run `alran auth login` first.",l.authRequired,"not_signed_in")}return n}function U(e,n){const t=n.environment.OTTILI_PLATFORM_URL?.trim();return(e.baseUrl||t||"https://platform.ottili.one").replace(/\/+$/u,"")}function A(e,n){return S(n.platformEnv,e.environment).replace(/\/+$/u,"")}async function B(e){try{const n=await e.json();return n&&typeof n==="object"?n:{}}catch{return{}}}function J(e,n,t,o){const a=n.error&&typeof n.error==="object"?n.error:n;const i=String(a.code??a.detail??"");const r=typeof a.message==="string"?a.message:typeof a.title==="string"?a.title:"";if(e===401){return new d("Your session has ended. Run `alran auth login` to sign in again.",l.authRequired,i||"unauthenticated")}if(e===429){const c=o?` Try again in ${o} s.`:"";return new d(`${t} is rate limiting this account.${c}`,l.rateLimited,i||"rate_limited")}if(e===402||i==="free_credit_model_restricted"||i==="insufficient_quota"){return new d(r||"Your credit does not cover this request. Add credits in the Ottili AI Platform.",l.credits,i)}if(e>=500){return new d(`${t} is not reachable right now (HTTP ${e}). Try again in a moment.`,l.unreachable,i||"unavailable")}return new d(`${t} refused the request (HTTP ${e}${i?`, ${i}`:""})${r?`: ${r}`:"."}`,l.error,i)}async function W(e,n,t,o){try{return await e.fetchImpl(n,{...t,signal:AbortSignal.timeout(15e3)})}catch{throw new d(`${o} is not reachable (${n.host}). Check your network connection and try again.`,l.unreachable,"network_error")}}async function f(e,n,t,o={}){const a=new URL(t,`${U(n,e)}/`);for(const[s,u]of Object.entries(o.query??{}))a.searchParams.set(s,u);const i={accept:"application/json","x-ottili-session":n.sessionId,...n.companyId?{"x-ottili-company":n.companyId}:{},...o.body!==void 0?{"content-type":"application/json"}:{},...o.idempotent?{"idempotency-key":`alran-cli-${z()}`}:{}};const r=await W(e,a,{method:o.method??"GET",headers:i,...o.body!==void 0?{body:JSON.stringify(o.body)}:{}},"The Ottili Platform");const c=await B(r);if(!r.ok)throw J(r.status,c,"The Ottili Platform",r.headers.get("retry-after"));return c.data??c}async function G(e,n,t){const o=new URL(`${A(e,n)}${t}`);const a=n.companyId?b(e.dataDir).projects[n.companyId]:void 0;const i=await W(e,o,{method:"GET",headers:{accept:"application/json",authorization:`Bearer ${n.sessionId}`,...n.companyId?{"x-ottili-company":n.companyId}:{},...a?{"x-ottili-project":a}:{}}},"The Ottili AI Gateway");const r=await B(i);if(!i.ok)throw J(i.status,r,"The Ottili AI Gateway",i.headers.get("retry-after"));return r}function m(e){const n=Number(e)/1e6;if(!Number.isFinite(n))return"\u2014";const t=Math.abs(n);const o=t>0&&t<.01?4:2;return`${n<0?"-":""}$${t.toFixed(o)}`}function X(e){const n=e&&typeof e==="object"?e:{};const t=Number(n.amount_minor);if(!Number.isFinite(t))return"\u2014";return`${(t/100).toFixed(2)} ${String(n.currency??"USD").toUpperCase()}`}function j(e,n){const t=e.map((a,i)=>Math.max(a.length,...n.map(r=>(r[i]??"").length)));const o=a=>a.map((i,r)=>(i??"").padEnd(t[r])).join(" ").trimEnd();return[o(e),o(t.map(a=>"\u2500".repeat(a))),...n.map(o)].join("\n")}var y=e=>`${JSON.stringify(e,null,2)}
|
|
3
|
-
`;async function Y(e,n){const[t,o]=await Promise.all([f(e,n,"/v2/profile"),f(e,n,`/v2/auth/sessions/${encodeURIComponent(n.sessionId)}`).catch(a=>{if(a instanceof d&&a.exitCode===l.authRequired)throw a;return{}})]);return{name:t.profile?.display_name||t.profile?.subject_id||n.subjectId||"unknown",subjectId:t.profile?.subject_id||n.subjectId,expiresAt:typeof o.expires_at==="string"?o.expires_at:null}}async function Q(e,n={}){const t=g(e.dataDir,e.platformEnv);if(!t){if(n.json)e.out(y({signed_in:false}));else e.out("Not signed in. Run `alran auth login` to connect Alran Code to your Ottili account.\n");throw new d("",l.authRequired,"not_signed_in")}const o=await Y(e,t);const a=b(e.dataDir).projects[t.companyId]??null;const i={signed_in:true,name:o.name,subject_id:o.subjectId,company_id:t.companyId,project_id:a,environment:t.platformEnv==="prod"?"production":"development",platform:U(t,e),gateway:A(e,t),session_expires_at:o.expiresAt,default_model:e.readDefaultModel()??"alran/Alran-Werk"};if(n.json){e.out(y(i));return}e.out([`Signed in as ${i.name}`,` Company ${i.company_id}`,` Project ${i.project_id??"default project of the company"}`,` Model ${i.default_model}`,` Platform ${i.platform} (${i.environment})`,` Gateway ${i.gateway}`,...i.session_expires_at?[` Session valid until ${i.session_expires_at}`]:[],""].join("\n"))}async function Z(e,n={}){const t=g(e.dataDir,e.platformEnv);if(t&&!n.force&&!n.apiKey){try{const o=await Y(e,t);e.out(`Already logged in as ${o.name} (company ${t.companyId}). Use \`alran auth login --force\` to sign in again.
|
|
4
|
-
`);return}catch(o){if(!(o instanceof d)||o.exitCode!==l.authRequired)throw o}}e.out(`${await e.login({openBrowser:n.browser!==false,apiKey:n.apiKey===true,...n.device===void 0?{}:{device:n.device}})}
|
|
5
|
-
`)}async function ee(e){const n=[];for(const t of R(e.platformEnv)){const o=g(e.dataDir,t);if(!o||o.platformEnv!==t)continue;try{await f(e,o,`/v2/auth/sessions/${encodeURIComponent(o.sessionId)}`,{method:"DELETE",idempotent:true})}catch(a){if(!(a instanceof d)||a.exitCode!==l.authRequired){n.push(`Could not revoke the ${t} session at the Platform (${a instanceof Error?a.message:String(a)}); it was removed from this machine and expires on its own.`)}}x(e.dataDir,t)}await e.clearLocalCredentials();for(const t of n)e.err(`${t}
|
|
6
|
-
`);e.out("Logged out.\n")}async function q(e,n,t={}){const o=v(e);const a=await f(e,o,"/v2/companies");const i=a.companies??[];if(!n){if(t.json){e.out(y({current:o.companyId,companies:i}));return}if(i.length===0){e.out("Your account is not a member of a company yet. Create or join one in the Ottili Console.\n");return}e.out(`${j(["","Company","Slug","Roles"],i.map(s=>[s.company_id===o.companyId?"*":"",s.company_id,s.slug??"",(s.roles??[]).join(", ")]))}
|
|
7
|
-
|
|
8
|
-
Switch with \`alran auth switch-company <company id or slug>\`.
|
|
9
|
-
`);return}const r=i.find(s=>s.company_id===n||s.slug===n);if(!r){throw new d(`You are not a member of a company "${n}". Run \`alran auth switch-company\` to list yours.`,l.error,"company_not_found")}if(r.company_id===o.companyId){e.out(`Already working in ${r.slug??r.company_id}.
|
|
10
|
-
`);return}const c=await f(e,o,"/v2/auth/company",{method:"POST",body:{company_id:r.company_id},idempotent:true});T(e.dataDir,o.platformEnv,{sessionId:c.session?.session_id||o.sessionId,companyId:c.session?.company_id||r.company_id,subjectId:o.subjectId,baseUrl:o.baseUrl},{via:"oidc"});e.out(`Switched to ${r.slug??r.company_id}. Model calls, usage and billing now use this company.
|
|
11
|
-
`)}async function ne(e,n,t={}){const o=v(e);const a=b(e.dataDir).projects[o.companyId]??null;if(t.clear){k(e.dataDir,o.companyId,null);e.out("Project cleared: requests use the default project of the company.\n");return}let i;try{i=await f(e,o,"/v2/projects",{query:{status:"active",member:"me",limit:"200"}})}catch(s){if(s instanceof d&&/HTTP 404/u.test(s.message)){throw new d("This Ottili Platform does not offer projects yet; requests use the default project of the company.",l.error,"projects_unavailable")}throw s}const r=i.items??[];if(!n){if(t.json){e.out(y({current:a,projects:r}));return}if(r.length===0){e.out("No projects you can use in this company. Requests use the default project.\n");return}e.out(`${j(["","Project","Name","Your role"],r.map(s=>[s.project_id===a?"*":"",s.project_id,s.name??"",s.access?.role??""]))}
|
|
12
|
-
|
|
13
|
-
${a?"":"No project chosen: requests use the default project.\n"}Choose one with \`alran config project <project id or name>\`.
|
|
14
|
-
`);return}const c=r.find(s=>s.project_id===n||s.name===n);if(!c){throw new d(`No active project "${n}" that you are a member of. Run \`alran config project\` to list them.`,l.error,"project_not_found")}k(e.dataDir,o.companyId,c.project_id);e.out(`Project set to ${c.name??c.project_id}. Model calls are attributed to it from now on.
|
|
15
|
-
`)}function K(e){const n=E(e.replace(/^(alran|external)\//u,""));if(!Object.hasOwn(_,n))return void 0;return`alran/${n}`}async function F(e,n){if(!n)return null;try{return await G(e,n,"/credits")}catch{return null}}async function H(e,n){if(!n){e.out(`${e.readDefaultModel()??"alran/Alran-Werk"}
|
|
16
|
-
`);return}const t=K(n);if(!t){throw new d(`Unknown model "${n}". Run \`alran models\` to list the models.`,l.error,"model_not_found")}await e.setDefaultModel(t);e.out(`Default model set to ${_[t.slice(t.indexOf("/")+1)]?.name??t} (${t}).
|
|
17
|
-
`);if(L(t.slice(t.indexOf("/")+1))){const o=await F(e,g(e.dataDir,e.platformEnv));const a=o?.models?.find(i=>i.id===D[t.slice(t.indexOf("/")+1)]);if(a&&a.usable===false){e.err("Note: this model uses purchased credits only. Your current credit is welcome credit, which covers Werk. Add credits in the Ottili AI Platform to use it.\n")}}}var $=Object.freeze([{key:"alran/Alran-Werk",id:"ottili/werk-1.1",short:"werk",name:"Ottili Werk 1.1",input:5e5,output:15e5,feeBps:0,credit:"welcome or purchased credit",description:"Ottili\u2019s own model for coding and agentic work. Default."},{key:"alran/anthropic/claude-sonnet-5.5",id:"anthropic/claude-sonnet-5.5",short:"sonnet",name:"Claude Sonnet 5.5",input:2e6,output:1e7,feeBps:450,credit:"purchased credit",description:"Anthropic\u2019s everyday model for coding and agents."},{key:"alran/anthropic/claude-opus-5.5",id:"anthropic/claude-opus-5.5",short:"opus",name:"Claude Opus 5.5",input:4e6,output:2e7,feeBps:450,credit:"purchased credit",description:"Anthropic\u2019s most capable Opus model for hard, long tasks."}]);function I(e,n){if(!n)return"sign in to check";const t=n.models?.find(o=>o.id===e.id);if(!t)return"not offered right now";if(t.usable)return"available";return t.reason==="requires_paid_credit"?"requires purchased credit":"no credit left"}function te(e,n,t=Boolean(process.stdout.isTTY)){const o=e.environment.FORCE_COLOR!==void 0&&e.environment.FORCE_COLOR!=="0";if(e.environment.NO_COLOR!==void 0||!t&&!o)return n;const a=n==="available"?32:n==="requires purchased credit"?33:n==="no credit left"?31:null;return a===null?n:`\x1B[${a}m${n}\x1B[39m`}async function oe(e,n={}){if(n.setDefault){await H(e,n.setDefault);return}if(n.thirdParty){e.out(["Third-party providers (bring your own key)","","Alran Code can call another provider directly with your own API key. Ottili does not see,","meter or bill those requests; the provider bills you. Configure one with:",""," alran provider add --name <name> --base-url <url> --api-format openai-completions \\"," --model <model id> --api-key-env <ENV_VAR_WITH_YOUR_KEY> --use","","Supported formats: openai-completions, openai-responses, anthropic-messages. `alran provider`","opens the provider picker with the bundled catalog of known providers; `alran provider list`","shows what you configured. See docs/MODELS.md.",""].join("\n"));return}const t=g(e.dataDir,e.platformEnv);const o=await F(e,t);const a=e.readDefaultModel()??"alran/Alran-Werk";if(n.info){const i=K(n.info);const r=$.find(u=>u.key===i);if(!r)throw new d(`Unknown model "${n.info}". Run \`alran models\` to list the models.`,l.error,"model_not_found");const c=_[r.key.slice(r.key.indexOf("/")+1)];const s={id:r.id,name:r.name,short_name:r.short,description:r.description,context_tokens:c?.limit?.context??null,max_output_tokens:c?.limit?.output??null,price_per_million_tokens:{input:m(r.input),output:m(r.output)},service_fee:r.feeBps?`${r.feeBps/100} % of the token cost, shown as its own line`:null,paid_with:r.credit,status:I(r,o)};if(n.json)e.out(y(s));else e.out(`${Object.entries(s).filter(([,u])=>u!==null).map(([u,p])=>`${u.padEnd(18)} ${typeof p==="object"?JSON.stringify(p):String(p)}`).join("\n")}
|
|
18
|
-
`);return}if(n.json){e.out(y($.map(i=>({...i,status:I(i,o),default:i.key===a}))));return}e.out(`${j(["","Model","Name","Input / output per 1M tokens","Paid with","Status"],$.map(i=>[i.key===a?"*":"",i.short,i.name,`${m(i.input)} / ${m(i.output)}`,i.credit,te(e,I(i,o))]))}
|
|
19
|
-
|
|
20
|
-
Claude models are billed at Anthropic's token prices plus a 4.5 % service fee, listed as its own line
|
|
21
|
-
per request. Change the default with \`alran models --set-default <model>\`; details with
|
|
22
|
-
\`alran models --info <model>\`; your own providers with \`alran models --third-party\`.
|
|
23
|
-
`)}async function re(e,n={}){const t=v(e);const o=await G(e,t,"/credits");if(n.json){e.out(y(o));return}const a=o.current_month;const i=(a?.by_model??[]).map(r=>[r.model,String(r.requests),String((r.input_tokens??0)+(r.output_tokens??0)),m(r.cost_microcents-(r.service_fee_microcents??0)),r.service_fee_microcents?m(r.service_fee_microcents):"\u2014",m(r.cost_microcents)]);e.out([`Credits (${String(o.currency??"USD").toUpperCase()})`,` Available ${m(o.available_microcents??0)}`,` Reserved ${m(o.reserved_microcents??0)}`,` Welcome credit ${m(o.free_credit?.remaining_microcents??0)} left of ${m(o.free_credit?.granted_microcents??0)} (Werk only)`,` Purchased credit ${m(o.paid_credit?.available_microcents??0)} (all models)`,"",`This month (since ${a?.from?.slice(0,10)??"\u2014"})`,i.length>0?j(["Model","Requests","Tokens","Token cost","Service fee","Total"],i):" No requests yet.","",`Total this month: ${m(a?.total_cost_microcents??0)}`,""].join("\n"))}async function ie(e,n={}){const t=v(e);const o=async h=>{try{return await h}catch(P){if(P instanceof d&&P.exitCode===l.authRequired)throw P;return null}};const[a,i,r,c]=await Promise.all([o(f(e,t,"/v2/billing/subscription")),o(f(e,t,"/v2/billing/payment-methods")),o(f(e,t,"/v2/billing/invoices",{query:{limit:"1"}})),o(f(e,t,"/v2/billing/welcome-credit"))]);const s={subscription:a?.subscription??null,paymentMethods:i?.payment_methods??[],invoices:r?.invoices??[],welcome:c?.welcome_credit??null};const u=`${A(e,t).replace(/\/v1$/u,"")}/billing`;if(n.json){e.out(y({plan:s.subscription?String(s.subscription.plan_id??"pay-per-use"):"pay-per-use",payment_methods:s.paymentMethods.map(h=>({label:h.display_label??null,default:h.is_default===true,state:h.state??null})),last_invoice:s.invoices[0]??null,welcome_credit:s.welcome?{state:s.welcome.state??null}:null,manage_at:u}));return}const p=s.paymentMethods.find(h=>h.is_default===true)??s.paymentMethods[0];const w=s.invoices[0];e.out([`Plan ${s.subscription?String(s.subscription.plan_id??"Pay-per-use"):"Pay-per-use (prepaid credits)"}`,`Payment method ${p?String(p.display_label??"on file"):"none on file"}`,`Last invoice ${w?`${X(w.amount)} \xB7 ${String(w.state??"")} \xB7 ${String(w.issued_at??"").slice(0,10)}`:"none yet"}`,`Next billing ${s.subscription&&s.subscription.state==="active"?"with your subscription period":"none: credits are prepaid, nothing is billed automatically"}`,`Welcome credit ${s.welcome?String(s.welcome.state??"unknown").replaceAll("_"," "):"not available"}`,"",`Add credits, change the payment method or download invoices: ${u}`,""].join("\n"))}async function ae(e,n){try{await n()}catch(t){if(t instanceof d){if(t.message)e.err(`${t.message}
|
|
24
|
-
`);process.exitCode=t.exitCode;return}throw t}}function le(e,n=V,t){const o=r=>async()=>{const c=n();const s=t?import("./update-hint-ED7O67WU.js").then(({resolveUpdateHint:p})=>p({currentVersion:t,dataDir:c.dataDir,environment:c.environment,fetchImpl:c.fetchImpl})).catch(()=>null):Promise.resolve(null);await ae(c,()=>r(c));const u=await Promise.race([s,new Promise(p=>setTimeout(()=>p(null),1500).unref())]);if(u)c.err(`${u}
|
|
25
|
-
`)};const a=e.command("auth").description("Sign in to your Ottili account, check it, switch company, sign out");a.command("login").description("Sign in with your Ottili account (in the browser, or with a code confirmed on any device)").option("--force","sign in again even when a session exists").option("--device","sign in with a code you confirm in a browser anywhere (the default over SSH or without a display)").option("--no-device","sign in through a browser on this machine even when none seems to be there").option("--no-browser","print the sign-in page URL without opening a browser").option("--api-key","paste an Ottili API key instead (for machines without a browser)").action(r=>o(c=>Z(c,r))());a.command("logout").description("Revoke the session at the Ottili Platform and remove local credentials").action(()=>o(ee)());a.command("status").description("Who you are signed in as, and which company, project and model you use").option("--json","print a JSON document").action(r=>o(c=>Q(c,r))());a.command("switch-company").description("List your companies, or switch to one").argument("[company]","company id or slug").option("--json","print a JSON document").action((r,c)=>o(s=>q(s,r,c))());const i=e.command("config").description("Show or set the company, project and model Alran Code works with");i.command("company").description("Show your companies, or switch to one").argument("[company]","company id or slug").option("--json","print a JSON document").action((r,c)=>o(s=>q(s,r,c))());i.command("project").description("Show your projects, or choose the one model calls are attributed to").argument("[project]","project id or name").option("--clear","go back to the default project of the company").option("--json","print a JSON document").action((r,c)=>o(s=>ne(s,r,c))());i.command("model").description("Show or set the default model (werk, sonnet, opus or a full id)").argument("[model]","model").action(r=>o(c=>H(c,r))());e.command("models").description("List the Ottili models, their prices and whether your credit covers them").option("--third-party","how to use another provider with your own API key").option("--info <model>","details of one model").option("--set-default <model>","make a model the default").option("--list","list the models (the default)").option("--json","print a JSON document").action(r=>o(c=>oe(c,r))());e.command("usage").description("Credits left and this month's spend per model").option("--json","print a JSON document").action(r=>o(c=>re(c,r))());e.command("billing").description("Plan, payment method, last invoice, and where to manage billing").option("--json","print a JSON document").action(r=>o(c=>ie(c,r))())}export{l as a,d as b,V as c,f as d,G as e,m as f,j as g,Q as h,Z as i,ee as j,q as k,ne as l,K as m,H as n,$ as o,te as p,oe as q,re as r,ie as s,ae as t,le as u};
|
package/chunks/chunk-Z6HBNJCA.js
DELETED
|
@@ -1,8 +0,0 @@
|
|
|
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 m}from"./chunk-4PDIO3M6.js";import{b as v,c as R,d as A,e as E,f as _,g as U,h as D,i as N,j as $,m as B,n as S,o as I,r as j,v as M}from"./chunk-IWK7PZP7.js";import{c as J}from"./chunk-EYK25HWR.js";import{Ub as K,Ya as P,eb as z,gb as x,hb as F,ib as W,kb as O,ob as H,pb as Y}from"./chunk-FXOH6TEQ.js";import{randomBytes as ee}from"node:crypto";import{createInterface as ce}from"node:readline/promises";import{cwd as de,stderr as ue,stdin as C,stdout as V}from"node:process";import{isAbsolute as ne,resolve as oe}from"node:path";import{spawn as ie}from"node:child_process";import{fileURLToPath as ae}from"node:url";function y(e){return t=>se(t,e)}function se(e,t){const n=le(e,t);const[r,o]=process.platform==="darwin"?["open",[n]]:process.platform==="win32"?["rundll32",["url.dll,FileProtocolHandler",n]]:["xdg-open",[n]];return new Promise((i,u)=>{const s=ie(r,o,{detached:true,stdio:"ignore",windowsHide:true});s.once("error",u);s.once("spawn",()=>{s.unref();i()})})}function le(e,t){if(/^https?:\/\//iu.test(e))return e;if(/^file:\/\//iu.test(e))return ae(e);return ne(e)?e:oe(t,e)}async function pe(e){const t=e.trim();if(!x(t)){throw new Error(`Invalid Ottili API key: expected a key starting with "${P}".`)}await K(n=>{n.alran_api={...n.alran_api??{},apiKey:t};n.alranModelSource="alran_api_key"})}async function fe(){await K(e=>{if(!e.alran_api){e.alranModelSource=void 0;return}const t={...e.alran_api};delete t.apiKey;e.alran_api=Object.keys(t).length>0?t:void 0;e.alranModelSource=void 0})}async function me(e,t){if(!C.isTTY){t("Reading the Ottili API key from stdin\u2026\n");const r=[];for await(const o of C)r.push(Buffer.from(o));return Buffer.concat(r).toString("utf8").trim()}const n=ce({input:C,output:V,terminal:true});try{e("Paste your Ottili API key: ");const r=await n.question("");e("\n");return r.trim()}finally{n.close()}}async function G(e={}){const t=e.write??(i=>V.write(i));const n=e.writeError??(i=>ue.write(i));const r=e.consoleUrl??W();n(`Open this page to create an Ottili API key:
|
|
3
|
-
${r}
|
|
4
|
-
`);if(e.openBrowser!==false){const i=e.openExternalTarget??y(de());try{await i(r)}catch{n("Couldn't open the default browser. Open the URL above manually.\n")}}const o=await(e.readApiKey??(()=>me(t,n)))();if(!x(o)){throw new Error(`Invalid Ottili API key: expected a key starting with "${P}".`)}await(e.storeKey??pe)(o);return{apiKey:o,consoleUrl:r,message:"Signed in to the Ottili AI Platform with your Ottili API key."}}async function q(e={}){await(e.clearKey??fe)();return"Signed out of the Ottili AI Platform. The stored API key was removed."}import{hostname as ge}from"node:os";var ye="urn:ietf:params:oauth:grant-type:device_code";var l=class extends Error{constructor(n,r){super(n);this.code=r;this.name="DeviceLoginError"}code};var we=15e3;var he=4;var ve=1;var Ae=(e,t)=>new Promise((n,r)=>{if(t?.aborted)return r(t.reason);const o=setTimeout(()=>{t?.removeEventListener("abort",i);n()},e);const i=()=>{clearTimeout(o);r(t?.reason)};t?.addEventListener("abort",i,{once:true})});function Q(e=process.env,t=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(t==="linux"&&!e.DISPLAY&&!e.WAYLAND_DISPLAY)return true;return false}function Ee(e){const t=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 ${t} minutes. Waiting for you to confirm\u2026 (Ctrl+C to cancel)`,""].join("\n")}async function X(e,t,n,r){const o=AbortSignal.timeout(we);const i=await e(t,{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify(n),signal:r?AbortSignal.any([r,o]):o});let u={};try{u=await i.json()}catch{}return{status:i.status,body:u&&typeof u==="object"?u:{}}}function Oe(e){const t=o=>typeof e[o]==="string"?e[o]:"";const n=(o,i)=>typeof e[o]==="number"&&Number.isFinite(e[o])?e[o]:i;const r={device_code:t("device_code"),user_code:t("user_code"),verification_uri:t("verification_uri"),verification_uri_complete:t("verification_uri_complete")||void 0,expires_in:n("expires_in",600),interval:Math.max(ve,n("interval",5))};if(!r.device_code||!r.user_code||!/^https?:\/\//u.test(r.verification_uri)){throw new l("The sign-in service answered without a device code.","refused")}return r}function be(e){const t=r=>typeof e[r]==="string"?e[r].trim():"";const n={sessionId:t("session_id"),companyId:t("company_id"),subjectId:t("subject_id"),baseUrl:t("platform_base_url").replace(/\/+$/u,"")};if(!n.sessionId||!n.companyId||!n.subjectId||!/^https?:\/\//u.test(n.baseUrl)){throw new l("The sign-in service answered without a session.","refused")}return n}async function Z(e){const t=e.fetchImpl??fetch;const n=e.sleep??Ae;const r=e.now??Date.now;const o=e.gatewayBaseUrl.replace(/\/+$/u,"");let i;try{const a=await X(t,`${o}/auth/device`,{client:"alran-code",device_name:e.deviceName??Te()},e.signal);if(a.status===404){throw new l("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 l("Too many sign-in attempts. Wait a minute and try again.","unavailable");if(a.status!==200)throw new l(`The sign-in service refused the request (HTTP ${a.status}).`,"refused");i=Oe(a.body)}catch(a){if(a instanceof l)throw a;if(e.signal?.aborted)throw new l("Sign-in cancelled.","aborted");throw new l(`Cannot reach the Ottili AI Platform at ${o}. Check the connection and try again.`,"unavailable")}e.write(Ee(i));const u=r()+i.expires_in*1e3;let s=i.interval;let c=0;for(;;){try{await n(s*1e3,e.signal)}catch{throw new l("Sign-in cancelled.","aborted")}if(r()>u)throw new l("The code expired before it was confirmed. Run `alran auth login` again.","expired");let a;try{a=await X(t,`${o}/auth/device/token`,{grant_type:ye,device_code:i.device_code},e.signal);c=0}catch{if(e.signal?.aborted)throw new l("Sign-in cancelled.","aborted");c+=1;if(c>=he){throw new l(`Lost the connection to the Ottili AI Platform at ${o}. Run \`alran auth login\` again.`,"unavailable")}continue}if(a.status===200)return be(a.body);const d=typeof a.body.error==="string"?a.body.error:"";if(d==="authorization_pending")continue;if(d==="slow_down"){s=typeof a.body.interval==="number"&&a.body.interval>s?a.body.interval:s+5;continue}if(d==="access_denied")throw new l("Sign-in was cancelled in the browser.","denied");if(d==="expired_token")throw new l("The code expired before it was confirmed. Run `alran auth login` again.","expired");if(a.status===429){s+=5;continue}throw new l(`The sign-in service answered with an error (${d||`HTTP ${a.status}`}).`,"refused")}}function Te(){try{return ge().slice(0,64)}catch{return"unknown device"}}function L(){return O(J().buildEnv)}async function Xe(e={}){const t=e.writeError??(r=>process.stderr.write(r));if(e.provider==="keycloak"){return Se({region:e.region,openBrowser:e.openBrowser!==false,openExternalTarget:e.openExternalTarget,writeError:t})}if(e.provider==="platform"){if(e.device??Q()){return _e({platformEnv:e.platformEnv??L(),writeError:t,...e.deviceAuthorization?{overrides:e.deviceAuthorization}:{}})}return Ie({platformEnv:e.platformEnv??L(),openBrowser:e.openBrowser!==false,openExternalTarget:e.openExternalTarget,writeError:t})}const n=await G({...e.readApiKey?{readApiKey:e.readApiKey}:{},...e.storeKey?{storeKey:e.storeKey}:{},consoleUrl:e.consoleUrl??F(_(L())),...e.openExternalTarget?{openExternalTarget:e.openExternalTarget}:{},openBrowser:e.openBrowser!==false,writeError:t});return n.message}async function Qe(e={}){const t=m();for(const n of Y(O())){H(t,n)}return q({...e.clearKey?{clearKey:e.clearKey}:{}})}async function _e(e){const t=new AbortController;const n=()=>t.abort(new Error("interrupted"));process.once("SIGINT",n);let r;try{r=await Z({gatewayBaseUrl:z(e.platformEnv),write:e.writeError,signal:t.signal,...e.overrides})}finally{process.removeListener("SIGINT",n)}const o=`${m()}/auth/platform/${e.platformEnv}`;const{mkdir:i}=await import("node:fs/promises");await i(o,{recursive:true});await te(o,r);return`Signed in to the Ottili AI Platform (${e.platformEnv==="prod"?"production":"development"}) with a device code.`}async function Se(e){const t=e.writeError??(f=>process.stderr.write(f));const n=e.region??"en";const r="prod";const o=k("ALRAN_KEYCLOAK_AUTHORIZATION_ENDPOINT",`https://${E}/realms/alran/protocol/openid-connect/auth`);const i=k("ALRAN_KEYCLOAK_TOKEN_ENDPOINT",`https://${E}/realms/alran/protocol/openid-connect/token`);const u=k("ALRAN_KEYCLOAK_REVOCATION_ENDPOINT",`https://${E}/realms/alran/protocol/openid-connect/revoke`);const s=N({dataDir:m(),buildEnv:r,region:n});const c=M({authHome:s.namespaceHome});const a=new $(s.statePath);let d;try{const f=ee(16).toString("base64url");d=new S({port:0,host:"127.0.0.1",baseUrl:"http://127.0.0.1",expectedState:f,onLogin:async T=>{await Pe(s,c,a,T,r,n)}});await d.start();const g=d.port;if(g===null){throw new Error("Callback server failed to start.")}const b=`http://127.0.0.1:${g}/callback`;const w=new B({authorizationEndpoint:o,tokenEndpoint:i,revocationEndpoint:u,redirectUri:b,clientId:v,scopes:R,audience:A});d.setClient(w);const p=await d.beginLogin();t(`Open this page to sign in with keycloak:
|
|
5
|
-
${p}
|
|
6
|
-
`);if(e.openBrowser!==false){const T=e.openExternalTarget??y(process.cwd());try{await T(p)}catch{t("Couldn't open the default browser. Open the URL above manually.\n")}}await d.waitForLogin();const h=await c.get(s.credentialKey);if(!h){throw new Error("Keycloak login succeeded but no credential was stored.")}return`Signed in to the Ottili AI Platform with keycloak (${xe(n)}).`}finally{if(d){try{await d.close()}catch{}}}}async function Ie(e){const t=e.writeError??(a=>process.stderr.write(a));const n=_(e.platformEnv);const r=m();const o=`${r}/auth/platform/${e.platformEnv}`;const{mkdir:i}=await import("node:fs/promises");await i(o,{recursive:true});const u=U(e.platformEnv);const s=D(u);let c;try{const a=ee(16).toString("base64url");c=new S({baseUrl:s.origin,callbackUri:s.uri,platformOidc:{platformBaseUrl:n},onLogin:async p=>{const h=p.platformSession;if(!h){throw new Error("Platform OIDC login succeeded but no session was returned.")}await te(o,h)}});try{await c.start()}catch(p){if(p.code==="EADDRINUSE"){throw new Error(`Cannot listen on ${s.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 d=c.port;if(d===null){throw new Error("Callback server failed to start.")}const f=c.platformOidcAuthorizeUrl();t(`Open this page to sign in with the Ottili Platform:
|
|
7
|
-
${f}
|
|
8
|
-
`);if(e.openBrowser!==false){const p=e.openExternalTarget??y(process.cwd());try{await p(f)}catch{t("Couldn't open the default browser. Open the URL above manually.\n")}}await c.waitForLogin();const g=await re(o);if(!g){throw new Error("Platform OIDC login succeeded but no session was stored.")}const b=new I(g);const w=await b.get("/v2/version");if(!w.ok){throw new Error(`Platform session stored but /v2/version returned HTTP ${w.status}.`)}return`Signed in to the Ottili AI Platform (${e.platformEnv==="prod"?"production":"development"}).`}finally{if(c){try{await c.close()}catch{}}}}function k(e,t){const n=process.env[e];if(n?.trim())return n.trim();return t}async function Pe(e,t,n,r,o,i){const u=Date.now();const s=1;const c={schemaVersion:j,accessToken:r.accessToken??"",refreshToken:r.refreshToken??"",tokenType:"Bearer",clientId:v,scopes:r.scopes??[],audience:A,expiresAtMs:u+(r.expiresInSec??3600)*1e3,generation:s,...r.subject?{subject:r.subject}:{},...r.accountId?{accountId:r.accountId}:{}};await t.put(e.credentialKey,c);await n.write({schemaVersion:2,status:"authenticated",storeKind:"file",clientId:v,scopes:r.scopes??[],audience:A,buildEnv:o,region:i,expiresAtMs:u+(r.expiresInSec??3600)*1e3,generation:s})}async function te(e,t){const{writePrivateConfigFileSync:n}=await import("./src-DNIDEMVV.js");const{chmod:r}=await import("node:fs/promises");if(process.platform!=="win32")await r(e,448).catch(()=>void 0);const o={...t,via:"oidc",storedAtMs:Date.now()};n(`${e}/platform-session.json`,JSON.stringify(o,null,2))}async function re(e){const{readFile:t}=await import("node:fs/promises");try{const n=await t(`${e}/platform-session.json`,"utf8");const r=JSON.parse(n);return{sessionId:typeof r.sessionId==="string"?r.sessionId:"",companyId:typeof r.companyId==="string"?r.companyId:"",subjectId:typeof r.subjectId==="string"?r.subjectId:"",baseUrl:typeof r.baseUrl==="string"?r.baseUrl:"",via:"oidc",storedAtMs:typeof r.storedAtMs==="number"?r.storedAtMs:0}}catch{return null}}function xe(e){return e==="cn"?"Alran China":"Alran Global"}async function Ze(e=O()){const t=m();const n=`${t}/auth/platform/${e}`;const r=await re(n);if(!r)return null;return new I({sessionId:r.sessionId,companyId:r.companyId,baseUrl:r.baseUrl})}export{y as a,fe as b,G as c,Xe as d,Qe as e,Ze as f};
|