UNPKG

@code-yeongyu/senpi

Version:

Coding agent CLI with read, bash, edit, write tools and session management

84 lines (83 loc) • 13.5 kB
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } } var __require=(x=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(x,{get:(a,b)=>(typeof require<"u"?require:a)[b]}):x)(function(x){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+x+'" is not supported')});import{createServer}from"node:http";function processSingleton(key,create){let slot=Symbol.for(key),existing=Reflect.get(globalThis,slot);if(existing!==void 0)return existing;let created=create();return Reflect.set(globalThis,slot,created),created}var brandSlot=processSingleton("@code-yeongyu/senpi-ai:oauth-page-brand",()=>({current:void 0}));function escapeHtml(value){return value.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}function renderPage(options){let title=escapeHtml(options.title),heading=escapeHtml(options.heading),message=escapeHtml(options.message),details=options.details?escapeHtml(options.details):void 0,brand=brandSlot.current,logo=brand?.logo?`<img class="logo" src="${brand.logo}" alt="" />`:"",brandName=brand?`<div class="brand-name">${escapeHtml(brand.name)}</div>`:"";return`<!doctype html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>${title}</title> <style> :root { --text: #fafafa; --text-dim: #a1a1aa; --page-bg: #09090b; --font-sans: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"; --font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; } * { box-sizing: border-box; } html { color-scheme: dark; } body { margin: 0; min-height: 100vh; display: flex; align-items: center; justify-content: center; padding: 24px; background: var(--page-bg); color: var(--text); font-family: var(--font-sans); text-align: center; } main { width: 100%; max-width: 560px; display: flex; flex-direction: column; align-items: center; justify-content: center; } .logo { width: 72px; height: 72px; display: block; margin-bottom: 16px; } .brand-name { margin-bottom: 24px; font-size: 15px; font-weight: 600; letter-spacing: 0.02em; color: var(--text-dim); } h1 { margin: 0 0 10px; font-size: 28px; line-height: 1.15; font-weight: 650; color: var(--text); } p { margin: 0; line-height: 1.7; color: var(--text-dim); font-size: 15px; } .details { margin-top: 16px; font-family: var(--font-mono); font-size: 13px; color: var(--text-dim); white-space: pre-wrap; word-break: break-word; } </style> </head> <body> <main> ${logo} ${brandName} <h1>${heading}</h1> <p>${message}</p> ${details?`<div class="details">${details}</div>`:""} </main> </body> </html>`}function oauthSuccessHtml(message){return renderPage({title:"Authentication successful",heading:"Authentication successful",message})}function oauthErrorHtml(message,details){return renderPage({title:"Authentication failed",heading:"Authentication failed",message,details})}var procEnvCache=null;function getBunSandboxEnvValue(name){if(!(typeof process>"u"||!process.versions?.bun||Object.keys(process.env).length>0)){if(procEnvCache===null){procEnvCache=new Map;try{let{readFileSync}=__require("node:fs"),data=readFileSync("/proc/self/environ","utf-8");for(let entry of data.split("\0")){let idx=entry.indexOf("=");idx>0&&procEnvCache.set(entry.slice(0,idx),entry.slice(idx+1))}}catch{}}return procEnvCache.get(name)}}function getProviderEnvValue(name,env){return env?.[name]||(typeof process<"u"?process.env[name]:void 0)||getBunSandboxEnvValue(name)||void 0}function formatThrownValue(value){return value instanceof Error?value.message||value.name:typeof value=="string"?value:String(value)}var ModelsError=class extends Error{constructor(code,message,options){super(withCauseDetail(message,options?.cause),options),this.name="ModelsError",this.code=code}};function withCauseDetail(message,cause){if(cause==null)return message;let detail=formatThrownValue(cause).trim();return!detail||message.includes(detail)?message:`${message}: ${detail}`}var _a,OAuthTokenEndpointError=class extends Error{constructor(message,status,facts={}){super(message),this.status=status,this.oauthError=facts.oauthError,this.credentialRefused=facts.credentialRefused??!1}};var UNAVAILABLE=Symbol.for("senpi.oauthRefreshUnavailable"),OAuthRefreshUnavailableError=class extends ModelsError{static{_a=UNAVAILABLE}constructor(provider,cause){super("oauth",`OAuth refresh failed for ${provider}`,{cause}),this[_a]=!0,this.name="OAuthRefreshUnavailableError"}};var DEVIN_TOKEN_URL="https://api.devin.ai/auth/cli/token";var DEVIN_FALLBACK_EXPIRY_MS=31536e6,TOKEN_EXCHANGE_TIMEOUT_MS=3e4;function decodeJwtExpiry(token){let payload=token.split(".")[1];if(!payload)return;let base64=payload.replaceAll("-","+").replaceAll("_","/"),padded=base64.padEnd(base64.length+(4-base64.length%4)%4,"=");try{let exp=JSON.parse(atob(padded)).exp;if(typeof exp=="number"&&Number.isFinite(exp)&&exp>0)return Math.trunc(exp*1e3)}catch{}}function errorDetail(body){if(typeof body.error_description=="string")return body.error_description;if(typeof body.message=="string")return body.message;if(typeof body.error=="string")return body.error;if(body.error&&typeof body.error=="object"&&!Array.isArray(body.error)){let message=body.error.message;if(typeof message=="string")return message}}function devinCredential(token){return{type:"oauth",access:token,refresh:token,expires:decodeJwtExpiry(token)??Date.now()+DEVIN_FALLBACK_EXPIRY_MS}}async function exchangeDevinAuthorizationCode(code,verifier,signal){if(signal.aborted)throw new Error("Login cancelled");let controller=new AbortController,onAbort=()=>controller.abort(signal.reason);signal.addEventListener("abort",onAbort,{once:!0});let timeout=setTimeout(()=>controller.abort(new Error("Devin OAuth token exchange timed out")),TOKEN_EXCHANGE_TIMEOUT_MS),response,body={};try{response=await fetch(DEVIN_TOKEN_URL,{method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({code,code_verifier:verifier}),signal:controller.signal});try{let parsed=await response.json();parsed&&typeof parsed=="object"&&!Array.isArray(parsed)&&(body=parsed)}catch{if(response.ok)throw new Error("Devin OAuth returned invalid JSON")}}catch(error){throw signal.aborted?new Error("Login cancelled"):controller.signal.aborted?new Error("Devin OAuth token exchange timed out"):error}finally{clearTimeout(timeout),signal.removeEventListener("abort",onAbort)}if(!response.ok){let detail=errorDetail(body);throw new OAuthTokenEndpointError(`Devin OAuth token exchange failed (HTTP ${response.status})${detail?`: ${detail}`:""}`,response.status)}if(typeof body.token!="string"||body.token.length===0)throw new Error('Devin OAuth response carries no "token"');return devinCredential(body.token)}var DEVIN_CALLBACK_PORT=59653,DEVIN_CALLBACK_PATH="/callback";function callbackHost(){return getProviderEnvValue("PI_OAUTH_CALLBACK_HOST")||"127.0.0.1"}function sendHtml(response,status,html){response.statusCode=status,response.setHeader("content-type","text/html; charset=utf-8"),response.setHeader("cache-control","no-store"),response.end(html)}async function startDevinCallbackServer(input){if(input.signal.aborted)throw new Error("Login cancelled");let host=callbackHost(),resolveCredential=()=>{},rejectCredential=()=>{},credential=new Promise((resolve,reject)=>{resolveCredential=resolve,rejectCredential=reject}),claimed=!1,settled=!1,timeout,onAbort,close=()=>{timeout&&clearTimeout(timeout),onAbort&&input.signal.removeEventListener("abort",onAbort),server.close()},finish=result=>{settled||(settled=!0,close(),"credential"in result?resolveCredential(result.credential):rejectCredential(result.error))},server=createServer((request,response)=>{(async()=>{let requestUrl=new URL(request.url??"/",`http://${host}`);if(request.method!=="GET"||requestUrl.pathname!==DEVIN_CALLBACK_PATH){sendHtml(response,404,oauthErrorHtml("OAuth callback route not found."));return}if(claimed||settled){sendHtml(response,409,oauthErrorHtml("This OAuth callback has already been used."));return}let oauthError=requestUrl.searchParams.get("error");if(oauthError){let description=requestUrl.searchParams.get("error_description")??oauthError;sendHtml(response,400,oauthErrorHtml("Devin authorization was denied.",description)),finish({error:new Error(`Devin authorization failed: ${description}`)});return}if((requestUrl.searchParams.get("state")??"")!==input.state){sendHtml(response,400,oauthErrorHtml("Devin authorization state mismatch.")),finish({error:new Error("Devin OAuth callback state mismatch")});return}let code=requestUrl.searchParams.get("code");if(!code){sendHtml(response,400,oauthErrorHtml("Devin returned no authorization code."));return}claimed=!0;try{let result=await exchangeDevinAuthorizationCode(code,input.verifier,input.signal);sendHtml(response,200,oauthSuccessHtml("Signed in to Devin. You may now close this page.")),finish({credential:result})}catch(error){let message=error instanceof Error?error.message:"Unknown token exchange error";sendHtml(response,502,oauthErrorHtml("Devin token exchange failed.",message)),finish({error:error instanceof Error?error:new Error(message)})}})()});if(await new Promise((resolve,reject)=>{server.once("error",reject),server.listen(DEVIN_CALLBACK_PORT,host,()=>{server.removeListener("error",reject),resolve()})}),server.on("error",error=>finish({error})),onAbort=()=>finish({error:new Error("Login cancelled")}),input.signal.addEventListener("abort",onAbort,{once:!0}),input.signal.aborted)throw close(),new Error("Login cancelled");return timeout=setTimeout(()=>finish({error:new Error("Devin OAuth login timed out")}),input.loginTimeoutMs),{callbackUrl:`http://${host}:${DEVIN_CALLBACK_PORT}${DEVIN_CALLBACK_PATH}`,close,cancelWait:()=>{claimed||finish({credential:null})},waitForCredential:()=>credential}}function base64urlEncode(bytes){let binary="";for(let byte of bytes)binary+=String.fromCharCode(byte);return btoa(binary).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async function generatePKCE(){let verifierBytes=new Uint8Array(32);crypto.getRandomValues(verifierBytes);let verifier=base64urlEncode(verifierBytes),data=new TextEncoder().encode(verifier),hashBuffer=await crypto.subtle.digest("SHA-256",data),challenge=base64urlEncode(new Uint8Array(hashBuffer));return{verifier,challenge}}var AUTHORIZE_URL="https://app.devin.ai/auth/cli/continue",LOGIN_TIMEOUT_MS=300*1e3;function parseAuthorizationInput(input){let value=input.trim();if(value){try{return new URL(value).searchParams.get("code")??void 0}catch{}return value.includes("code=")?new URLSearchParams(value).get("code")??void 0:value}}function authorizeUrl(input){let url=new URL(AUTHORIZE_URL);return url.search=new URLSearchParams({response_type:"code",redirect_uri:input.redirectUri,code_challenge:input.challenge,code_challenge_method:"S256",state:input.state,prompt:"select_account"}).toString(),url.toString()}async function loginDevin(interaction){let{verifier,challenge}=await generatePKCE(),state=crypto.randomUUID(),callback=await startDevinCallbackServer({state,verifier,signal:interaction.signal,loginTimeoutMs:LOGIN_TIMEOUT_MS}),manualAbort=new AbortController,manualInput,manualError;try{interaction.notify({type:"progress",message:`Listening for the Devin OAuth callback on ${callback.callbackUrl}`}),interaction.notify({type:"auth_url",url:authorizeUrl({redirectUri:callback.callbackUrl,challenge,state}),instructions:"Sign in to Devin in your browser. If the browser is on another machine, paste the final redirect URL here."});let manualPromise=interaction.prompt({type:"manual_code",message:"Complete sign-in in your browser, or paste the authorization code / redirect URL here:",placeholder:callback.callbackUrl,signal:manualAbort.signal}).then(input=>{manualInput=input,callback.cancelWait()}).catch(error=>{manualError=error instanceof Error?error:new Error(String(error)),callback.cancelWait()}),credential=await callback.waitForCredential();if(manualError)throw manualError;if(credential)return credential;if(await manualPromise,manualError)throw manualError;let code=manualInput?parseAuthorizationInput(manualInput):void 0;if(!code)throw new Error("Missing authorization code");return interaction.notify({type:"progress",message:"Exchanging the authorization code for a Devin token..."}),await exchangeDevinAuthorizationCode(code,verifier,interaction.signal)}finally{manualAbort.abort(),callback.close()}}var devinOAuth={name:"Devin",isSubscription:!0,loginLabel:"Sign in with Devin",login:loginDevin,async refresh(credential,_signal){return credential},async toAuth(credential){return{apiKey:credential.access}}};export{devinOAuth};