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.
Files changed (127) hide show
  1. package/ALRAN_TOOLS_NOTICES.md +11 -0
  2. package/README.md +11 -16
  3. package/assets/agents/alran/skills/alran-code-product/SKILL.md +3 -3
  4. package/assets/agents/alran/skills/alran-code-product/references/account-models.md +19 -16
  5. package/chunks/{account-commands-JZ6NXTTK.js → account-commands-GW7N3MYC.js} +1 -1
  6. package/chunks/{anthropic-MN33DP4E.js → anthropic-63VE6MAE.js} +1 -1
  7. package/chunks/{application-ITGAJ4HC.js → application-WPPTE6LU.js} +1 -1
  8. package/chunks/{auth-command-V3RVPLZO.js → auth-command-36RMNQZW.js} +1 -1
  9. package/chunks/azure-openai-responses-OIP3KVKJ.js +2 -0
  10. package/chunks/chunk-2K5H5GA7.js +2 -0
  11. package/chunks/chunk-3GGKARES.js +2 -0
  12. package/chunks/chunk-5RIMHTEU.js +207 -0
  13. package/chunks/{chunk-EYK25HWR.js → chunk-5Y76VFHY.js} +1 -1
  14. package/chunks/{chunk-QIN5ZBE2.js → chunk-6DOVXX7W.js} +1 -1
  15. package/chunks/{chunk-E3GLGDGC.js → chunk-6PFI65C6.js} +1 -1
  16. package/chunks/{chunk-4PDIO3M6.js → chunk-6UXSIWCB.js} +1 -1
  17. package/chunks/{chunk-OQNU3VPS.js → chunk-C6LAAFG2.js} +2 -2
  18. package/chunks/{chunk-33CNY6GP.js → chunk-CUG7F2FN.js} +1 -1
  19. package/chunks/chunk-DFMYLGVU.js +249 -0
  20. package/chunks/{chunk-IIE366LR.js → chunk-G5MOGPZ3.js} +490 -485
  21. package/chunks/{chunk-FC4M2B7E.js → chunk-IC6A323Q.js} +1 -1
  22. package/chunks/{chunk-4X22UJQH.js → chunk-IN2Z5SSJ.js} +1 -1
  23. package/chunks/chunk-JSTSFMGK.js +70 -0
  24. package/chunks/{chunk-WWNUAU4P.js → chunk-LCC45PCZ.js} +1 -1
  25. package/chunks/{chunk-7QLAXRD2.js → chunk-MPQ6G7LH.js} +254 -254
  26. package/chunks/{chunk-FUERW2DW.js → chunk-MUXNNOSQ.js} +1 -1
  27. package/chunks/{chunk-44VPC5LA.js → chunk-NBONSNQZ.js} +1 -1
  28. package/chunks/chunk-NMKRNU5O.js +2 -0
  29. package/chunks/chunk-NVPGGFT3.js +2 -0
  30. package/chunks/chunk-NZXJAHTO.js +9 -0
  31. package/chunks/{chunk-6255CZPL.js → chunk-PCL2CVVE.js} +1 -1
  32. package/chunks/chunk-PXH4SBCS.js +3 -0
  33. package/chunks/chunk-RLJVY75P.js +28 -0
  34. package/chunks/{chunk-WYANV3IX.js → chunk-RLND4AYL.js} +1 -1
  35. package/chunks/chunk-TJC4LPRQ.js +2 -0
  36. package/chunks/chunk-U4PFHJ7Z.js +27 -0
  37. package/chunks/chunk-V2SB4U4D.js +2 -0
  38. package/chunks/chunk-VGKKKM2W.js +6 -0
  39. package/chunks/{chunk-XFCC2CI2.js → chunk-VUISZDXX.js} +1 -1
  40. package/chunks/chunk-XVGPB7TW.js +21 -0
  41. package/chunks/{chunk-CJM7ZJ6W.js → chunk-ZDI22NOK.js} +1 -1
  42. package/chunks/{data-dir-LDVKDCJ2.js → data-dir-OEPRRIOO.js} +1 -1
  43. package/chunks/{dist-2BRD4JFU.js → dist-VKYZJYR6.js} +1 -1
  44. package/chunks/{dist-EXKHRFQO.js → dist-WGTMUM3E.js} +1 -1
  45. package/chunks/{ffi-OUPK6AY6.js → ffi-EFLUAAVX.js} +1 -1
  46. package/chunks/{ffi-M5UP5J6C.js → ffi-QKKA5HYI.js} +1 -1
  47. package/chunks/{google-UJAPMFAB.js → google-RCR46TTQ.js} +1 -1
  48. package/chunks/{google-vertex-VLSF55PW.js → google-vertex-Y26T7YYR.js} +1 -1
  49. package/chunks/{install-source-JTIUC4G4.js → install-source-63OVVBMK.js} +1 -1
  50. package/chunks/launcher-2UG3JPYF.js +63 -0
  51. package/chunks/lifecycle-5IPJRP2V.js +2 -0
  52. package/chunks/{main-TQGGRHTS.js → main-7SGOQBHZ.js} +2 -2
  53. package/chunks/{mistral-ZJZUEF2X.js → mistral-NEBDKUEI.js} +1 -1
  54. package/chunks/{module-6F3E5H7Y-BN7QWGYB.js → module-6F3E5H7Y-FIMLNSCK.js} +1 -1
  55. package/chunks/{module-asyncify-R6PWJ6ZV-P4FWSBAY.js → module-asyncify-R6PWJ6ZV-Q2HJ3NOC.js} +1 -1
  56. package/chunks/{multipart-parser-L6M455MS.js → multipart-parser-JVSLI2CL.js} +1 -1
  57. package/chunks/{network-proxy-U72JCK2I.js → network-proxy-AJO7ZW3O.js} +1 -1
  58. package/chunks/openai-codex-responses-L2CIGCKO.js +2 -0
  59. package/chunks/openai-completions-C4PHW6MD.js +2 -0
  60. package/chunks/openai-responses-5NVFOW4Y.js +2 -0
  61. package/chunks/{openrouter-G2EHY5BD.js → openrouter-BKUGQT7Z.js} +1 -1
  62. package/chunks/{otel-OHXIZ666.js → otel-DRJM2PIX.js} +1 -1
  63. package/chunks/plugin-command-CIDTOPNB.js +2 -0
  64. package/chunks/provider-command-UZ7KQFAC.js +2 -0
  65. package/chunks/run-acp-command-AKDLHKMR.js +59 -0
  66. package/chunks/{run-exec-command-5ADSQR2Z.js → run-exec-command-UXTPS7LC.js} +1 -1
  67. package/chunks/{skills-command-XXXEZAG6.js → skills-command-57TF53NO.js} +1 -1
  68. package/chunks/src-5PSNGHHD.js +2 -0
  69. package/chunks/{src-IBHIRTD7.js → src-YZ26EVSY.js} +1 -1
  70. package/chunks/telemetry-3NXMCOVD.js +2 -0
  71. package/chunks/{telemetry-command-COQG2AKK.js → telemetry-command-CMDERYNN.js} +1 -1
  72. package/chunks/{tools-WDBB2JKV.js → tools-CRJR35HS.js} +1 -1
  73. package/chunks/{undici-TUGHZJSA.js → undici-O4OQVZ6I.js} +1 -1
  74. package/chunks/{update-NB6OD572.js → update-ACFAGV6F.js} +1 -1
  75. package/cli.js +2 -3
  76. package/embedded/alran-tools/cli.mjs +1 -5
  77. package/embedded/alran-tools/manifest.json +1 -1
  78. package/image-preview-worker.js +1 -1
  79. package/matrix-mcp-stdio.js +1 -1
  80. package/package.json +1 -1
  81. package/quickjs-worker.js +1 -1
  82. package/chunks/azure-openai-responses-OWHMUNKC.js +0 -2
  83. package/chunks/chunk-C3CMJAAV.js +0 -3
  84. package/chunks/chunk-ENHOPPS7.js +0 -16
  85. package/chunks/chunk-FSNYOJPJ.js +0 -2
  86. package/chunks/chunk-FXOH6TEQ.js +0 -21
  87. package/chunks/chunk-GRXX6I72.js +0 -2
  88. package/chunks/chunk-GSYHBK5Q.js +0 -6
  89. package/chunks/chunk-IWK7PZP7.js +0 -207
  90. package/chunks/chunk-KCLRJQ53.js +0 -59
  91. package/chunks/chunk-M7GW4VMR.js +0 -27
  92. package/chunks/chunk-QFUV5PX6.js +0 -2
  93. package/chunks/chunk-TW23QKAD.js +0 -3
  94. package/chunks/chunk-U7U3DJHF.js +0 -2
  95. package/chunks/chunk-WTAJMYF2.js +0 -249
  96. package/chunks/chunk-YLQXZBEL.js +0 -2
  97. package/chunks/chunk-Z6BHCXKT.js +0 -25
  98. package/chunks/chunk-Z6HBNJCA.js +0 -8
  99. package/chunks/launcher-FCZ3EDBF.js +0 -61
  100. package/chunks/lifecycle-GY435YMF.js +0 -2
  101. package/chunks/openai-codex-responses-FPCDNRL5.js +0 -2
  102. package/chunks/openai-completions-D32YW6KL.js +0 -2
  103. package/chunks/openai-responses-ZCGSENM4.js +0 -2
  104. package/chunks/plugin-command-OSAFHS7C.js +0 -2
  105. package/chunks/provider-command-SKTCHD4E.js +0 -2
  106. package/chunks/run-acp-command-SG2BDMFJ.js +0 -2
  107. package/chunks/src-DNIDEMVV.js +0 -2
  108. package/chunks/telemetry-J7ZLGF5X.js +0 -2
  109. /package/chunks/{chunk-EOR6EDNR.js → chunk-2AYWJZ72.js} +0 -0
  110. /package/chunks/{chunk-YPV2X2RG.js → chunk-4XP5XUIZ.js} +0 -0
  111. /package/chunks/{chunk-NWB7LFOK.js → chunk-5DQTVSQV.js} +0 -0
  112. /package/chunks/{chunk-OIQ336YE.js → chunk-EJN3SE5B.js} +0 -0
  113. /package/chunks/{chunk-A7GMJNA2.js → chunk-K5DTFR6D.js} +0 -0
  114. /package/chunks/{chunk-ZQOALVGL.js → chunk-R44C5DM6.js} +0 -0
  115. /package/chunks/{chunk-PNXZWSWT.js → chunk-UJCAE7SG.js} +0 -0
  116. /package/chunks/{chunk-J3KCPYZT.js → chunk-W5ZOLW7T.js} +0 -0
  117. /package/chunks/{chunk-XAGZ6ZEU.js → chunk-XLVABFJC.js} +0 -0
  118. /package/chunks/{chunk-N5SVBCUB.js → chunk-XSEU4WQD.js} +0 -0
  119. /package/chunks/{chunk-CSOUJVKM.js → chunk-Z5HOCNTZ.js} +0 -0
  120. /package/chunks/{emscripten-module-ZS3PMSDF.js → emscripten-module-3WGSFZYF.js} +0 -0
  121. /package/chunks/{emscripten-module-XPTEOIWW.js → emscripten-module-74WUXTHL.js} +0 -0
  122. /package/chunks/{emscripten-module-WYNDFH3N.js → emscripten-module-MCN4Y3N4.js} +0 -0
  123. /package/chunks/{emscripten-module-RD6P2XH5.js → emscripten-module-NEAT5LGD.js} +0 -0
  124. /package/chunks/{ffi-ORLOPBB3.js → ffi-JIGPPPF7.js} +0 -0
  125. /package/chunks/{ffi-IO7WZQNG.js → ffi-RLX77WFG.js} +0 -0
  126. /package/chunks/{pdfjs-SHZAF7PF.js → pdfjs-2UOWBGC2.js} +0 -0
  127. /package/chunks/{photon_rs-C52RL4CI.js → photon_rs-MVWYTYTO.js} +0 -0
@@ -0,0 +1,207 @@
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 ge,c as K}from"./chunk-5Y76VFHY.js";import{Da as fe,Ea as me,a as Qe}from"./chunk-XVGPB7TW.js";import{e as Ze}from"./chunk-XQK7JM66.js";var m="alran-public";var h=["agent.default"];var y="agent-backend";var Ae="alran-public";var Z=["openid","profile","email","agent.default"];var Q="agent-backend";var ur="auth.ottili.one";var ye={dev:"http://127.0.0.1:18360",prod:"https://platform.ottili.one"};function hr(r){if(r==="dev"){const t=process.env.ALRAN_PLATFORM_BASE_URL_DEV;if(t?.trim())return t.trim();return ye.dev}const e=process.env.ALRAN_PLATFORM_BASE_URL_PROD??process.env.ALRAN_PLATFORM_BASE_URL;if(e?.trim())return e.trim();return ye.prod}var Xe="http://127.0.0.1:18370/callback";function pr(r){const e=process.env.ALRAN_OIDC_CALLBACK_URI?.trim();if(e)return e;const t=r==="dev"?process.env.ALRAN_OIDC_CALLBACK_URI_DEV:process.env.ALRAN_OIDC_CALLBACK_URI_PROD;if(t?.trim())return t.trim();return Xe}function we(r){let e;try{e=new URL(r)}catch{throw new Error(`OIDC callback URI "${r}" is not an absolute URL.`)}if(e.protocol!=="http:"&&e.protocol!=="https:"){throw new Error(`OIDC callback URI "${r}" must use http or https.`)}if(e.username!==""||e.password!==""){throw new Error(`OIDC callback URI "${r}" must not carry credentials.`)}if(e.search!==""||e.hash!==""){throw new Error(`OIDC callback URI "${r}" must not carry a query or fragment.`)}if(e.pathname===""||e.pathname==="/"){throw new Error(`OIDC callback URI "${r}" must name a callback path.`)}const t=e.port?Number(e.port):e.protocol==="https:"?443:80;const n=e.hostname;const i=n.startsWith("[")&&n.endsWith("]")?n.slice(1,-1):n;return{uri:`${e.origin}${e.pathname}`,origin:e.origin,host:i,port:t,path:e.pathname}}import{createHash as et}from"node:crypto";import{join as w,resolve as tt}from"node:path";function X(r){const e=w(tt(r.dataDir),"auth");const t=w(e,r.buildEnv,r.region,m);const n=`com.alran.oauth.${r.buildEnv}.${r.region}`;const i=et("sha256").update(`${e}\0${m}`).digest("base64url");return{authHome:e,namespaceHome:t,lockPath:w(t,"auth.lock"),statePath:w(t,"auth-state.json"),credentialPath:w(t,"auth.json"),legacyLockPath:w(e,"auth.lock"),legacyStatePath:w(e,"auth-state.json"),legacyEncryptedCredentialPath:w(e,"credentials.enc"),buildEnv:r.buildEnv,region:r.region,credentialKey:{service:n,account:i}}}var Ee=Ze(Qe(),1);import{open as ut}from"node:fs/promises";import{chmod as be,mkdir as it,open as ot,rename as st,unlink as at}from"node:fs/promises";import{randomUUID as ct}from"node:crypto";import{dirname as dt}from"node:path";import{setTimeout as lt}from"node:timers/promises";import{AsyncLocalStorage as rt}from"node:async_hooks";var F=new rt;var ee=class extends Error{constructor(t,n){super("Failed to save authentication credentials. Please retry.",{cause:n});this.authDiagnostic=t;this.name="AuthCredentialSaveError"}authDiagnostic;code="AUTH_CREDENTIAL_SAVE_FAILED"};function L(r,e,t,n,i=0){const o={...r,pid:process.pid,timeMs:Date.now(),outcome:t,retryCount:i,...nt(n)};try{e?.(o)}catch{}return o}function ve(r,e){const t=F.getStore();if(!t)return;t.retryCount=e;L(t.context,t.observer,"retry",r,e)}async function Se(r,e,t){return F.run({context:r,observer:e,retryCount:0},async()=>{try{const n=await t();L(r,e,"success",void 0,F.getStore()?.retryCount);return n}catch(n){const i=L(r,e,"failure",n,F.getStore()?.retryCount);throw new ee(i,n)}})}function nt(r){if(!r||typeof r!=="object")return{};const e=r;return{...typeof e.name==="string"&&/^[A-Za-z]{1,64}$/u.test(e.name)?{errorName:e.name}:{},...typeof e.code==="string"&&/^[A-Za-z_]{1,64}$/u.test(e.code)?{code:e.code}:{},...typeof e.errno==="number"&&Number.isFinite(e.errno)?{errno:e.errno}:{},...typeof e.syscall==="string"&&/^[a-z]{1,32}$/u.test(e.syscall)?{syscall:e.syscall}:{},...typeof e.httpStatus==="number"&&Number.isInteger(e.httpStatus)?{httpStatus:e.httpStatus}:{}}}async function j(r){await it(r,{recursive:true,mode:448});if(process.platform!=="win32")await be(r,448)}async function V(r,e){const t=dt(r);await j(t);const n=`${r}.${process.pid}.${ct()}.tmp`;const i=await ot(n,"wx",384);try{try{await i.writeFile(e,{encoding:"utf8"});await i.sync()}finally{await i.close()}if(process.platform!=="win32")await be(n,384);for(let o=0;;o+=1){try{await st(n,r);break}catch(s){const a=s.code;if(o>=3||!["EPERM","EACCES","EBUSY"].includes(a??""))throw s;ve(s,o+1);await lt(40*2**o)}}}catch(o){await at(n).catch(()=>void 0);throw o}}import{dirname as ht}from"node:path";var _=class{constructor(e,t={}){this.lockPath=e;this.staleMs=t.staleMs??3e4;this.retries=t.retries??120}lockPath;staleMs;retries;async withLock(e){await j(ht(this.lockPath));const t=await ut(this.lockPath,"a",384);await t.close();let n;const i=await Ee.default.lock(this.lockPath,{realpath:false,stale:this.staleMs,retries:{retries:this.retries,factor:1.15,minTimeout:5,maxTimeout:250},onCompromised:o=>{n??=o}});try{return await e()}finally{try{await i()}catch(o){if(!n)throw o}if(n)throw n}}};import{readFile as pt}from"node:fs/promises";var P=2;var ft=1;var mt=/access[_-]?token|refresh[_-]?token|device[_-]?code|code[_-]?verifier/iu;function Pe(r){if(typeof r!=="object"||r===null)return;for(const[e,t]of Object.entries(r)){if(mt.test(e)){throw new TypeError("Sensitive OAuth fields cannot be persisted in auth-state.json.")}Pe(t)}}function _e(r){if(typeof r!=="object"||r===null||Array.isArray(r)){throw new TypeError("Invalid OAuth state.")}const e=r;const t=typeof e.schemaVersion==="number"&&Number.isInteger(e.schemaVersion)&&e.schemaVersion>=ft&&e.schemaVersion<=P&&["anonymous","authorizing","authenticated","refreshing","scope_upgrade_required","logging_out","logout_pending","expired","error"].includes(e.status)&&(e.schemaVersion===1&&(e.storeKind==="os-keyring"||e.storeKind==="file")||e.schemaVersion===P&&e.storeKind==="file")&&e.clientId==="alran-public"&&Array.isArray(e.scopes)&&e.scopes.every(n=>typeof n==="string")&&e.audience==="agent-backend"&&gt(e.buildEnv,e.region)&&(e.expiresAtMs===void 0||typeof e.expiresAtMs==="number"&&Number.isFinite(e.expiresAtMs))&&Number.isSafeInteger(e.generation)&&e.generation>=0&&(e.authorization===void 0||At(e.authorization))&&(e.refresh===void 0||yt(e.refresh));if(!t)throw new TypeError("Invalid OAuth state.");Pe(e);return e}function gt(r,e){if(r===void 0&&e===void 0)return true;return(r==="dev"||r==="test"||r==="staging"||r==="prod")&&(e==="cn"||e==="en")}function yt(r){if(typeof r!=="object"||r===null||Array.isArray(r))return false;const e=r;if(typeof e.id!=="string"||!e.id.length)return false;if(e.owner===void 0)return true;if(typeof e.owner!=="object"||e.owner===null)return false;const t=e.owner;return Number.isSafeInteger(t.pid)&&t.pid>0&&Number.isSafeInteger(t.startedAtMs)&&t.startedAtMs>0}function At(r){if(typeof r!=="object"||r===null||Array.isArray(r))return false;const e=r;return typeof e.leaseId==="string"&&e.leaseId.length>0&&typeof e.leaseExpiresAtMs==="number"&&Number.isFinite(e.leaseExpiresAtMs)&&te(e.userCode)&&te(e.verificationUri)&&te(e.verificationUriComplete)}function te(r){return r===void 0||typeof r==="string"}var R=class{constructor(e){this.path=e}path;async read(){let e;try{e=await pt(this.path,"utf8")}catch(t){if(t.code==="ENOENT")return null;throw t}try{return _e(JSON.parse(e))}catch(t){if(t instanceof TypeError)throw t;throw new TypeError("Invalid OAuth state.")}}async write(e){const t=_e(e);await V(this.path,`${JSON.stringify(t,null,2)}
3
+ `)}};async function wt(r){const e=await vt(r);const t=new R(r.statePath);const n=new _(r.lockPath);await n.withLock(async()=>{const i=await t.read();if(i?.schemaVersion===P)return;const o=i??e;if(!o)return;await t.write(bt(o,r))})}async function vt(r){const e=new R(r.legacyStatePath);const t=new _(r.legacyLockPath);return t.withLock(async()=>{const n=await e.read();if(!St(n,r))return null;const{authorization:i,...o}=n;await e.write({...o,status:"error"});return n})}function St(r,e){return r!==null&&r.status!=="error"&&r.buildEnv===e.buildEnv&&r.region===e.region}function bt(r,e){return{schemaVersion:P,status:"anonymous",storeKind:"file",clientId:"alran-public",scopes:["agent.default"],audience:"agent-backend",buildEnv:e.buildEnv,region:e.region,generation:r.generation+1}}import{createHash as Et,randomBytes as _t}from"node:crypto";var Pt="urn:ietf:params:oauth:grant-type:device_code";var l=class extends Error{constructor(t,n,i){super(n??`The OAuth server rejected the request (${t}${i?`, HTTP ${i}`:""}).`);this.code=t;this.httpStatus=i;this.name="OAuthProtocolError"}code;httpStatus};var re=class{constructor(e){this.options=e;this.fetchImpl=e.fetchImpl??fetch;this.sleep=e.sleep??(t=>new Promise(n=>setTimeout(n,t)));this.now=e.now??Date.now}options;fetchImpl;sleep;now;async startDeviceAuthorization(e={}){const t=_t(32).toString("base64url");const n=Et("sha256").update(t,"ascii").digest("base64url");const i=await this.postForm(this.options.deviceAuthorizationEndpoint,{client_id:m,scope:h.join(" "),audience:y,code_challenge:n,code_challenge_method:"S256"},{headers:this.options.deviceAuthorizationHeaders,signal:e.signal});const o=p(i,"user_code");const s=p(i,"device_code");const a=$(i,"expired_in");const c=!s&&Boolean(o)&&a!==void 0;const u=s??(c?o:void 0);const d=p(i,"verification_uri")??p(i,"verification_url");const g=$(i,"expires_in")??Ct(a,this.now());const W=$(i,"interval");const We=c&&W!==void 0?W/1e3:W??5;if(!u||!o||!d||!g){throw new l("invalid_device_authorization_response")}return{deviceCode:u,codeVerifier:t,...c?{tokenPollingParameter:"user_code"}:{},userCode:o,verificationUri:d,...p(i,"verification_uri_complete")||c?{verificationUriComplete:p(i,"verification_uri_complete")??d}:{},expiresInSec:g,intervalSec:We}}async pollDeviceToken(e,t={}){const n=this.now()+e.expiresInSec*1e3;let i=e.intervalSec*1e3;while(this.now()<n){t.signal?.throwIfAborted();const o=e.tokenPollingParameter==="user_code"?{user_code:e.userCode}:{device_code:e.deviceCode};const s=await this.postFormAllowOAuthError(this.options.tokenEndpoint,{grant_type:Pt,...o,client_id:m,code_verifier:e.codeVerifier},{signal:t.signal});const a=p(s.body,"status");if(s.ok&&a==="pending"){await B(this.sleep,i,t.signal);continue}if(s.ok&&a==="slow_down"){i+=5e3;await B(this.sleep,i,t.signal);continue}if(s.ok&&(a==="denied"||a==="access_denied")){throw new l("access_denied")}if(s.ok&&(a==="expired"||a==="expired_token")){throw new l("expired_token")}if(s.ok)return Re(s.body);if(s.error==="authorization_pending"){await B(this.sleep,i,t.signal);continue}if(s.error==="slow_down"){i+=5e3;await B(this.sleep,i,t.signal);continue}throw new l(s.error??"device_authorization_failed",void 0,s.status)}throw new l("expired_token","The OAuth device authorization expired.")}async refreshToken(e){const t=await this.postForm(this.options.tokenEndpoint,{grant_type:"refresh_token",refresh_token:e,client_id:m,scope:h.join(" "),audience:y});return Re(t,e)}async revokeToken(e){const t=await this.postFormAllowOAuthError(this.options.revocationEndpoint,{token:e,token_type_hint:"refresh_token",client_id:m},{allowEmptySuccess:true});if(!t.ok)throw new l(t.error??"oauth_request_failed",void 0,t.status)}async postForm(e,t,n={}){const i=await this.postFormAllowOAuthError(e,t,n);if(!i.ok)throw new l(i.error??"oauth_request_failed",void 0,i.status);return i.body}async postFormAllowOAuthError(e,t,n={}){const i=await this.fetchImpl(e,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded",...n.headers},body:new URLSearchParams(t),signal:n.signal});const o=q(await i.json().catch(()=>void 0));if(!o&&i.ok&&n.allowEmptySuccess)return{ok:true,status:i.status,body:{}};if(!o)throw new l("invalid_json_response",void 0,i.status);const s=p(o,"error");return{ok:i.ok&&!s,status:i.status,body:o,...s?{error:s}:{}}}};async function B(r,e,t){if(!t){await r(e);return}t.throwIfAborted();let n;const i=()=>n(t.reason);const o=new Promise((s,a)=>{n=a});t.addEventListener("abort",i,{once:true});try{await Promise.race([r(e),o])}finally{t.removeEventListener("abort",i)}}function Re(r,e){const t=p(r,"access_token");const n=p(r,"refresh_token")??e;const i=p(r,"token_type");const o=$(r,"expires_in");const s=t?Rt(t):void 0;const a=kt(r.scope??s?.scope??s?.scp);if(!t||!n||i?.toLowerCase()!=="bearer"||!o||!a.includes(h[0])){throw new l("invalid_token_response")}return{accessToken:t,refreshToken:n,tokenType:"Bearer",scopes:a,audience:y,expiresInSec:o,...p(s,"sub")?{subject:p(s,"sub")}:{},...p(s,"account_id")?{accountId:p(s,"account_id")}:{}}}function Rt(r){const e=r.split(".");if(e.length!==3||!e[1])return void 0;try{return q(JSON.parse(Buffer.from(e[1],"base64url").toString("utf8")))}catch{return void 0}}function kt(r){if(typeof r==="string")return r.split(/\s+/u).filter(Boolean);if(Array.isArray(r)&&r.every(e=>typeof e==="string"))return r;return[]}function q(r){return typeof r==="object"&&r!==null&&!Array.isArray(r)?r:void 0}function p(r,e){const t=q(r);const n=t?.[e];return typeof n==="string"&&n.trim()?n.trim():void 0}function $(r,e){const t=q(r);const n=t?.[e];return typeof n==="number"&&Number.isFinite(n)&&n>0?n:void 0}function Ct(r,e){if(r===void 0)return void 0;if(r<1e12)return r;const t=r-e;return t>0?Math.ceil(t/1e3):void 0}import{createHash as Ot,randomBytes as ke}from"node:crypto";var Ce=class{constructor(e){this.options=e;this.fetchImpl=e.fetchImpl??fetch;this.redirectUri=e.redirectUri;this.clientId=e.clientId??Ae;this.scopes=e.scopes?[...e.scopes]:[...Z];this.audience=e.audience??Q}options;fetchImpl;redirectUri;clientId;scopes;audience;async startAuthorizationCodeFlow(){const e=ke(32).toString("base64url");const t=Ot("sha256").update(e,"ascii").digest("base64url");const n=ke(16).toString("base64url");const i=new URL(this.options.authorizationEndpoint);i.searchParams.set("response_type","code");i.searchParams.set("client_id",this.clientId);i.searchParams.set("redirect_uri",this.redirectUri);i.searchParams.set("scope",this.scopes.join(" "));i.searchParams.set("state",n);i.searchParams.set("code_challenge",t);i.searchParams.set("code_challenge_method","S256");if(this.audience)i.searchParams.set("audience",this.audience);return{authorizeUrl:i.toString(),codeVerifier:e,state:n}}async exchangeCodeForToken(e,t,n,i){if(n!==void 0&&i!==n){throw new l("state_mismatch")}const o=await this.postForm(this.options.tokenEndpoint,{grant_type:"authorization_code",code:e,redirect_uri:this.redirectUri,client_id:this.clientId,code_verifier:t});return Oe(o)}async refreshToken(e){const t=await this.postForm(this.options.tokenEndpoint,{grant_type:"refresh_token",refresh_token:e,client_id:this.clientId,scope:this.scopes.join(" "),audience:this.audience});return Oe(t,e)}async revokeToken(e){const t=await this.postFormAllowOAuthError(this.options.revocationEndpoint,{token:e,token_type_hint:"refresh_token",client_id:this.clientId},{allowEmptySuccess:true});if(!t.ok){throw new l(t.error??"oauth_request_failed",void 0,t.status)}}async postForm(e,t,n={}){const i=await this.postFormAllowOAuthError(e,t,n);if(!i.ok)throw new l(i.error??"oauth_request_failed",void 0,i.status);return i.body}async postFormAllowOAuthError(e,t,n={}){const i=await this.fetchImpl(e,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded",...n.headers},body:new URLSearchParams(t),signal:n.signal});const o=G(await i.json().catch(()=>void 0));if(!o&&i.ok&&n.allowEmptySuccess)return{ok:true,status:i.status,body:{}};if(!o)throw new l("invalid_json_response",void 0,i.status);const s=v(o,"error");return{ok:i.ok&&!s,status:i.status,body:o,...s?{error:s}:{}}}};function Oe(r,e){const t=v(r,"access_token");const n=v(r,"refresh_token")??e;const i=v(r,"token_type");const o=It(r,"expires_in");const s=t?Tt(t):void 0;const a=xt(r.scope??s?.scope??s?.scp);if(!t||!n||i?.toLowerCase()!=="bearer"||!o||!a.includes(Z[0])){throw new l("invalid_token_response")}return{accessToken:t,refreshToken:n,tokenType:"Bearer",scopes:a,audience:Q,expiresInSec:o,...v(s,"sub")?{subject:v(s,"sub")}:{},...v(s,"account_id")?{accountId:v(s,"account_id")}:{}}}function Tt(r){const e=r.split(".");if(e.length!==3||!e[1])return void 0;try{return G(JSON.parse(Buffer.from(e[1],"base64url").toString("utf8")))}catch{return void 0}}function xt(r){if(typeof r==="string")return r.split(/\s+/u).filter(Boolean);if(Array.isArray(r)&&r.every(e=>typeof e==="string"))return r;return[]}function G(r){return typeof r==="object"&&r!==null&&!Array.isArray(r)?r:void 0}function v(r,e){const t=G(r);const n=t?.[e];return typeof n==="string"&&n.trim()?n.trim():void 0}function It(r,e){const t=G(r);const n=t?.[e];return typeof n==="number"&&Number.isFinite(n)&&n>0?n:void 0}import{createServer as Lt}from"node:http";function Te(r){const e=new URLSearchParams({return_to:r.callback});if(r.prompt)e.set("prompt",r.prompt);return`${r.platformOrigin.replace(/\/+$/,"")}/v2/auth/oidc/login?${e}`}async function xe(r,e=fetch){const t=await e(`${r.platformBaseUrl.replace(/\/+$/,"")}/v2/auth/sessions/handoff`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({code:r.code})});if(!t.ok){throw Object.assign(new Error(`Platform OIDC handoff refused: HTTP ${t.status}`),{status:t.status,code:"platform_handoff_refused"})}const n=await t.json().catch(()=>({}));const i=n.data;const o=i!==null&&typeof i==="object"?i:n;const s=typeof o.session_id==="string"?o.session_id:void 0;const a=typeof o.company_id==="string"?o.company_id:void 0;const c=typeof o.subject_id==="string"?o.subject_id:void 0;const u=typeof o.base_url==="string"&&o.base_url.length>0?o.base_url:r.platformBaseUrl.replace(/\/+$/,"");if(!s||!a){throw new l("platform_handoff_invalid","The Platform handoff response is missing session_id or company_id.")}return{sessionId:s,companyId:a,subjectId:c??"",baseUrl:u,via:"oidc"}}function Nt(r){return`<!DOCTYPE html>
4
+ <html lang="en">
5
+ <head>
6
+ <meta charset="utf-8" />
7
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
8
+ <title>Sign in \u2013 Alran Code</title>
9
+ <link rel="stylesheet" href="https://unpkg.com/@ottili/foundation-ui@2.0.0-alpha.1/dist/styles.css" />
10
+ <style>
11
+ :root {
12
+ --ottili-auth-max-width: 380px;
13
+ --ottili-auth-card-radius: var(--ottili-radius-md, 12px);
14
+ }
15
+ html, body { height: 100%; margin: 0; }
16
+ body {
17
+ font-family: var(--ottili-font-sans, system-ui, -apple-system, sans-serif);
18
+ background: var(--ottili-color-surface-canvas, #f4f5f7);
19
+ color: var(--ottili-color-text-primary, #16181d);
20
+ display: flex;
21
+ align-items: center;
22
+ justify-content: center;
23
+ min-height: 100vh;
24
+ }
25
+ .ottili-auth-shell {
26
+ width: min(var(--ottili-auth-max-width), calc(100vw - 32px));
27
+ }
28
+ .ottili-auth-shell__sign-in {
29
+ background: var(--ottili-color-surface-raised, #ffffff);
30
+ border: 1px solid var(--ottili-color-border-default, #d9dce3);
31
+ border-radius: var(--ottili-auth-card-radius);
32
+ padding: var(--ottili-space-page, 32px);
33
+ box-shadow: var(--ottili-elevation-raised, 0 4px 6px -1px rgb(0 0 0 / 0.1));
34
+ }
35
+ .ottili-auth-heading {
36
+ font-family: var(--ottili-font-sans, system-ui, -apple-system, sans-serif);
37
+ font-size: var(--ottili-type-h2-size, 22px);
38
+ line-height: var(--ottili-type-h2-line, 1.3);
39
+ margin: 0 0 8px;
40
+ color: var(--ottili-color-text-primary, #16181d);
41
+ }
42
+ .ottili-auth-shell__sign-in p {
43
+ margin: 0 0 24px;
44
+ color: var(--ottili-color-text-secondary, #4a5060);
45
+ line-height: var(--ottili-type-body-line, 1.5);
46
+ }
47
+ .ottili-auth-button {
48
+ width: 100%;
49
+ display: block;
50
+ text-align: center;
51
+ padding: 10px 14px;
52
+ border-radius: var(--ottili-radius-sm, 8px);
53
+ background: var(--ottili-color-text-primary, #0a7d3b);
54
+ color: var(--ottili-color-text-inverse, #ffffff);
55
+ border: none;
56
+ font-family: inherit;
57
+ font-size: var(--ottili-type-body-size, 14px);
58
+ font-weight: 600;
59
+ cursor: pointer;
60
+ text-decoration: none;
61
+ }
62
+ .ottili-auth-button:hover {
63
+ opacity: 0.9;
64
+ }
65
+ .ottili-auth-button:focus-visible {
66
+ outline: 2px solid var(--ottili-color-focus-ring, #0a7d3b);
67
+ outline-offset: 2px;
68
+ }
69
+ .hint {
70
+ margin-top: 24px;
71
+ font-size: 12px;
72
+ color: var(--ottili-color-text-secondary, #6b7180);
73
+ }
74
+ </style>
75
+ </head>
76
+ <body>
77
+ <div class="ottili-auth-shell" data-ottili-state="signed_out">
78
+ <div class="ottili-auth-shell__sign-in">
79
+ <h2 class="ottili-auth-heading">Sign in</h2>
80
+ <p>You'll be redirected to the Ottili Platform to complete sign-in.</p>
81
+ <a class="ottili-auth-button" href="${U(r)}">Continue to sign-in</a>
82
+ <p class="hint">If you're not redirected automatically, click the button above.</p>
83
+ </div>
84
+ </div>
85
+ <script>
86
+ (function() {
87
+ const url = "${U(r)}";
88
+ if (url) window.location.replace(url);
89
+ })();
90
+ </script>
91
+ </body>
92
+ </html>`}function Ut(){return`<!DOCTYPE html>
93
+ <html lang="en">
94
+ <head>
95
+ <meta charset="utf-8" />
96
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
97
+ <title>Signed in \u2013 Alran Code</title>
98
+ <link rel="stylesheet" href="https://unpkg.com/@ottili/foundation-ui@2.0.0-alpha.1/dist/styles.css" />
99
+ <style>
100
+ :root {
101
+ --ottili-auth-max-width: 380px;
102
+ --ottili-auth-card-radius: var(--ottili-radius-md, 12px);
103
+ }
104
+ html, body { height: 100%; margin: 0; }
105
+ body {
106
+ font-family: var(--ottili-font-sans, system-ui, -apple-system, sans-serif);
107
+ background: var(--ottili-color-surface-canvas, #f4f5f7);
108
+ color: var(--ottili-color-text-primary, #16181d);
109
+ display: flex;
110
+ align-items: center;
111
+ justify-content: center;
112
+ min-height: 100vh;
113
+ }
114
+ .ottili-auth-shell {
115
+ width: min(var(--ottili-auth-max-width), calc(100vw - 32px));
116
+ }
117
+ .ottili-auth-shell__sign-in {
118
+ background: var(--ottili-color-surface-raised, #ffffff);
119
+ border: 1px solid var(--ottili-color-border-default, #d9dce3);
120
+ border-radius: var(--ottili-auth-card-radius);
121
+ padding: var(--ottili-space-page, 32px);
122
+ box-shadow: var(--ottili-elevation-raised, 0 4px 6px -1px rgb(0 0 0 / 0.1));
123
+ text-align: center;
124
+ }
125
+ .ottili-auth-heading {
126
+ font-family: var(--ottili-font-sans, system-ui, -apple-system, sans-serif);
127
+ font-size: var(--ottili-type-h2-size, 22px);
128
+ line-height: var(--ottili-type-h2-line, 1.3);
129
+ margin: 0 0 16px;
130
+ color: var(--ottili-color-text-primary, #16181d);
131
+ }
132
+ .ottili-auth-shell__sign-in p {
133
+ margin: 0;
134
+ color: var(--ottili-color-text-secondary, #4a5060);
135
+ line-height: var(--ottili-type-body-line, 1.5);
136
+ }
137
+ </style>
138
+ </head>
139
+ <body>
140
+ <div class="ottili-auth-shell" data-ottili-state="active">
141
+ <div class="ottili-auth-shell__sign-in">
142
+ <h2 class="ottili-auth-heading" style="color: var(--ottili-color-text-primary, #15803d);">Signed in</h2>
143
+ <p>You can close this window and return to Alran Code.</p>
144
+ </div>
145
+ </div>
146
+ <script>
147
+ window.close?.();
148
+ </script>
149
+ </body>
150
+ </html>`}function N(r){return`<!DOCTYPE html>
151
+ <html lang="en">
152
+ <head>
153
+ <meta charset="utf-8" />
154
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
155
+ <title>Sign-in failed \u2013 Alran Code</title>
156
+ <link rel="stylesheet" href="https://unpkg.com/@ottili/foundation-ui@2.0.0-alpha.1/dist/styles.css" />
157
+ <style>
158
+ :root {
159
+ --ottili-auth-max-width: 380px;
160
+ --ottili-auth-card-radius: var(--ottili-radius-md, 12px);
161
+ }
162
+ html, body { height: 100%; margin: 0; }
163
+ body {
164
+ font-family: var(--ottili-font-sans, system-ui, -apple-system, sans-serif);
165
+ background: var(--ottili-color-surface-canvas, #f4f5f7);
166
+ color: var(--ottili-color-text-primary, #16181d);
167
+ display: flex;
168
+ align-items: center;
169
+ justify-content: center;
170
+ min-height: 100vh;
171
+ }
172
+ .ottili-auth-shell {
173
+ width: min(var(--ottili-auth-max-width), calc(100vw - 32px));
174
+ }
175
+ .ottili-auth-shell__sign-in {
176
+ background: var(--ottili-color-surface-raised, #ffffff);
177
+ border: 1px solid var(--ottili-color-border-danger, #f3b8b2);
178
+ border-radius: var(--ottili-auth-card-radius);
179
+ padding: var(--ottili-space-page, 32px);
180
+ box-shadow: var(--ottili-elevation-raised, 0 4px 6px -1px rgb(0 0 0 / 0.1));
181
+ }
182
+ .ottili-auth-heading {
183
+ font-family: var(--ottili-font-sans, system-ui, -apple-system, sans-serif);
184
+ font-size: var(--ottili-type-h2-size, 22px);
185
+ line-height: var(--ottili-type-h2-line, 1.3);
186
+ margin: 0 0 16px;
187
+ color: var(--ottili-color-text-danger, #8a1c12);
188
+ }
189
+ .ottili-auth-shell__sign-in p {
190
+ margin: 0;
191
+ color: var(--ottili-color-text-secondary, #4a5060);
192
+ line-height: var(--ottili-type-body-line, 1.5);
193
+ white-space: pre-wrap;
194
+ }
195
+ </style>
196
+ </head>
197
+ <body>
198
+ <div class="ottili-auth-shell" data-ottili-state="signed_out">
199
+ <div class="ottili-auth-shell__sign-in">
200
+ <h2 class="ottili-auth-heading">Sign-in failed</h2>
201
+ <p>${U(r)}</p>
202
+ </div>
203
+ </div>
204
+ </body>
205
+ </html>`}function U(r){return r.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}function Ie(r){return r.includes(":")&&!r.startsWith("[")?`[${r}]`:r}var Le=class{server=null;listenedPort=null;host;baseUrl;callbackUri;callbackPath;client=null;expectedState;platformOidc;onLogin;onError;startResult=null;resolveLogin=null;rejectLogin=null;constructor(e){const t=e.callbackUri?we(e.callbackUri):null;this.listenedPort=t?.port??e.port??0;this.host=t?.host??e.host??"127.0.0.1";this.baseUrl=e.baseUrl;this.callbackUri=t?.uri;this.callbackPath=t?.path??"/callback";this.expectedState=e.expectedState;this.platformOidc=e.platformOidc;this.onLogin=e.onLogin;this.onError=e.onError;if(e.client)this.setClient(e.client)}setClient(e){this.client=e}get port(){return this.listenedPort}async start(){const e=this.listenedPort??0;return new Promise((t,n)=>{this.server=Lt((i,o)=>{void this.handleRequest(i,o)});this.server.once("error",n);this.server.listen(e,this.host,()=>{this.server.once("error",()=>{});const i=this.server.address();if(i&&typeof i==="object"){this.listenedPort=i.port}t(`${this.baseUrl.split("://")[0]}://${Ie(this.host)}:${this.listenedPort}`)})})}async beginLogin(){if(!this.client)throw new Error("Authorization code client not set.");this.startResult=await this.client.startAuthorizationCodeFlow();return this.startResult.authorizeUrl}platformOidcAuthorizeUrl(){if(!this.platformOidc)throw new Error("Platform OIDC is not configured.");const e=this.listenedPort??0;const t=this.callbackUri??`http://${Ie(this.host)}:${e}/callback`;return Te({platformOrigin:this.platformOidc.platformBaseUrl,callback:t})}waitForLogin(){return new Promise((e,t)=>{this.resolveLogin=e;this.rejectLogin=t})}close(){if(!this.server)return Promise.resolve();return new Promise(e=>{this.server.close(()=>{this.server=null;e()})})}async handleRequest(e,t){const n=new URL(e.url??"/",`http://${this.host}`);const i=n.pathname;t.setHeader("Content-Type","text/html; charset=utf-8");t.setHeader("Cache-Control","no-store");try{if(i==="/login"){let o;if(this.platformOidc){o=this.platformOidcAuthorizeUrl()}else{if(!this.startResult){await this.beginLogin()}o=this.startResult.authorizeUrl}t.statusCode=200;t.end(Nt(o));return}if(i===this.callbackPath||i==="/callback"){await this.handleCallback(n,t);return}if(i==="/"){t.statusCode=200;t.end('<html><body><p>Alran Code OAuth callback server.</p><p><a href="/login">Sign in</a></p></body></html>');return}t.statusCode=404;t.end("Not found")}catch(o){const s=o;t.statusCode=500;t.end(N(s.message));void this.onError?.(s);if(this.rejectLogin){this.rejectLogin(s);this.rejectLogin=null;this.resolveLogin=null}}}async handleCallback(e,t){const n=e.searchParams.get("code")??void 0;const i=e.searchParams.get("ottili_handoff")??n;const o=e.searchParams.get("state")??void 0;const s=e.searchParams.get("error")??void 0;const a=e.searchParams.get("error_description")??void 0;if(s){const d=a??s;t.statusCode=400;t.end(N(`The auth server returned an error: ${U(d)}`));const g=new l(s,d);void this.onError?.(g);if(this.rejectLogin){this.rejectLogin(g);this.rejectLogin=null;this.resolveLogin=null}return}const c=this.platformOidc?i:n;if(!c){t.statusCode=400;t.end(N("Missing authorization code or handoff code."));const d=new Error("Missing authorization code or handoff code.");void this.onError?.(d);if(this.rejectLogin){this.rejectLogin(d);this.rejectLogin=null;this.resolveLogin=null}return}if(!this.platformOidc){if(!o||o!==this.expectedState){t.statusCode=400;t.end(N("State mismatch \u2014 possible CSRF attack."));const d=new l("state_mismatch");void this.onError?.(d);if(this.rejectLogin){this.rejectLogin(d);this.rejectLogin=null;this.resolveLogin=null}return}}let u;try{if(this.platformOidc){const d=await xe({platformBaseUrl:this.platformOidc.platformBaseUrl,code:i});u={platformSession:d}}else{const d=await this.client.exchangeCodeForToken(n,this.startResult?.codeVerifier??"",this.expectedState??"",o??"");u={accessToken:d.accessToken,refreshToken:d.refreshToken,expiresInSec:d.expiresInSec,scopes:d.scopes,...d.subject?{subject:d.subject}:{},...d.accountId?{accountId:d.accountId}:{}}}}catch(d){const g=d;t.statusCode=500;t.end(N(`Failed to complete sign in: ${U(g.message)}`));void this.onError?.(g);if(this.rejectLogin){this.rejectLogin(g);this.rejectLogin=null;this.resolveLogin=null}return}try{await this.onLogin?.(u)}catch(d){const g=d;t.statusCode=500;t.end(N(`Failed to save the sign-in session: ${U(g.message)}`));void this.onError?.(g);if(this.rejectLogin){this.rejectLogin(g);this.rejectLogin=null;this.resolveLogin=null}return}t.statusCode=200;t.end(Ut());if(this.resolveLogin){this.resolveLogin(u);this.resolveLogin=null;this.rejectLogin=null}}};var Ne=class r{credentials;fetchImpl;constructor(e,t=fetch){this.credentials=e;this.fetchImpl=t}withCompany(e){return new r({...this.credentials,companyId:e},this.fetchImpl)}get baseUrl(){return this.credentials.baseUrl}async call(e){const t=new URL(e.path,this.credentials.baseUrl);if(e.query){for(const[a,c]of Object.entries(e.query)){t.searchParams.set(a,c)}}const n={"x-ottili-session":this.credentials.sessionId,"x-ottili-company":this.credentials.companyId,Accept:"application/json"};if(e.body!==void 0){n["Content-Type"]="application/json"}if(e.idempotencyKey){n["idempotency-key"]=e.idempotencyKey}let i;try{i=await this.fetchImpl(t.toString(),{method:e.method,headers:n,...e.body!==void 0?{body:JSON.stringify(e.body)}:{}})}catch(a){return{ok:false,status:0,problem:{code:"platform_unreachable",detail:a instanceof Error?a.message:String(a)}}}let o;let s;try{const a=await i.json().catch(()=>({}));const c=typeof a==="object"&&a!==null&&!Array.isArray(a)?a:{};if(i.ok&&!c.error){o=a}else{s={code:typeof c.error==="string"?c.error:typeof c.code==="string"?c.code:"platform_error",detail:typeof c.message==="string"?c.message:void 0}}}catch{if(!i.ok){s={code:`http_${i.status}`,detail:i.statusText}}}return{ok:i.ok,status:i.status,data:o,problem:s}}async get(e,t){return this.call({...t,method:"GET",path:e})}async post(e,t){return this.call({...t??{},method:"POST",path:e,body:t?.body})}async delete(e,t){return this.call({...t,method:"DELETE",path:e})}};function Zr(){return`k-${crypto.randomUUID()}`}var zt={cn:{dev:"https://account-test.example.invalid",test:"https://account-test.example.invalid",staging:"https://account-pre.example.invalid",prod:"https://api.ottili.one"},en:{dev:"https://account-overseas-test.example.invalid",test:"https://account-overseas-test.example.invalid",staging:"https://account-overseas-pre.example.invalid",prod:"https://api.ottili.one"}};function Xr(r,e){const t=[r.ALRAN_OAUTH_DEVICE_AUTHORIZATION_ENDPOINT,r.ALRAN_OAUTH_TOKEN_ENDPOINT,r.ALRAN_OAUTH_REVOCATION_ENDPOINT];if(t.every(s=>!s?.trim())){const s=zt[e.region][e.buildEnv];return{deviceAuthorizationEndpoint:`${s}/oauth2/device/code`,...Ue(e.buildEnv),tokenEndpoint:`${s}/oauth2/token`,revocationEndpoint:`${s}/oauth2/revoke`}}const n=ne(r.ALRAN_OAUTH_DEVICE_AUTHORIZATION_ENDPOINT);const i=ne(r.ALRAN_OAUTH_TOKEN_ENDPOINT);const o=ne(r.ALRAN_OAUTH_REVOCATION_ENDPOINT);if(!n||!i||!o){throw new TypeError("Shared Alran OAuth requires all three public OAuth endpoints to be configured.")}return{deviceAuthorizationEndpoint:n,...Ue(e.buildEnv),tokenEndpoint:i,revocationEndpoint:o}}function Ue(r){return r==="staging"?{deviceAuthorizationHeaders:{"X-User-Pre":"1"}}:{}}function ne(r){if(!r?.trim())return void 0;try{const e=new URL(r);if(e.protocol!=="https:"||e.username||e.password||e.hash)return void 0;return e.toString()}catch{return void 0}}var Dt=1;var Mt=1;var A=class extends Error{code="CREDENTIAL_RECORD_CORRUPT";constructor(){super("The stored OAuth credential record is invalid.");this.name="CredentialRecordCorruptError"}};var J=class extends Error{code="AUTH_CREDENTIAL_STORE_PERMISSION";constructor(){super("The OAuth credential file permissions are not private.");this.name="CredentialStorePermissionError"}};function ie(r){return r===void 0||typeof r==="string"}function oe(r){if(typeof r!=="object"||r===null||Array.isArray(r)){throw new A}const e=r;const t=e.scopes;const n=Array.isArray(t)&&t.every(o=>typeof o==="string");const i=typeof e.schemaVersion==="number"&&Number.isInteger(e.schemaVersion)&&e.schemaVersion>=Mt&&e.schemaVersion<=Dt&&typeof e.accessToken==="string"&&e.accessToken.length>0&&typeof e.refreshToken==="string"&&e.refreshToken.length>0&&e.tokenType==="Bearer"&&e.clientId===m&&n&&e.audience===y&&typeof e.expiresAtMs==="number"&&Number.isFinite(e.expiresAtMs)&&Number.isSafeInteger(e.generation)&&e.generation>=0&&ie(e.subject)&&ie(e.accountId)&&ie(e.loginEpoch);if(!i)throw new A;return e}import{randomUUID as M}from"node:crypto";import{watchFile as Bt,unwatchFile as $t}from"node:fs";import{unlink as qt}from"node:fs/promises";import{join as Fe}from"node:path";import{readFile as jt,stat as ze}from"node:fs/promises";import{join as Ht}from"node:path";var ae=1;function se(r){return`${r.service}\0${r.account}`}function De(r){if(typeof r!=="object"||r===null||Array.isArray(r)){throw new A}const e=r;if(e.schemaVersion!==ae||typeof e.records!=="object"||e.records===null||Array.isArray(e.records)){throw new A}const t=Object.fromEntries(Object.entries(e.records).map(([n,i])=>[n,oe(i)]));return{schemaVersion:ae,records:t}}var z=class{kind="file";authHome;path;constructor(e){this.authHome=e.authHome;this.path=Ht(e.authHome,"auth.json")}async get(e){const t=await this.readPayload();return t.records[se(e)]??null}async put(e,t){const n=await this.readPayload();n.records[se(e)]=oe(t);await this.writePayload(n)}async delete(e){const t=await this.readPayload();delete t.records[se(e)];await this.writePayload(t)}async healthCheck(){await j(this.authHome);await this.assertPrivatePermissions()}async readPayload(){let e;try{await this.assertPrivatePermissions();e=await jt(this.path,"utf8")}catch(t){if(t.code==="ENOENT"){return{schemaVersion:ae,records:{}}}throw t}try{return De(JSON.parse(e))}catch(t){if(t instanceof A)throw t;throw new A}}async assertPrivatePermissions(){if(process.platform==="win32")return;try{const[e,t]=await Promise.all([ze(this.authHome),ze(this.path)]);if((e.mode&63)!==0||(t.mode&63)!==0){throw new J}}catch(e){if(e.code==="ENOENT")return;throw e}}async writePayload(e){const t=De(e);await V(this.path,`${JSON.stringify(t,null,2)}
206
+ `)}};import{readFileSync as Me}from"node:fs";import{performance as Kt}from"node:perf_hooks";var Y={pid:process.pid,startedAtMs:Math.trunc(Kt.timeOrigin)};var je=5e3;function He(r){try{const e=Me(`/proc/${r}/stat`,"utf8");const t=e.slice(e.lastIndexOf(")")+2).split(" ");const n=Number(t[19]);const i=Number(/^btime (\d+)$/mu.exec(Me("/proc/stat","utf8"))?.[1]);if(!Number.isFinite(n)||!Number.isFinite(i))return void 0;return i*1e3+n/100*1e3}catch{return void 0}}var ce;function Ft(){if(ce===void 0){const r=He(process.pid);ce=r!==void 0&&Math.abs(r-Y.startedAtMs)<=je}return ce}var Vt={processStartMs(r){if(process.platform!=="linux"||!Ft())return void 0;return He(r)}};function Ke(){return{...Y}}function de(r,e=Vt){if(!r)return true;if(r.pid===Y.pid)return r.startedAtMs===Y.startedAtMs;try{process.kill(r.pid,0)}catch(n){if(n.code==="ESRCH")return false}const t=e.processStartMs(r.pid);if(t===void 0)return true;return t-r.startedAtMs<=je}var Gt=10*60*1e3;var Jt=250;var O=class extends Error{code="AUTH_REFRESH_COMMIT_PENDING";constructor(){super("OAuth refresh recovery is pending. Retry, or explicitly sign in again if recovery is unavailable.");this.name="AuthRefreshCommitPendingError"}};var f=class extends Error{code="AUTH_REQUIRED";constructor(e){super("Alran authentication is required.",e);this.name="AuthRequiredError"}};var T=class extends Error{code="AUTH_LOGIN_CANCELLED";constructor(){super("Alran OAuth device authorization was cancelled.");this.name="AuthLoginCancelledError"}};var E=class extends Error{code="AUTH_SESSION_CHANGED";constructor(){super("The login changed while this request was in progress.");this.name="AuthSessionChangedError"}};function Yt(r,e){if(!r||r!==e)throw new E}var x=class extends Error{constructor(t){super("The current Alran authorization does not include the required scope.");this.missingScopes=t;this.name="AuthScopeUpgradeRequiredError"}missingScopes;code="AUTH_SCOPE_UPGRADE_REQUIRED"};var I=class extends Error{code="AUTH_RESOURCE_CONTRACT_MISMATCH";constructor(){super("The stored credential does not match the Alran resource contract.");this.name="AuthResourceContractMismatchError"}};function Ve(r){return r instanceof f||r instanceof x||r instanceof I}var ue=class extends Error{constructor(t,n){super(`Alran is signed in to ${t.buildEnv}/${t.region}; sign out before using ${n.buildEnv}/${n.region}.`);this.active=t;this.requested=n;this.name="AuthDomainConflictError"}active;requested;code="AUTH_DOMAIN_CONFLICT"};var he=class{constructor(e){this.options=e;this.stateStore=new R(e.namespace.statePath);this.lock=new _(e.namespace.lockPath);this.refreshStore=new z({authHome:Fe(e.namespace.namespaceHome,"refresh")});this.now=e.now??Date.now;this.sleep=e.sleep??(t=>new Promise(n=>setTimeout(n,t)));this.authorizationLeaseMs=e.authorizationLeaseMs??Gt;this.statePollIntervalMs=e.statePollIntervalMs??Jt;this.createLeaseId=e.createLeaseId??M}options;stateStore;lock;now;sleep;authorizationLeaseMs;statePollIntervalMs;createLeaseId;loginPromise;loginAbortController;initializePromise;refreshStore;pendingRefresh;pendingRefreshRollback;pendingRefreshInvalidation;async getStatus(){await this.initialize();const e=await this.stateStore.read();if(!e)return{status:"anonymous",generation:0,scopes:[]};if(e.status==="authorizing"||e.status==="refreshing"||this.matchesPendingInvalidation(e)){const t=await this.recoverInterruptedCredentialCommit(e);return k(t)}if(e.status==="authenticated"||e.status==="expired"){const t=await this.options.credentialStore.get(this.options.namespace.credentialKey);if(!t||t.generation!==e.generation){return k({...e,status:"error"})}try{b(t,[...h])}catch(i){if(i instanceof x){return k({...D(t,this.options.credentialStore.kind,this.options.namespace),status:"scope_upgrade_required"})}if(i instanceof I){return k({...e,status:"error"})}throw i}const n=D(t,this.options.credentialStore.kind,this.options.namespace);if(e.status==="expired"||t.expiresAtMs<=this.now()){return k({...n,status:"expired"})}return k(n)}return k(e)}login(e={}){if(!this.loginPromise){const t=new AbortController;const n=this.initialize().then(()=>this.runLogin(e,t.signal)).finally(()=>{if(this.loginPromise!==n)return;this.loginPromise=void 0;this.loginAbortController=void 0});this.loginAbortController=t;this.loginPromise=n}return this.loginPromise}async cancelLogin(){const e=this.loginAbortController;const t=this.loginPromise;if(!e||!t)return;e.abort();try{await t}catch(n){if(!(n instanceof T))throw n}}async getAccessToken(e){await this.initialize();Xt(e.requiredScopes);try{const t=await this.readUsableCredential(e.requiredScopes);if(this.satisfiesMinValidity(t,e.minValidityMs)){return le(t.credential)}}catch(t){if(!(t instanceof f)&&!(t instanceof O))throw t}return this.lock.withLock(async()=>{const t=await this.readUsableCredential(e.requiredScopes,true);if(this.satisfiesMinValidity(t,e.minValidityMs)){return le(t.credential)}return this.refreshCredential(t)})}satisfiesMinValidity(e,t){if(e.state.status!=="authenticated")return false;const n=e.credential.expiresAtMs-this.now();return n>0&&n>=t}async handleUnauthorized(e){await this.initialize();try{return await this.lock.withLock(async()=>{const t=await this.readUsableCredential([...h],true);if(e.loginEpoch!==void 0){Yt(e.loginEpoch,t.credential.loginEpoch)}else if(t.credential.generation>e.generation){throw new E}if(t.credential.generation>e.generation)return"retry";if(t.credential.generation<e.generation)return"logout";await this.refreshCredential(t,{rejected:true});return"retry"})}catch(t){if(Ve(t))return"logout";throw t}}async commitExternalLogin(e){await this.initialize();return this.lock.withLock(async()=>{const t=await this.stateStore.read();$e(t,this.options.namespace);const n=await this.options.credentialStore.get(this.options.namespace.credentialKey);const i=Math.max(t?.generation??0,n?.generation??0);await this.stateStore.write({...S({status:"authorizing",generation:i,storeKind:this.options.credentialStore.kind},this.options.namespace),authorization:{leaseId:this.createLeaseId(),leaseExpiresAtMs:this.now()+this.authorizationLeaseMs}});await this.clearPendingRefresh();const o=i+1;const s=e({generation:o,loginEpoch:M()});if(s.generation!==o){throw new TypeError("The credential must carry the generation the core allocated.")}await this.options.credentialStore.put(this.options.namespace.credentialKey,s);await this.stateStore.write(D(s,this.options.credentialStore.kind,this.options.namespace));return{status:"authenticated",generation:o}})}async logout(e){await this.initialize();return this.lock.withLock(async()=>{const t=await this.stateStore.read();const n=await this.options.credentialStore.get(this.options.namespace.credentialKey);const i=t?.refresh&&await this.readPendingRefresh(t)||n;const o=Math.max(t?.generation??0,i?.generation??0);if(!i&&(!t||t.status==="anonymous")){return{status:"anonymous",generation:o}}const s=o+1;await this.stateStore.write({...S({status:"logging_out",generation:s,storeKind:this.options.credentialStore.kind},this.options.namespace),...t?.refresh?{refresh:t.refresh}:{}});if(e.revoke&&i){try{await this.options.oauthClient.revokeToken(i.refreshToken)}catch{await this.stateStore.write({...S({status:"logout_pending",generation:s,storeKind:this.options.credentialStore.kind},this.options.namespace),...t?.refresh?{refresh:t.refresh}:{}});return{status:"logout_pending",generation:s}}}await this.options.credentialStore.delete(this.options.namespace.credentialKey);await this.stateStore.write(S({status:"anonymous",generation:s,storeKind:this.options.credentialStore.kind},this.options.namespace));await this.clearPendingRefresh();return{status:"anonymous",generation:s}})}watch(e){let t=0;let n=0;let i=false;const o=()=>{const s=++t;void this.getStatus().then(a=>{if(i||s<n)return;n=s;e(a)}).catch(()=>void 0)};Bt(this.options.namespace.statePath,{interval:this.statePollIntervalMs},o);return()=>{i=true;$t(this.options.namespace.statePath,o)}}initialize(){this.initializePromise??=(async()=>{await this.options.initialize?.();await this.options.credentialStore.healthCheck()})().catch(e=>{this.initializePromise=void 0;throw e});return this.initializePromise}async runLogin(e,t){while(true){C(t);const n=this.createLeaseId();const i=await this.lock.withLock(async()=>{let o=await this.stateStore.read();$e(o,this.options.namespace);if(o?.status==="refreshing"&&o.refresh){try{o=await this.resumeRefreshCommit(o)}catch(c){if(!(c instanceof O)&&!(c instanceof f))throw c}}const s=await this.options.credentialStore.get(this.options.namespace.credentialKey);if(o&&s&&o.generation===s.generation&&(o.status==="authenticated"||o.status==="expired"||o.status==="refreshing")){try{b(s,[...h]);if(o.status==="authenticated"&&s.expiresAtMs>this.now()){return{kind:"authenticated",generation:s.generation}}return{kind:"refresh",generation:s.generation}}catch(c){if(!(c instanceof x)&&!(c instanceof I)){throw c}}}if(o?.status==="authorizing"&&o.authorization&&o.authorization.leaseExpiresAtMs>this.now()){return{kind:"wait",leaseExpiresAtMs:o.authorization.leaseExpiresAtMs}}const a=Math.max(o?.generation??0,s?.generation??0);await this.stateStore.write({...S({status:"authorizing",generation:a,storeKind:this.options.credentialStore.kind},this.options.namespace),authorization:{leaseId:n,leaseExpiresAtMs:this.now()+this.authorizationLeaseMs}});await this.clearPendingRefresh();return{kind:"owner"}});if(i.kind==="authenticated"){return{status:"authenticated",generation:i.generation}}if(i.kind==="refresh"){try{await this.lock.withLock(async()=>{const s=await this.readUsableCredential([...h],true);if(s.credential.generation>i.generation&&this.satisfiesMinValidity(s,1))return;await this.refreshCredential(s)})}catch(s){if(Ve(s))continue;throw s}const o=await this.stateStore.read();if(o?.status==="authenticated"){return{status:"authenticated",generation:o.generation}}continue}if(i.kind==="wait"){const o=await this.waitForAuthorization(i.leaseExpiresAtMs,e.onDeviceAuthorization,t);if(o)return o;continue}try{const o=await this.options.oauthClient.startDeviceAuthorization({signal:t});await this.publishAuthorizationProgress(n,o);e.onDeviceAuthorization?.(Qt(o));const s=await this.options.oauthClient.pollDeviceToken(o,{signal:t});return await this.commitLogin(n,s,t)}catch(o){const s=t.aborted;await this.releaseAuthorizationLease(n,s?"anonymous":"error");if(s)throw new T;throw o}}}async commitLogin(e,t,n){return this.lock.withLock(async()=>{C(n);const i=await this.stateStore.read();if(i?.status!=="authorizing"||i.authorization?.leaseId!==e){throw new f}const o=await this.options.credentialStore.get(this.options.namespace.credentialKey);C(n);const s=Math.max(i.generation,o?.generation??0)+1;const a=Be(t,s,this.now(),M());await this.options.credentialStore.put(this.options.namespace.credentialKey,a);try{C(n);await this.stateStore.write(D(a,this.options.credentialStore.kind,this.options.namespace));C(n)}catch(c){if(c instanceof T){await this.stateStore.write(i);if(o){await this.options.credentialStore.put(this.options.namespace.credentialKey,o)}else{await this.options.credentialStore.delete(this.options.namespace.credentialKey)}}throw c}return{status:"authenticated",generation:s}})}async waitForAuthorization(e,t,n){let i=false;while(this.now()<e){C(n);const o=await this.stateStore.read();if(!i&&o?.status==="authorizing"&&o.authorization?.userCode&&o.authorization.verificationUri){t?.({userCode:o.authorization.userCode,verificationUri:o.authorization.verificationUri,...o.authorization.verificationUriComplete?{verificationUriComplete:o.authorization.verificationUriComplete}:{},expiresInSec:Math.max(1,Math.ceil((o.authorization.leaseExpiresAtMs-this.now())/1e3))});i=true}if(o?.status==="authenticated"){const s=await this.options.credentialStore.get(this.options.namespace.credentialKey);if(s&&s.generation===o.generation){b(s,[...h]);return{status:"authenticated",generation:o.generation}}}if(o?.status!=="authorizing")return void 0;await Zt(this.sleep,this.statePollIntervalMs,n)}return void 0}async publishAuthorizationProgress(e,t){await this.lock.withLock(async()=>{const n=await this.stateStore.read();if(n?.status!=="authorizing"||n.authorization?.leaseId!==e){throw new f}await this.stateStore.write({...n,authorization:{...n.authorization,userCode:t.userCode,verificationUri:t.verificationUri,...t.verificationUriComplete?{verificationUriComplete:t.verificationUriComplete}:{}}})})}async releaseAuthorizationLease(e,t){await this.lock.withLock(async()=>{const n=await this.stateStore.read();if(n?.status!=="authorizing"||n.authorization?.leaseId!==e)return;await this.stateStore.write(S({status:t,generation:n.generation,storeKind:this.options.credentialStore.kind},this.options.namespace))})}async recoverInterruptedCredentialCommit(e){if(this.matchesPendingInvalidation(e)){return this.lock.withLock(async()=>{const n=await this.stateStore.read();const i=this.pendingRefreshInvalidation;if(!n||!i||!this.matchesPendingInvalidation(n))return n??e;return this.observeRefreshInvalidation(i)})}if(e.status==="refreshing"&&e.refresh){const n=await this.options.credentialStore.get(this.options.namespace.credentialKey);if(n?.generation!==e.generation&&!await this.readPendingRefresh(e)&&this.pendingRefreshRollback?.id!==e.refresh.id&&de(e.refresh.owner)){return e}return this.lock.withLock(async()=>{const i=await this.stateStore.read();if(i?.status!=="refreshing"||!i.refresh)return i??e;try{return await this.resumeRefreshCommit(i)}catch(o){if(o instanceof f&&this.matchesPendingInvalidation(i)){return this.refreshInvalidatedState(i)}throw o}})}const t=await this.options.credentialStore.get(this.options.namespace.credentialKey);if(!t||t.generation<=e.generation){return e}b(t,[...h]);return this.lock.withLock(async()=>{const n=await this.stateStore.read();const i=await this.options.credentialStore.get(this.options.namespace.credentialKey);if(!n||!i||n.status!=="authorizing"&&n.status!=="refreshing"||i.generation<=n.generation){return n??e}b(i,[...h]);const o=D(i,this.options.credentialStore.kind,this.options.namespace);await this.stateStore.write(o);return o})}async readUsableCredential(e,t=false){let n=await this.stateStore.read();const i=this.pendingRefreshInvalidation;if(n&&i&&this.matchesPendingInvalidation(n)){if(t)await this.finishRefreshInvalidation(i);throw new f}if(!n||n.status!=="authenticated"&&n.status!=="expired"&&n.status!=="refreshing"){throw new f}let o=await this.options.credentialStore.get(this.options.namespace.credentialKey);if(n.status==="refreshing"&&n.refresh){if(!t)throw new O;n=await this.resumeRefreshCommit(n);if(n.status==="anonymous")throw new f;o=await this.options.credentialStore.get(this.options.namespace.credentialKey)}if(!o||n.generation!==o.generation)throw new f;b(o,e);return{state:n,credential:o}}async refreshCredential(e,t={}){const n=M();const i={...e.state,status:"refreshing",generation:Math.max(e.state.generation,e.credential.generation)+1,refresh:{id:n,owner:Ke()}};await this.persistRefresh(i,"prepare_refresh","auth-state.json",null,()=>this.stateStore.write(i));let o;try{o=await this.options.oauthClient.refreshToken(e.credential.refreshToken);L({phase:"refresh_response",file:"oauth",correlationId:n,generation:i.generation,refreshResponseSucceeded:true},this.options.onDiagnostic,"success")}catch(a){L({phase:"refresh_response",file:"oauth",correlationId:n,generation:i.generation,refreshResponseSucceeded:false},this.options.onDiagnostic,"failure",a);if(Wt(a)){this.pendingRefreshInvalidation={state:i,refreshResponseSucceeded:false};await this.finishRefreshInvalidation(this.pendingRefreshInvalidation);throw new f({cause:a})}else{const c=!t.rejected&&e.state.status==="authenticated"&&e.credential.expiresAtMs>this.now();this.pendingRefreshRollback={id:n,state:{...e.state,status:c?"authenticated":"expired"}};await this.resumeRefreshCommit(i)}throw a}const s=Be(o,i.generation,this.now(),e.credential.loginEpoch);this.pendingRefresh={id:n,credential:s};await this.resumeRefreshCommit(i);return le(s)}async readPendingRefresh(e){if(!e.refresh)return null;return this.pendingRefresh?.id===e.refresh.id?this.pendingRefresh.credential:this.refreshStore.get({...this.options.namespace.credentialKey,account:e.refresh.id})}async resumeRefreshCommit(e){const t=e.refresh?.id;if(!t)throw new O;await this.assertRefreshCurrent(e);const n=this.pendingRefreshInvalidation;if(n?.state.refresh?.id===t){return this.finishRefreshInvalidation(n)}const i=this.pendingRefreshRollback;if(i?.id===t){await this.persistRefresh(e,"restore_state","auth-state.json",false,()=>this.stateStore.write(i.state));this.pendingRefreshRollback=void 0;return i.state}const o=await this.options.credentialStore.get(this.options.namespace.credentialKey);const s=o?.generation===e.generation?o:await this.readPendingRefresh(e);if(!s||s.generation!==e.generation){if(!de(e.refresh?.owner)){this.pendingRefreshInvalidation={state:e,refreshResponseSucceeded:null};return this.finishRefreshInvalidation(this.pendingRefreshInvalidation)}throw new O}b(s,[...h]);if(o?.generation!==e.generation){this.pendingRefresh={id:t,credential:s};const c={...this.options.namespace.credentialKey,account:t};const u=await this.refreshStore.get(c);if(u?.generation!==s.generation||u.accessToken!==s.accessToken||u.refreshToken!==s.refreshToken||u.loginEpoch!==s.loginEpoch){await this.persistRefresh(e,"stage_credentials","refresh/auth.json",true,()=>this.refreshStore.put(c,s))}await this.assertRefreshCurrent(e);await this.persistRefresh(e,"commit_credentials","auth.json",true,()=>this.options.credentialStore.put(this.options.namespace.credentialKey,s))}const a=D(s,this.options.credentialStore.kind,this.options.namespace);await this.assertRefreshCurrent(e);await this.persistRefresh(e,"commit_state","auth-state.json",true,()=>this.stateStore.write(a));await this.clearPendingRefresh();return a}refreshInvalidatedState(e){return S({status:"anonymous",generation:e.generation,storeKind:this.options.credentialStore.kind},this.options.namespace)}matchesPendingInvalidation(e){const t=this.pendingRefreshInvalidation?.state;return t!==void 0&&e.generation===t.generation&&(e.status==="anonymous"||e.status==="refreshing"&&e.refresh?.id===t.refresh?.id)}async finishRefreshInvalidation(e){const{state:t,refreshResponseSucceeded:n}=e;const i=this.refreshInvalidatedState(t);try{const o=await this.stateStore.read();if(!o||!this.matchesPendingInvalidation(o))throw new E;if(o.status!=="anonymous"){await this.persistRefresh(t,"invalidate_state","auth-state.json",n,()=>this.stateStore.write(i))}const s=await this.stateStore.read();if(s?.status!=="anonymous"||s.generation!==t.generation){throw new E}await this.persistRefresh(t,"delete_credentials","auth.json",n,()=>this.options.credentialStore.delete(this.options.namespace.credentialKey))}catch(o){if(o instanceof E)throw o;throw new f({cause:o})}await this.clearPendingRefresh();return i}async observeRefreshInvalidation(e){try{return await this.finishRefreshInvalidation(e)}catch(t){if(t instanceof f)return this.refreshInvalidatedState(e.state);throw t}}persistRefresh(e,t,n,i,o){return Se({phase:t,file:n,correlationId:e.refresh?.id??M(),generation:e.generation,refreshResponseSucceeded:i},this.options.onDiagnostic,o)}async assertRefreshCurrent(e){const t=await this.stateStore.read();if(t?.status!=="refreshing"||t.generation!==e.generation||t.refresh?.id!==e.refresh?.id){throw new E}}async clearPendingRefresh(){this.pendingRefresh=void 0;this.pendingRefreshRollback=void 0;this.pendingRefreshInvalidation=void 0;await qt(Fe(this.options.namespace.namespaceHome,"refresh","auth.json")).catch(()=>void 0)}};function C(r){if(r?.aborted)throw new T}function Wt(r){return r instanceof l&&r.code==="invalid_grant"&&r.httpStatus===400}async function Zt(r,e,t){if(!t){await r(e);return}C(t);let n;const i=()=>n(new T);const o=new Promise((s,a)=>{n=a});t.addEventListener("abort",i,{once:true});try{await Promise.race([r(e),o])}finally{t.removeEventListener("abort",i)}}function Qt(r){return{userCode:r.userCode,verificationUri:r.verificationUri,...r.verificationUriComplete?{verificationUriComplete:r.verificationUriComplete}:{},expiresInSec:r.expiresInSec}}function S(r,e){return{schemaVersion:P,status:r.status,storeKind:r.storeKind,clientId:m,scopes:[...h],audience:y,buildEnv:e.buildEnv,region:e.region,generation:r.generation}}function D(r,e,t){return{...S({status:"authenticated",generation:r.generation,storeKind:e},t),scopes:r.scopes,expiresAtMs:r.expiresAtMs}}function Be(r,e,t,n=M()){const i={schemaVersion:1,accessToken:r.accessToken,refreshToken:r.refreshToken,tokenType:r.tokenType,clientId:m,scopes:r.scopes,audience:y,expiresAtMs:t+r.expiresInSec*1e3,generation:e,loginEpoch:n,...r.subject?{subject:r.subject}:{},...r.accountId?{accountId:r.accountId}:{}};b(i,[...h]);if(r.audience!==y)throw new I;return i}function Xt(r){const e=r.filter(t=>!h.includes(t));if(e.length>0)throw new x(e)}function b(r,e){if(r.clientId!==m||r.audience!==y||r.tokenType!=="Bearer"){throw new I}const t=e.filter(n=>!r.scopes.includes(n));if(t.length>0)throw new x(t)}function k(r){return{status:r.status,generation:r.generation,scopes:r.scopes,...r.buildEnv===void 0?{}:{buildEnv:r.buildEnv},...r.region===void 0?{}:{region:r.region},...r.expiresAtMs===void 0?{}:{expiresAtMs:r.expiresAtMs}}}function $e(r,e){if(!r||r.status==="anonymous"||r.buildEnv===void 0||r.region===void 0||r.buildEnv===e.buildEnv&&r.region===e.region){return}throw new ue({buildEnv:r.buildEnv,region:r.region},{buildEnv:e.buildEnv,region:e.region})}function le(r){return{accessToken:r.accessToken,...r.loginEpoch?{loginEpoch:r.loginEpoch}:{},expiresAtMs:r.expiresAtMs,generation:r.generation,scopes:h,audience:y}}function er(r){return new z(r)}import nr from"node:fs";import H from"node:fs";import qe from"node:path";var Ge="preferences";var tr="alran-region.json";function Je(r,e){try{const t=JSON.parse(H.readFileSync(Ye(r),"utf8"));if(t.version!==1||!t.regions||typeof t.regions!=="object"){return void 0}const n=t.regions[e];return n==="cn"||n==="en"?n:void 0}catch{return void 0}}function oi(r,e){const t=qe.join(r,Ge);H.mkdirSync(t,{recursive:true,mode:448});const n=Ye(r);const i=rr(n);const o={version:1,regions:{...i,[e.buildEnv]:e.region},updatedAtMs:Date.now()};const s=`${n}.${process.pid}.${Date.now()}.tmp`;H.writeFileSync(s,`${JSON.stringify(o,null,2)}
207
+ `,{encoding:"utf8",mode:384});H.renameSync(s,n);return n}function Ye(r){return qe.join(r,Ge,tr)}function rr(r){try{const e=JSON.parse(H.readFileSync(r,"utf8"));if(e.version!==1||!e.regions||typeof e.regions!=="object")return{};return Object.fromEntries(Object.entries(e.regions).filter(([t,n])=>(t==="dev"||t==="test"||t==="staging"||t==="prod")&&(n==="cn"||n==="en")))}catch{return{}}}var ir=/^[A-Za-z0-9._-]+$/u;var pe="--env";var or=new Set(["--lane","--resume","--tui-mode","-m","--model","--system-prompt","--system-prompt-file","--append-system-prompt","--append-system-prompt-file"]);var sr=Object.freeze({test:"test",pre:"staging",staging:"staging",prod:"prod"});function hi(r={}){fe(false);me(false);const{target:e=process.env,dataDir:t,startupBuildEnvironment:n,...i}=r;if(n)ge(n);const o=K(i);const s=t?Je(t,o.buildEnv):void 0;const a=t?cr(t,o.buildEnv):void 0;const c=lr(e.ALRAN_REGION);const u=K({...i,runtimeRegion:i.runtimeRegion??c??s??a?.region??"en"});if(t){e.ALRAN_DATA_DIR=t;e.ALRAN_DATA_DIR=t}e.ALRAN_REGION=u.region;e.ALRAN_BUILD_ENV=u.buildEnv;e.__ALRAN_RUNTIME_MANAGED="1";return u}function ar(r){const e=sr[r.trim()];if(!e){throw new Error("--env must be test, staging, pre, or prod.")}return e}function pi(r,e){const t=[];for(let n=0;n<r.length;n+=1){const i=r[n];if(i===void 0)continue;if(i==="--")break;if(i===pe){const o=r[n+1];if(!o||o.startsWith("-"))throw new Error("--env requires a value.");t.push(o);n+=1;continue}if(i.startsWith(`${pe}=`)){t.push(i.slice(pe.length+1));continue}if(or.has(i)){n+=1;continue}if(i==="--session"&&r[n+1]&&!r[n+1]?.startsWith("-")){n+=1;continue}if(!i.startsWith("-"))break}if(t.length===0)return void 0;if(!e){throw new Error("--env is only available in the internal Alran package.")}if(t.length>1)throw new Error("--env may only be specified once.");return ar(t[0]??"")}function fi(r,e=K().buildEnv){if(r===void 0)return void 0;if(e!=="test"&&e!=="staging"){throw new Error("--lane is only supported in test or staging builds.")}const t=r.trim();if(!ir.test(t)){throw new Error("--lane only accepts letters, numbers, dot, underscore, and hyphen.")}return t}function cr(r,e){const t=["cn","en"].filter(i=>{try{const o=X({dataDir:r,buildEnv:e,region:i});const s=JSON.parse(nr.readFileSync(o.statePath,"utf8"));return s.buildEnv===e&&s.region===i&&dr(s.status)}catch{return false}});const n=t.length===1?t[0]:void 0;return n?{buildEnv:e,region:n}:void 0}function dr(r){return r==="authorizing"||r==="authenticated"||r==="refreshing"||r==="scope_upgrade_required"||r==="expired"}function lr(r){return r==="cn"||r==="en"?r:void 0}export{h as a,Ae as b,Z as c,Q as d,ur as e,hr as f,pr as g,we as h,X as i,wt as j,re as k,Ce as l,Le as m,Ne as n,Zr as o,Xr as p,Dt as q,E as r,Ve as s,he as t,er as u,oi as v,hi as w,ar as x,pi as y,fi as z};
@@ -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{la as d}from"./chunk-FXOH6TEQ.js";import{e as r}from"./chunk-XFCC2CI2.js";var i;function A(n){i=n}function v(n={}){const e=n.embeddedBuildEnvironment??l();const o=n.embeddedBuildVariant??B();const a=n.runtimeBuildEnv??d();const t=n.runtimeBuildEnv??E();return r({buildEnv:t?u(t):e??u(a),internalBuild:o==="internal"})}function f(n={}){const e=v(n);return{region:n.runtimeRegion??"en",buildEnv:i??e.buildEnv??"test"}}function c(n=l()){return i??n??"dev"}function l(){if(false)return void 0;return"prod"}function B(){if(false)return void 0;return"standard"}function u(n){return n==="dev"?"test":n}function E(){const n=process.env.ALRAN_BUILD_ENV;return n==="test"||n==="prod"||n==="dev"||n==="staging"?n:void 0}export{A as a,v as b,f as c,c as d};
2
+ import{ma as d}from"./chunk-XVGPB7TW.js";import{e as r}from"./chunk-VUISZDXX.js";var i;function A(n){i=n}function v(n={}){const e=n.embeddedBuildEnvironment??l();const o=n.embeddedBuildVariant??B();const a=n.runtimeBuildEnv??d();const t=n.runtimeBuildEnv??E();return r({buildEnv:t?u(t):e??u(a),internalBuild:o==="internal"})}function f(n={}){const e=v(n);return{region:n.runtimeRegion??"en",buildEnv:i??e.buildEnv??"test"}}function c(n=l()){return i??n??"dev"}function l(){if(false)return void 0;return"prod"}function B(){if(false)return void 0;return"standard"}function u(n){return n==="dev"?"test":n}function E(){const n=process.env.ALRAN_BUILD_ENV;return n==="test"||n==="prod"||n==="dev"||n==="staging"?n:void 0}export{A as a,v as b,f as c,c as d};
@@ -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 X}from"./chunk-7QLAXRD2.js";import{b as g}from"./chunk-MACBL5HF.js";import{L as $,U as A}from"./chunk-XFCC2CI2.js";import{e as I}from"./chunk-XQK7JM66.js";import{execFile as F}from"node:child_process";import{platform as O,release as W}from"node:os";import{posix as M}from"node:path";import{promisify as V}from"node:util";var j=V(F);async function he(e,n){if(!/^(?:[a-z]:[\\/]|\\\\)/iu.test(e)||O()!=="linux"||!(process.env.WSL_DISTRO_NAME||process.env.WSL_INTEROP||process.env.WSLENV||/microsoft/iu.test(W()))){return e}try{const{stdout:t}=await j("wslpath",["-a","-u",e],{encoding:"utf8",timeout:1e3,maxBuffer:64*1024,...n?{signal:n}:{}});const r=t.replace(/\r?\n$/u,"");if(!M.isAbsolute(r)||/[\r\n\0]/u.test(r)){throw new Error("wslpath did not return an absolute Linux path.")}return r}catch(t){throw new Error("Could not convert the Windows path with wslpath. Use an accessible Linux path instead.",{cause:t})}}var _=I(X(),1);var q=1e6;var z=1e3;var B=32;var v=/^(?![A-Za-z]:[\\/])(?![\\/])(?!.*(?:^|[\\/])\.\.(?:[\\/]|$))[^\0]+$/u;var L=/^sha256:[a-f0-9]{64}$/u;var G=/^git-blob:[a-f0-9]{40,64}$/u;function be(e){if(!E(e))return void 0;const n=e.reviewOutcome;return n==="pass"||n==="needs_changes"||n==="failed"?n:void 0}function xe(e){const n=e.trim();if(!n.startsWith("<annotation-result")||!n.endsWith("</annotation-result>")){return void 0}try{const t=K(n);R(t,"annotation-result");m(t,["version","source","review-run-id","trigger","mode","verdict"]);if(c(t,"version")!=="2"||c(t,"source")!=="code-review"||c(t,"verdict")!=="needs-changes"||!c(t,"review-run-id")){return void 0}const r=c(t,"trigger");const i=c(t,"mode");if(r!=="slash"&&r!=="natural_language"||i!=="inline"&&i!=="subagent"){return void 0}h(t);T(t,["summary","annotations"]);const s=x(f(t,"summary"));const o=f(t,"annotations");m(o,[]);h(o);if(o.children.some(l=>l.name!=="annotation"))return void 0;const u=o.children.map(U);if(!s||u.length===0)return void 0;return{schemaVersion:1,type:"review.result",scope:"local_changes",verdict:"needs_changes",summary:s,findings:u,mode:i}}catch{return void 0}}function ve(e){const n=e.trim();if(!n)return void 0;return{schemaVersion:1,type:"review.result",scope:"local_changes",verdict:"pass",summary:n,findings:[]}}function Re(e){if(!E(e)||e.schemaVersion!==1||e.type!=="review.result"){return false}if(e.scope!=="local_changes"||e.verdict!=="pass"&&e.verdict!=="needs_changes"||typeof e.summary!=="string"||!e.summary.trim()||!Array.isArray(e.findings)||!e.findings.every(Y)||e.mode!==void 0&&e.mode!=="inline"&&e.mode!=="subagent"){return false}return e.verdict==="pass"?e.findings.length===0:e.findings.length>0}function Te(e){if(e.verdict==="pass")return g(e.summary);return[g(e.summary),...e.findings.flatMap(n=>["",`[${n.priority}] ${g(n.title)}`,g(H(n)),g(n.content)])].join("\n")}function H(e){if(e.targetType==="file")return e.path;const n=e.startLine===e.endLine?String(e.startLine):`${String(e.startLine)}-${String(e.endLine)}`;return`${e.path}:${n}${e.side?` (${e.side})`:""}`}function U(e){R(e,"annotation");m(e,["id","kind","priority"]);if(c(e,"kind")!=="code-review"){throw new Error("annotation kind must be code-review")}const n=c(e,"id");const t=c(e,"priority");if(!n||!S(t))throw new Error("annotation identity is invalid");h(e);T(e,["target","title","content"]);const r=Z(f(e,"target"));const i=x(f(e,"title"));const s=x(f(e,"content"));if(!i||!s)throw new Error("annotation text is empty");return{id:n,priority:t,...r,title:i,content:s}}function Z(e){R(e,"target");const n=c(e,"uri");if(!v.test(n)||c(e,"type")!=="file"){throw new Error("annotation target is invalid")}h(e);if(e.attributes.state==="deleted"){m(e,["type","uri","state","blob-revision"]);if(e.children.length>0||!G.test(c(e,"blob-revision"))){throw new Error("deleted annotation target is invalid")}return{targetType:"file",path:n}}m(e,["type","uri"]);T(e,["selector","related-change"]);const t=f(e,"selector");m(t,["type","side","start-line","end-line","anchor-revision","context-before","context-after"]);h(t);if(t.children.length>0||c(t,"type")!=="line-range"){throw new Error("annotation selector is invalid")}const r=c(t,"side");const i=y(c(t,"start-line"));const s=y(c(t,"end-line"));const o=t.attributes["anchor-revision"];if(r!=="old"&&r!=="new"||s<i||o!==void 0&&!L.test(o)||!k(t.attributes["context-before"])||!k(t.attributes["context-after"])){throw new Error("annotation selector is invalid")}const u=Q(e,"related-change");if(u)J(u);return{targetType:"line-range",path:n,side:r,startLine:i,endLine:s}}function J(e){m(e,["path","side","start-line","end-line","revision"]);h(e);const n=c(e,"path");const t=c(e,"side");const r=y(c(e,"start-line"));const i=y(c(e,"end-line"));if(e.children.length>0||!v.test(n)||t!=="old"&&t!=="new"||i<r||!L.test(c(e,"revision"))){throw new Error("related change is invalid")}}function K(e){if(e.length>q)throw new Error("Review result is too large");let n;let t=false;let r=0;let i="";const s=[];const o=new _.SaxesParser({xmlns:false});o.on("opentag",u=>{r+=1;if(r>z||s.length>=B)t=true;const l={name:u.name,attributes:Object.fromEntries(Object.entries(u.attributes).map(([a,p])=>[a,String(p)])),children:[],text:""};const d=s.at(-1);if(d)d.children.push(l);else if(n)t=true;else n=l;s.push(l)});o.on("text",u=>{const l=s.at(-1);if(l)l.text+=u;else i+=u});o.on("closetag",()=>{s.pop()});o.on("cdata",()=>{t=true});o.on("comment",()=>{t=true});o.on("doctype",()=>{t=true});o.on("processinginstruction",()=>{t=true});o.on("error",()=>{t=true});o.write(e).close();if(t||!n||s.length>0||i.trim()){throw new Error("Review result XML is invalid")}return n}function x(e){m(e,[]);if(e.children.length>0)throw new Error(`${e.name} must contain text only`);return e.text.trim()}function R(e,n){if(e.name!==n)throw new Error(`Expected ${n}`)}function m(e,n){const t=[...n].sort().join("\0");const r=Object.keys(e.attributes).sort().join("\0");if(r!==t)throw new Error(`${e.name} attributes are invalid`)}function h(e){if(e.text.trim())throw new Error(`${e.name} contains unexpected text`)}function T(e,n){const t=new Set(n);if(e.children.some(r=>!t.has(r.name))){throw new Error(`${e.name} contains an unexpected element`)}}function f(e,n){const t=e.children.filter(i=>i.name===n);const r=t[0];if(t.length!==1||!r){throw new Error(`${e.name} must contain one ${n}`)}return r}function Q(e,n){const t=e.children.filter(r=>r.name===n);if(t.length>1)throw new Error(`${e.name} contains duplicate ${n}`);return t[0]}function c(e,n){const t=e.attributes[n];if(t===void 0)throw new Error(`${e.name}.${n} is required`);return t}function y(e){if(!/^[1-9]\d*$/u.test(e))throw new Error("Expected a positive integer");const n=Number(e);if(!Number.isSafeInteger(n))throw new Error("Integer is out of range");return n}function k(e){return e===void 0||/^[0-3]$/u.test(e)}function S(e){return e==="P0"||e==="P1"||e==="P2"||e==="P3"}function Y(e){if(!E(e))return false;if(typeof e.id!=="string"||!e.id||typeof e.priority!=="string"||!S(e.priority)||typeof e.path!=="string"||!v.test(e.path)||typeof e.title!=="string"||!e.title.trim()||typeof e.content!=="string"||!e.content.trim()){return false}if(e.targetType==="file"){return e.side===void 0&&e.startLine===void 0&&e.endLine===void 0}return e.targetType==="line-range"&&(e.side==="old"||e.side==="new")&&typeof e.startLine==="number"&&Number.isSafeInteger(e.startLine)&&e.startLine>0&&typeof e.endLine==="number"&&Number.isSafeInteger(e.endLine)&&e.endLine>=e.startLine}function E(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var N=/<(?:deliver[-_]assets|media|publish[_-]artifact|preview_card|genui-|alran-widget|alran-thinking|alran-progress|think|final|permission-(?:ask|response)|questionnaire-(?:ask|response))\b|^\s*preview_cards?:\s*$/imu;function ke(e){const n=ee(e);if(n.assets.length===0)return n.text;return[n.text,ue(n.assets)].filter(Boolean).join("\n\n")}function ee(e){const n=g(e);if(!n||!N.test(n))return{text:n,assets:[]};const t=$(n);const r=[];const i=[];let s="\uE000alran-protected";while(n.includes(s))s+="-";let o=false;const u=t.map(a=>{if(a.type==="protected"){const p=r.push(a.content)-1;return`${s}-${p}\uE001`}if(!N.test(a.content)){return a.content}o=true;return te(a.content,i)}).join("");if(!o)return{text:n,assets:[]};let l=de(u);r.forEach((a,p)=>{l=l.replace(`${s}-${p}\uE001`,a)});const d=[...new Map(i.map(a=>[a.path.trim(),a])).values()];return{text:l,assets:d.map(a=>({path:a.path.trim(),...a.name?.trim()?{name:a.name.trim()}:{}}))}}function te(e,n){let t=e;t=w(t,"alran-thinking");t=w(t,"think");t=ne(t,"alran-progress");t=w(t,"permission-ask");t=w(t,"permission-response");t=w(t,"questionnaire-ask");t=w(t,"questionnaire-response");t=t.replace(/<\/?final\b[^>]*>/giu,"");t=re(t);t=ie(t);t=se(t);t=ae(t);t=ce(t,n);t=t.replace(/<\/?(?:deliver-assets|deliver_assets)\b[^>]*>/giu,"file attachment").replace(/<media\b[^>]*\/?>/giu,"file attachment").replace(/<media\b[^>]*$/iu,"");return t}function w(e,n){const t=new RegExp(`<${n}\\b[^>]*>((?:(?!<${n}\\b)[\\s\\S])*?)<\\/${n}\\s*>`,"giu");let r=e;let i=e.replace(t,"");while(i!==r){r=i;i=i.replace(t,"")}return i}function ne(e,n){const t=new RegExp(`<${n}\\b[^>]*>((?:(?!<${n}\\b)[\\s\\S])*?)<\\/${n}\\s*>`,"giu");let r=e;let i=e.replace(t,(s,o)=>o.trim());while(i!==r){r=i;i=i.replace(t,(s,o)=>o.trim())}return i}function re(e){const n=/<alran-widget\b([^>]*)>([\s\S]*?)<\/alran-widget\s*>/giu;let t=e.replace(n,(r,i,s)=>{const o=/<alran-fallback\b[^>]*>([\s\S]*?)<\/alran-fallback\s*>/iu.exec(s)?.[1];if(o?.trim())return o.trim();return P(b(i))});t=t.replace(/<alran-widget\b([^>]*)>[\s\S]*$/iu,(r,i)=>P(b(i)));return t.replace(/<alran-widget\b[^>]*$/iu,"Interactive content is loading\u2026")}function P(e){const n=e["kind"]?.trim();const t=e["title"]?.trim();if(n&&t)return`Interactive ${n}: ${t} (open in Desktop).`;if(t)return`Interactive content: ${t} (open in Desktop).`;return"Interactive content available in Desktop."}function ie(e){const n=/<genui-([\w-]+)\b([^>]*)>[\s\S]*?<\/genui-\1\s*>/giu;const t=/<genui-([\w-]+)\b([^>]*?)\/\s*>/giu;let r=e.replace(n,(i,s,o)=>C(s,b(o)));r=r.replace(t,(i,s,o)=>C(s,b(o)));return r.replace(/<genui-[\w-]*\b[^>]*$/iu,"Interactive content is loading\u2026")}function C(e,n){if(e.toLocaleLowerCase()==="mcp-auth"){const t=n["label"]?.trim()||n["server-id"]?.trim();return t?`MCP authorization required: ${t} (open in Desktop).`:"MCP authorization required (open in Desktop)."}if(e.toLocaleLowerCase()==="agent-team-recommendation"){const t=n["status"]?.trim().toLocaleLowerCase();if(t==="accepted")return"Team recommendation accepted.";if(t==="skipped")return"Team recommendation skipped.";return"Team recommendation available in Desktop."}return"Interactive content available in Desktop."}function b(e){const n={};const t=/([\w-]+)\s*=\s*(["'])(.*?)\2/gu;let r;while((r=t.exec(e))!==null){const i=r[1];const s=r[3];if(i&&s!==void 0)n[i]=oe(s)}return n}function se(e){const n=/<(deliver-assets|deliver_assets)\b[^>]*>\s*<\/\1\s*>/giu;let t=e;let r=e.replace(n,"");while(r!==t){t=r;r=r.replace(n,"")}return r}function oe(e){return e.replace(/&quot;/gu,'"').replace(/&apos;|&#39;/gu,"'").replace(/&lt;/gu,"<").replace(/&gt;/gu,">").replace(/&amp;/gu,"&")}function ae(e){const n=/<\/?(deliver-assets|deliver_assets)\b[^>]*>/giu;const t=[];let r;while((r=n.exec(e))!==null){t.push({start:r.index,end:n.lastIndex,name:r[1]?.toLocaleLowerCase()??"",closing:r[0].startsWith("</")})}if(t.length===0)return e;const i=[];const s=new Set;t.forEach((l,d)=>{if(!l.closing){i.push(d);return}for(let a=i.length-1;a>=0;a-=1){const p=i[a];if(p===void 0||t[p]?.name!==l.name)continue;i.splice(a,1);s.add(p);s.add(d);return}});if(s.size===t.length)return e;let o=0;let u="";t.forEach((l,d)=>{u+=e.slice(o,l.start);u+=s.has(d)?e.slice(l.start,l.end):"file attachment";o=l.end});return u+e.slice(o)}function ce(e,n){let t=e;for(let r=0;r<3;r+=1){const i=A(t);const s=le(i);t=s.text;if(s.assets.length===0)break;n.push(...s.assets)}return t}function le(e){const n=[];const t=[];for(const r of e){if(r.type==="deliver-assets"||r.type==="image-gallery"){t.push(...r.items)}else if(r.content.trim()){n.push(r.content.trim())}}return{text:n.join("\n\n"),assets:t}}function ue(e){const n=e[0];if(!n)return"";if(e.length===1)return`File: ${D(n)}`;return["Files:",...e.map(t=>`- ${D(t)}`)].join("\n")}function D(e){const n=e.path.trim();const t=e.name?.trim();const r=n.split(/[\\/]/u).filter(Boolean).at(-1);if(!t||t===n||t===r)return n;const i=n?t.indexOf(n):-1;if(i>=0){return t.slice(0,i+n.length).trimEnd()}return`${t} \xB7 ${n}`}function de(e){return e.replace(/[^\S\r\n]+$/gmu,"").replace(/(?:\r?\n[\t ]*){3,}/gu,"\n\n").trim()}export{he as a,ke as b,ee as c,be as d,xe as e,ve as f,Re as g,Te as h};
2
+ import{b as X}from"./chunk-MPQ6G7LH.js";import{b as g}from"./chunk-MACBL5HF.js";import{L as $,U as A}from"./chunk-VUISZDXX.js";import{e as I}from"./chunk-XQK7JM66.js";import{execFile as F}from"node:child_process";import{platform as O,release as W}from"node:os";import{posix as M}from"node:path";import{promisify as V}from"node:util";var j=V(F);async function he(e,n){if(!/^(?:[a-z]:[\\/]|\\\\)/iu.test(e)||O()!=="linux"||!(process.env.WSL_DISTRO_NAME||process.env.WSL_INTEROP||process.env.WSLENV||/microsoft/iu.test(W()))){return e}try{const{stdout:t}=await j("wslpath",["-a","-u",e],{encoding:"utf8",timeout:1e3,maxBuffer:64*1024,...n?{signal:n}:{}});const r=t.replace(/\r?\n$/u,"");if(!M.isAbsolute(r)||/[\r\n\0]/u.test(r)){throw new Error("wslpath did not return an absolute Linux path.")}return r}catch(t){throw new Error("Could not convert the Windows path with wslpath. Use an accessible Linux path instead.",{cause:t})}}var _=I(X(),1);var q=1e6;var z=1e3;var B=32;var v=/^(?![A-Za-z]:[\\/])(?![\\/])(?!.*(?:^|[\\/])\.\.(?:[\\/]|$))[^\0]+$/u;var L=/^sha256:[a-f0-9]{64}$/u;var G=/^git-blob:[a-f0-9]{40,64}$/u;function be(e){if(!E(e))return void 0;const n=e.reviewOutcome;return n==="pass"||n==="needs_changes"||n==="failed"?n:void 0}function xe(e){const n=e.trim();if(!n.startsWith("<annotation-result")||!n.endsWith("</annotation-result>")){return void 0}try{const t=K(n);R(t,"annotation-result");m(t,["version","source","review-run-id","trigger","mode","verdict"]);if(c(t,"version")!=="2"||c(t,"source")!=="code-review"||c(t,"verdict")!=="needs-changes"||!c(t,"review-run-id")){return void 0}const r=c(t,"trigger");const i=c(t,"mode");if(r!=="slash"&&r!=="natural_language"||i!=="inline"&&i!=="subagent"){return void 0}h(t);T(t,["summary","annotations"]);const s=x(f(t,"summary"));const o=f(t,"annotations");m(o,[]);h(o);if(o.children.some(l=>l.name!=="annotation"))return void 0;const u=o.children.map(U);if(!s||u.length===0)return void 0;return{schemaVersion:1,type:"review.result",scope:"local_changes",verdict:"needs_changes",summary:s,findings:u,mode:i}}catch{return void 0}}function ve(e){const n=e.trim();if(!n)return void 0;return{schemaVersion:1,type:"review.result",scope:"local_changes",verdict:"pass",summary:n,findings:[]}}function Re(e){if(!E(e)||e.schemaVersion!==1||e.type!=="review.result"){return false}if(e.scope!=="local_changes"||e.verdict!=="pass"&&e.verdict!=="needs_changes"||typeof e.summary!=="string"||!e.summary.trim()||!Array.isArray(e.findings)||!e.findings.every(Y)||e.mode!==void 0&&e.mode!=="inline"&&e.mode!=="subagent"){return false}return e.verdict==="pass"?e.findings.length===0:e.findings.length>0}function Te(e){if(e.verdict==="pass")return g(e.summary);return[g(e.summary),...e.findings.flatMap(n=>["",`[${n.priority}] ${g(n.title)}`,g(H(n)),g(n.content)])].join("\n")}function H(e){if(e.targetType==="file")return e.path;const n=e.startLine===e.endLine?String(e.startLine):`${String(e.startLine)}-${String(e.endLine)}`;return`${e.path}:${n}${e.side?` (${e.side})`:""}`}function U(e){R(e,"annotation");m(e,["id","kind","priority"]);if(c(e,"kind")!=="code-review"){throw new Error("annotation kind must be code-review")}const n=c(e,"id");const t=c(e,"priority");if(!n||!S(t))throw new Error("annotation identity is invalid");h(e);T(e,["target","title","content"]);const r=Z(f(e,"target"));const i=x(f(e,"title"));const s=x(f(e,"content"));if(!i||!s)throw new Error("annotation text is empty");return{id:n,priority:t,...r,title:i,content:s}}function Z(e){R(e,"target");const n=c(e,"uri");if(!v.test(n)||c(e,"type")!=="file"){throw new Error("annotation target is invalid")}h(e);if(e.attributes.state==="deleted"){m(e,["type","uri","state","blob-revision"]);if(e.children.length>0||!G.test(c(e,"blob-revision"))){throw new Error("deleted annotation target is invalid")}return{targetType:"file",path:n}}m(e,["type","uri"]);T(e,["selector","related-change"]);const t=f(e,"selector");m(t,["type","side","start-line","end-line","anchor-revision","context-before","context-after"]);h(t);if(t.children.length>0||c(t,"type")!=="line-range"){throw new Error("annotation selector is invalid")}const r=c(t,"side");const i=y(c(t,"start-line"));const s=y(c(t,"end-line"));const o=t.attributes["anchor-revision"];if(r!=="old"&&r!=="new"||s<i||o!==void 0&&!L.test(o)||!k(t.attributes["context-before"])||!k(t.attributes["context-after"])){throw new Error("annotation selector is invalid")}const u=Q(e,"related-change");if(u)J(u);return{targetType:"line-range",path:n,side:r,startLine:i,endLine:s}}function J(e){m(e,["path","side","start-line","end-line","revision"]);h(e);const n=c(e,"path");const t=c(e,"side");const r=y(c(e,"start-line"));const i=y(c(e,"end-line"));if(e.children.length>0||!v.test(n)||t!=="old"&&t!=="new"||i<r||!L.test(c(e,"revision"))){throw new Error("related change is invalid")}}function K(e){if(e.length>q)throw new Error("Review result is too large");let n;let t=false;let r=0;let i="";const s=[];const o=new _.SaxesParser({xmlns:false});o.on("opentag",u=>{r+=1;if(r>z||s.length>=B)t=true;const l={name:u.name,attributes:Object.fromEntries(Object.entries(u.attributes).map(([a,p])=>[a,String(p)])),children:[],text:""};const d=s.at(-1);if(d)d.children.push(l);else if(n)t=true;else n=l;s.push(l)});o.on("text",u=>{const l=s.at(-1);if(l)l.text+=u;else i+=u});o.on("closetag",()=>{s.pop()});o.on("cdata",()=>{t=true});o.on("comment",()=>{t=true});o.on("doctype",()=>{t=true});o.on("processinginstruction",()=>{t=true});o.on("error",()=>{t=true});o.write(e).close();if(t||!n||s.length>0||i.trim()){throw new Error("Review result XML is invalid")}return n}function x(e){m(e,[]);if(e.children.length>0)throw new Error(`${e.name} must contain text only`);return e.text.trim()}function R(e,n){if(e.name!==n)throw new Error(`Expected ${n}`)}function m(e,n){const t=[...n].sort().join("\0");const r=Object.keys(e.attributes).sort().join("\0");if(r!==t)throw new Error(`${e.name} attributes are invalid`)}function h(e){if(e.text.trim())throw new Error(`${e.name} contains unexpected text`)}function T(e,n){const t=new Set(n);if(e.children.some(r=>!t.has(r.name))){throw new Error(`${e.name} contains an unexpected element`)}}function f(e,n){const t=e.children.filter(i=>i.name===n);const r=t[0];if(t.length!==1||!r){throw new Error(`${e.name} must contain one ${n}`)}return r}function Q(e,n){const t=e.children.filter(r=>r.name===n);if(t.length>1)throw new Error(`${e.name} contains duplicate ${n}`);return t[0]}function c(e,n){const t=e.attributes[n];if(t===void 0)throw new Error(`${e.name}.${n} is required`);return t}function y(e){if(!/^[1-9]\d*$/u.test(e))throw new Error("Expected a positive integer");const n=Number(e);if(!Number.isSafeInteger(n))throw new Error("Integer is out of range");return n}function k(e){return e===void 0||/^[0-3]$/u.test(e)}function S(e){return e==="P0"||e==="P1"||e==="P2"||e==="P3"}function Y(e){if(!E(e))return false;if(typeof e.id!=="string"||!e.id||typeof e.priority!=="string"||!S(e.priority)||typeof e.path!=="string"||!v.test(e.path)||typeof e.title!=="string"||!e.title.trim()||typeof e.content!=="string"||!e.content.trim()){return false}if(e.targetType==="file"){return e.side===void 0&&e.startLine===void 0&&e.endLine===void 0}return e.targetType==="line-range"&&(e.side==="old"||e.side==="new")&&typeof e.startLine==="number"&&Number.isSafeInteger(e.startLine)&&e.startLine>0&&typeof e.endLine==="number"&&Number.isSafeInteger(e.endLine)&&e.endLine>=e.startLine}function E(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var N=/<(?:deliver[-_]assets|media|publish[_-]artifact|preview_card|genui-|alran-widget|alran-thinking|alran-progress|think|final|permission-(?:ask|response)|questionnaire-(?:ask|response))\b|^\s*preview_cards?:\s*$/imu;function ke(e){const n=ee(e);if(n.assets.length===0)return n.text;return[n.text,ue(n.assets)].filter(Boolean).join("\n\n")}function ee(e){const n=g(e);if(!n||!N.test(n))return{text:n,assets:[]};const t=$(n);const r=[];const i=[];let s="\uE000alran-protected";while(n.includes(s))s+="-";let o=false;const u=t.map(a=>{if(a.type==="protected"){const p=r.push(a.content)-1;return`${s}-${p}\uE001`}if(!N.test(a.content)){return a.content}o=true;return te(a.content,i)}).join("");if(!o)return{text:n,assets:[]};let l=de(u);r.forEach((a,p)=>{l=l.replace(`${s}-${p}\uE001`,a)});const d=[...new Map(i.map(a=>[a.path.trim(),a])).values()];return{text:l,assets:d.map(a=>({path:a.path.trim(),...a.name?.trim()?{name:a.name.trim()}:{}}))}}function te(e,n){let t=e;t=w(t,"alran-thinking");t=w(t,"think");t=ne(t,"alran-progress");t=w(t,"permission-ask");t=w(t,"permission-response");t=w(t,"questionnaire-ask");t=w(t,"questionnaire-response");t=t.replace(/<\/?final\b[^>]*>/giu,"");t=re(t);t=ie(t);t=se(t);t=ae(t);t=ce(t,n);t=t.replace(/<\/?(?:deliver-assets|deliver_assets)\b[^>]*>/giu,"file attachment").replace(/<media\b[^>]*\/?>/giu,"file attachment").replace(/<media\b[^>]*$/iu,"");return t}function w(e,n){const t=new RegExp(`<${n}\\b[^>]*>((?:(?!<${n}\\b)[\\s\\S])*?)<\\/${n}\\s*>`,"giu");let r=e;let i=e.replace(t,"");while(i!==r){r=i;i=i.replace(t,"")}return i}function ne(e,n){const t=new RegExp(`<${n}\\b[^>]*>((?:(?!<${n}\\b)[\\s\\S])*?)<\\/${n}\\s*>`,"giu");let r=e;let i=e.replace(t,(s,o)=>o.trim());while(i!==r){r=i;i=i.replace(t,(s,o)=>o.trim())}return i}function re(e){const n=/<alran-widget\b([^>]*)>([\s\S]*?)<\/alran-widget\s*>/giu;let t=e.replace(n,(r,i,s)=>{const o=/<alran-fallback\b[^>]*>([\s\S]*?)<\/alran-fallback\s*>/iu.exec(s)?.[1];if(o?.trim())return o.trim();return P(b(i))});t=t.replace(/<alran-widget\b([^>]*)>[\s\S]*$/iu,(r,i)=>P(b(i)));return t.replace(/<alran-widget\b[^>]*$/iu,"Interactive content is loading\u2026")}function P(e){const n=e["kind"]?.trim();const t=e["title"]?.trim();if(n&&t)return`Interactive ${n}: ${t} (open in Desktop).`;if(t)return`Interactive content: ${t} (open in Desktop).`;return"Interactive content available in Desktop."}function ie(e){const n=/<genui-([\w-]+)\b([^>]*)>[\s\S]*?<\/genui-\1\s*>/giu;const t=/<genui-([\w-]+)\b([^>]*?)\/\s*>/giu;let r=e.replace(n,(i,s,o)=>C(s,b(o)));r=r.replace(t,(i,s,o)=>C(s,b(o)));return r.replace(/<genui-[\w-]*\b[^>]*$/iu,"Interactive content is loading\u2026")}function C(e,n){if(e.toLocaleLowerCase()==="mcp-auth"){const t=n["label"]?.trim()||n["server-id"]?.trim();return t?`MCP authorization required: ${t} (open in Desktop).`:"MCP authorization required (open in Desktop)."}if(e.toLocaleLowerCase()==="agent-team-recommendation"){const t=n["status"]?.trim().toLocaleLowerCase();if(t==="accepted")return"Team recommendation accepted.";if(t==="skipped")return"Team recommendation skipped.";return"Team recommendation available in Desktop."}return"Interactive content available in Desktop."}function b(e){const n={};const t=/([\w-]+)\s*=\s*(["'])(.*?)\2/gu;let r;while((r=t.exec(e))!==null){const i=r[1];const s=r[3];if(i&&s!==void 0)n[i]=oe(s)}return n}function se(e){const n=/<(deliver-assets|deliver_assets)\b[^>]*>\s*<\/\1\s*>/giu;let t=e;let r=e.replace(n,"");while(r!==t){t=r;r=r.replace(n,"")}return r}function oe(e){return e.replace(/&quot;/gu,'"').replace(/&apos;|&#39;/gu,"'").replace(/&lt;/gu,"<").replace(/&gt;/gu,">").replace(/&amp;/gu,"&")}function ae(e){const n=/<\/?(deliver-assets|deliver_assets)\b[^>]*>/giu;const t=[];let r;while((r=n.exec(e))!==null){t.push({start:r.index,end:n.lastIndex,name:r[1]?.toLocaleLowerCase()??"",closing:r[0].startsWith("</")})}if(t.length===0)return e;const i=[];const s=new Set;t.forEach((l,d)=>{if(!l.closing){i.push(d);return}for(let a=i.length-1;a>=0;a-=1){const p=i[a];if(p===void 0||t[p]?.name!==l.name)continue;i.splice(a,1);s.add(p);s.add(d);return}});if(s.size===t.length)return e;let o=0;let u="";t.forEach((l,d)=>{u+=e.slice(o,l.start);u+=s.has(d)?e.slice(l.start,l.end):"file attachment";o=l.end});return u+e.slice(o)}function ce(e,n){let t=e;for(let r=0;r<3;r+=1){const i=A(t);const s=le(i);t=s.text;if(s.assets.length===0)break;n.push(...s.assets)}return t}function le(e){const n=[];const t=[];for(const r of e){if(r.type==="deliver-assets"||r.type==="image-gallery"){t.push(...r.items)}else if(r.content.trim()){n.push(r.content.trim())}}return{text:n.join("\n\n"),assets:t}}function ue(e){const n=e[0];if(!n)return"";if(e.length===1)return`File: ${D(n)}`;return["Files:",...e.map(t=>`- ${D(t)}`)].join("\n")}function D(e){const n=e.path.trim();const t=e.name?.trim();const r=n.split(/[\\/]/u).filter(Boolean).at(-1);if(!t||t===n||t===r)return n;const i=n?t.indexOf(n):-1;if(i>=0){return t.slice(0,i+n.length).trimEnd()}return`${t} \xB7 ${n}`}function de(e){return e.replace(/[^\S\r\n]+$/gmu,"").replace(/(?:\r?\n[\t ]*){3,}/gu,"\n\n").trim()}export{he as a,ke as b,ee as c,be as d,xe as e,ve as f,Re as g,Te as h};
@@ -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 u,c as p,f as c,g as S,h as w,i as b,j as h}from"./chunk-WYANV3IX.js";var d={plugin:"Plugin",skill:"Skill"};var N="No store is configured yet. Add one with: alran plugin marketplace add <url>";function f(e){return{id:e.id,kind:e.kind,name:e.name,displayName:e.displayName,origin:e.origin,...e.version?{version:e.version}:{},...e.installedVersion?{installedVersion:e.installedVersion}:{},description:e.description,...e.author?{author:e.author}:{},...e.group?{group:e.group}:{},...e.license?{license:e.license}:{},installed:e.installed,enabled:e.enabled,updateAvailable:e.updateAvailable,...e.conflict?{conflict:e.conflict}:{},summary:e.summary}}function y(e){const n=[];for(const t of e.sources){if(t.error&&t.index){const o=t.fetchedAtMs?` from ${new Date(t.fetchedAtMs).toISOString().slice(0,10)}`:"";n.push(`note: store "${t.source.id}" is unreachable (${t.error}); showing the copy${o}.`)}else if(t.error){n.push(`note: store "${t.source.id}" could not be read: ${t.error}`)}}return n}function $(e,n){return e.items.filter(t=>t.kind===n)}function x(e,n){const t=new Map;for(const o of[...e].sort((s,r)=>s.name.localeCompare(r.name))){const s=o.group??"Other";t.set(s,[...t.get(s)??[],o])}return[...t.entries()].sort(([o],[s])=>o.localeCompare(s)).map(([o,s])=>`${o}
2
+ import{a as u,c as p,f as c,g as S,h as w,i as b,j as h}from"./chunk-RLND4AYL.js";var d={plugin:"Plugin",skill:"Skill"};var N="No store is configured yet. Add one with: alran plugin marketplace add <url>";function f(e){return{id:e.id,kind:e.kind,name:e.name,displayName:e.displayName,origin:e.origin,...e.version?{version:e.version}:{},...e.installedVersion?{installedVersion:e.installedVersion}:{},description:e.description,...e.author?{author:e.author}:{},...e.group?{group:e.group}:{},...e.license?{license:e.license}:{},installed:e.installed,enabled:e.enabled,updateAvailable:e.updateAvailable,...e.conflict?{conflict:e.conflict}:{},summary:e.summary}}function y(e){const n=[];for(const t of e.sources){if(t.error&&t.index){const o=t.fetchedAtMs?` from ${new Date(t.fetchedAtMs).toISOString().slice(0,10)}`:"";n.push(`note: store "${t.source.id}" is unreachable (${t.error}); showing the copy${o}.`)}else if(t.error){n.push(`note: store "${t.source.id}" could not be read: ${t.error}`)}}return n}function $(e,n){return e.items.filter(t=>t.kind===n)}function x(e,n){const t=new Map;for(const o of[...e].sort((s,r)=>s.name.localeCompare(r.name))){const s=o.group??"Other";t.set(s,[...t.get(s)??[],o])}return[...t.entries()].sort(([o],[s])=>o.localeCompare(s)).map(([o,s])=>`${o}
3
3
  ${S(s,n)}`).join("\n\n")}async function j(e,n,t){const o=await e.store.catalog({offline:t.installed===true});const s=$(o,n).filter(i=>!t.installed||i.installed&&!p(i));if(t.json){return JSON.stringify({items:s.map(f),...y(o).length?{notes:y(o)}:{}},null,2)}const r=s.length?x(s,e.width??100):t.installed?`No ${n}s installed. Browse with: alran ${n==="plugin"?"plugin":"skills"} search`:o.sources.length===0?N:`No ${n}s are available.`;return[r,...y(o)].join("\n")}async function P(e,n,t){const o=await e.store.catalog({...t.refresh?{refresh:true}:{}});const s=h($(o,n),t.query??"");if(t.json){return JSON.stringify({query:t.query??"",items:s.map(f),...y(o).length?{notes:y(o)}:{}},null,2)}const r=s.length?S(s,e.width??100):o.sources.length===0?N:`No ${n}s match "${t.query??""}".`;return[r,...y(o)].join("\n")}async function H(e,n,t,o){const s=await e.store.catalog();const r=e.store.resolve(s,n,t);return o?JSON.stringify(f(r),null,2):w(r,void 0,e.width??100)}async function C(e,n,t){if(!n.inspection.requiresConsent)return false;const o=b(n.inspection.executes.map(r=>r.line));e.notify(`${d[n.entry.kind]} ${n.entry.name} ${n.entry.version}
4
4
  ${o}`);if(t)return true;const s=await e.confirm(`Install ${n.entry.name}? [y/N] `);if(s===void 0){throw new u("CONSENT_REQUIRED",`${n.entry.name} runs commands or connects to services (listed above). Nobody can be asked here: read the list and run again with --yes to approve it.`)}if(!s)throw new u("CONSENT_REQUIRED",`Not installed: ${n.entry.name} was not approved.`);return true}async function v(e,n,t){const o=await e.store.stage(n);const s=await C(e,o,t);const r=await e.store.commit(o,{consent:s});return{item:n,warnings:r.warnings,executes:o.inspection.executes.map(i=>i.line),updated:o.replacesVersion!==void 0}}async function J(e,n,t,o){const s=await e.store.catalog();const r=e.store.resolve(s,n,t);if(p(r)){return o.json?JSON.stringify({...f(r),changed:false},null,2):`${d[n]} ${r.name} is built in to Alran Code; there is nothing to install.`}if(r.installed&&!r.updateAvailable){return o.json?JSON.stringify({...f(r),changed:false},null,2):`${d[n]} ${c(r)} is already installed (${r.installedVersion??r.version??"unknown version"}).`}const i=await v(e,r,o.yes);const l=e.store.resolve(await e.store.catalog(),n,`${r.name}@${r.origin}`);if(o.json){return JSON.stringify({...f(l),changed:true,executes:i.executes,warnings:i.warnings},null,2)}const m=i.updated?"Updated":"Installed";const a=l.installedVersion?` ${l.installedVersion}`:"";return[`${m} ${d[n]} ${c(l)}${a} \u2014 ${l.summary}.`,...n==="plugin"?["It is enabled; Alran loads its skills in new sessions and after /reload."]:["Alran picks it up in new sessions and after /reload."],...i.warnings.map(g=>`warning: ${g}`)].join("\n")}async function T(e,n,t){const o=await e.store.catalog({refresh:true});const s=t.selector?[e.store.resolve(o,n,t.selector)]:$(o,n).filter(a=>a.installed&&a.updateAvailable);const r=[];const i=[];const l=[];for(const a of s){if(!a.installed){l.push(`${c(a)}: not installed`);continue}if(!a.updateAvailable){i.push(`${c(a)}: already current`);continue}try{await v(e,a,t.yes);r.push(`${c(a)}: ${a.installedVersion??"?"} \u2192 ${a.version??"?"}`)}catch(g){const I=g instanceof Error?g.message:String(g);if(t.selector)throw g;l.push(`${c(a)}: ${I}`)}}if(t.json)return JSON.stringify({updated:r,skipped:i,failed:l},null,2);const m=[...r.map(a=>`updated ${a}`),...i.map(a=>`skipped ${a}`),...l.map(a=>`failed ${a}`)];return m.length?m.join("\n"):`All ${n}s from stores are up to date.`}async function K(e,n,t,o){const s=await e.store.catalog({offline:true});let r;try{r=e.store.resolve(s,n,t)}catch(l){if(l instanceof u&&l.code==="NOT_FOUND"){throw new u("NOT_FOUND",`${d[n]} ${t} is not installed.`)}throw l}if(p(r)){throw new u("INSTALL_FAILED",`${d[n]} ${r.name} is built in to Alran Code and cannot be removed.`)}if(!r.installed)throw new u("NOT_FOUND",`${d[n]} ${c(r)} is not installed.`);const i=await e.store.remove(r);return o?JSON.stringify({...f(r),installed:false,enabled:false,warnings:i},null,2):[`Removed ${d[n]} ${c(r)}.`,...i.map(l=>`warning: ${l}`)].join("\n")}async function R(e,n,t){const o=await e.store.sources.list();const s=[...o.map(r=>({name:r.id,kind:"store",location:r.url,builtin:r.builtin===true})),{name:"local",kind:"directory",location:`${n}/plugins`,builtin:true}];if(t)return JSON.stringify(s,null,2);return s.map(r=>`${r.name} ${r.kind} ${r.location}`).join("\n")}async function D(e,n){const t=await e.store.sources.add({url:n.url,...n.name?{id:n.name}:{}});const o=await e.store.catalog({refresh:true});const s=o.sources.find(i=>i.source.id===t.id);if(n.json){return JSON.stringify({source:t,readable:Boolean(s?.index),...s?.error?{error:s.error}:{}},null,2)}const r=s?.index?`${s.index.plugins.length} plugins, ${s.index.skills.length} skills`:`not readable yet: ${s?.error??"unknown error"}`;return`Added store "${t.id}" (${t.url}): ${r}.`}async function q(e,n,t){const o=await e.store.sources.remove(n);return t?JSON.stringify({removed:o},null,2):`Removed store "${o.id}". Packages installed from it stay installed.`}function V(e,n={stdin:process.stdin,stderr:process.stderr,stdout:process.stdout}){return{store:e,width:n.stdout.columns&&n.stdout.columns>40?n.stdout.columns:100,notify:t=>{n.stderr.write(`${t}
5
5
  `)},confirm:async t=>{if(!n.stdin.isTTY||!n.stderr.isTTY)return void 0;const{createInterface:o}=await import("node:readline");const s=o({input:n.stdin,output:n.stderr});try{const r=await new Promise(i=>{s.question(t,i)});return/^y(es)?$/iu.test(r.trim())}finally{s.close()}}}}export{j as a,P as b,H as c,J as d,T as e,K as f,R as g,D as h,q as i,V as j};
@@ -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{x as D}from"./chunk-IWK7PZP7.js";import{d as n}from"./chunk-EYK25HWR.js";import{t as i,xa as a}from"./chunk-FXOH6TEQ.js";function o(r,t=i,e=a){return t(void 0,e())}function u(){return o(n())}function f(r){const t=r.ALRAN_DATA_DIR?.trim();if(t)return t;return void 0}function m(r=process.env,t=u){return f(r)??t()}function v(r=u,t=process.env){return m(t,r)}function p(r={}){const t=(r.getBuildEnv??n)();const e=v(r.getDefaultDataDir??(()=>o(t)),r.environment??process.env);(r.configureRuntimeEnvironment??D)({dataDir:e});return Promise.resolve(e)}export{o as a,m as b,v as c,p as d};
2
+ import{w as D}from"./chunk-5RIMHTEU.js";import{d as n}from"./chunk-5Y76VFHY.js";import{s as i,ya as a}from"./chunk-XVGPB7TW.js";function o(r,t=i,e=a){return t(void 0,e())}function u(){return o(n())}function f(r){const t=r.ALRAN_DATA_DIR?.trim();if(t)return t;return void 0}function v(r=process.env,t=u){return f(r)??t()}function m(r=u,t=process.env){return v(t,r)}function p(r={}){const t=(r.getBuildEnv??n)();const e=m(r.getDefaultDataDir??(()=>o(t)),r.environment??process.env);(r.configureRuntimeEnvironment??D)({dataDir:e});return Promise.resolve(e)}export{o as a,v as b,m as c,p as d};