@mitsein-ai/cli 0.1.3 → 0.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +2 -2
- package/package.json +2 -2
- package/src/commands/command-opts.ts +5 -1
- package/src/core/errors.ts +4 -1
package/dist/index.js
CHANGED
|
@@ -237,7 +237,7 @@ ${I}`)}formatType(A,Q,B){let I=Jz[A.type]||wz[A.level]||"gray";if(Q)return Vz(I)
|
|
|
237
237
|
`):""),A.type==="trace"){let L=Error("Trace: "+A.message);Y+=this.formatStack(L.stack||"",L.message)}return C?`
|
|
238
238
|
`+Y+`
|
|
239
239
|
`:Y}}function DF(A){return A.replace(/`([^`]+)`/gm,(Q,B)=>FQ.cyan(B)).replace(/\s+_([^_]+)_\s+/gm,(Q,B)=>` ${FQ.underline(B)} `)}function Lz(A="white"){return FQ[A]||FQ.white}function Vz(A="bgWhite"){return FQ[`bg${A[0].toUpperCase()}${A.slice(1)}`]||FQ.bgWhite}function Wz(A={}){let Q=Zz();if(process.env.CONSOLA_LEVEL)Q=Number.parseInt(process.env.CONSOLA_LEVEL)??Q;return L1({level:Q,defaults:{level:Q},stdout:process.stdout,stderr:process.stderr,prompt:(...I)=>Promise.resolve().then(() => (a1(),o1)).then((E)=>E.prompt(...I)),reporters:A.reporters||[A.fancy??!(sU||oU)?new I9:new e0],...A})}function Zz(){if(mT)return tA.debug;if(oU)return tA.warn;return tA.info}var wA=Wz();function SH(){let A=process.env.https_proxy??process.env.HTTPS_PROXY??process.env.http_proxy??process.env.HTTP_PROXY;if(!A)return;try{let{ProxyAgent:Q,setGlobalDispatcher:B}=HH(),I=new Q(A);B(I)}catch{process.stderr.write(`[warn] Proxy ${A} detected but undici not available. Install undici for proxy support.
|
|
240
|
-
`)}}bJ();FC();import{existsSync as rS,readFileSync as Ri}from"node:fs";import{join as aS}from"node:path";class e extends Error{code;detail;constructor(A,Q=1,B){super(A);this.name="CliError",this.code=Q,this.detail=B}}class mJ extends e{constructor(A="No credentials found. Set MITSEIN_TOKEN, pass --token, or run from a dev environment with scripts/dev-token.sh."){super(A,2);this.name="NoCredentialsError"}}class WD extends e{statusCode;constructor(A,Q,B){let I=A>=400&&A<500?1:3;super(Q,I,B);this.name="HttpError",this.statusCode=A}}function NA(A){return async function(...B){try{await Promise.resolve(A.apply(this,B))}catch(I){if(I instanceof e){if(wA.error(`Error: ${I.message}`),I.detail!=null&&I.detail!=="")
|
|
240
|
+
`)}}bJ();FC();import{existsSync as rS,readFileSync as Ri}from"node:fs";import{join as aS}from"node:path";class e extends Error{code;detail;constructor(A,Q=1,B){super(A);this.name="CliError",this.code=Q,this.detail=B}}class mJ extends e{constructor(A="No credentials found. Set MITSEIN_TOKEN, pass --token, or run from a dev environment with scripts/dev-token.sh."){super(A,2);this.name="NoCredentialsError"}}class WD extends e{statusCode;constructor(A,Q,B){let I=A>=400&&A<500?1:3;super(Q,I,B);this.name="HttpError",this.statusCode=A}}function NA(A){return async function(...B){try{await Promise.resolve(A.apply(this,B))}catch(I){if(I instanceof e){if(wA.error(`Error: ${I.message}`),I.detail!=null&&I.detail!==""){let E=typeof I.detail==="object"?JSON.stringify(I.detail,null,2):String(I.detail);wA.error(E)}process.exit(I.code)}if(I!==null&&typeof I==="object"&&I.name==="AbortError")process.stderr.write(`
|
|
241
241
|
Interrupted.
|
|
242
242
|
`),process.exit(130);throw I}}}function Li(A){try{return new URL(A).hostname}catch{return""}}function Vi(A){let Q=Li(A);return Q==="localhost"||Q==="127.0.0.1"||Q==="::1"||Q==="0.0.0.0"}function Wi(A){let Q=[];if(A)Q.push(A);Q.push(process.cwd());for(let B of Q){let I=B;for(let E=0;E<10;E++){let D=aS(I,"scripts","dev-token.sh");if(rS(D))return D;let C=aS(I,"..");if(C===I)break;I=C}}return null}function Zi(A,Q){let{execFileSync:B}=z("node:child_process"),I=[A,"--raw"];if(Q)I.push("--real");try{let E=B("bash",I,{timeout:1e4,encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim();return{ok:E.length>0,stdout:E}}catch{return{ok:!1,stdout:""}}}function Xi(A,Q){if(A)return{token:A,endpoint:Q??DE};return null}function Hi(){let A=process.env.MITSEIN_TOKEN;if(A)return{token:A,endpoint:process.env.MITSEIN_API_URL??DE};return null}function Si(A,Q){let B=gE(A);if(!rS(B))return null;try{let I=Ri(B,"utf8"),E=JSON.parse(I),D=E.access_token;if(D)return{token:D,endpoint:Q??E.endpoint??DE}}catch{}return null}function Ki(A,Q,B,I){let E=A??DE;if(!Vi(E))return null;let D=Wi(B);if(!D)return null;try{let{ok:C,stdout:F}=I(D,Q);if(C)return{token:F,endpoint:E}}catch{}return null}function GB(A={}){let Q=A.profile??"e2e",B=A.spawnDevToken??Zi,I=Xi(A.token,A.endpoint);if(I)return I;let E=Hi();if(E)return E;let D=Si(Q,A.endpoint);if(D)return D;let C=Ki(A.endpoint,A.real??!1,A.projectRoot,B);if(C)return C;throw new mJ}function Ti(A){return A.replace(/\/$/,"")}function FE(A,Q){if(A)process.stderr.write(`[debug] ${Q}
|
|
243
243
|
`)}function zi(A){let Q="HTTP error",B;if(A!==null&&typeof A==="object"&&!Array.isArray(A)){let I=A;Q=typeof I.message==="string"?I.message:Q,B=I.detail??I.error}return{message:Q,detail:B}}async function L0(A){try{return await A}catch(Q){if(Q instanceof VD){let B=Q.statusCode??Q.status??0,{message:I,detail:E}=zi(Q.data);throw new WD(B||599,I,E)}throw Q}}class PA{timeoutMs;debug;fetchImpl;baseUrl;bearerToken;constructor(A,Q={}){this.debug=Q.debug??!1,this.timeoutMs=Q.timeoutSec===void 0||Q.timeoutSec===0?void 0:Q.timeoutSec*1000,this.baseUrl=Ti(A.endpoint),this.bearerToken=A.token;let B=this.debug;this.fetchImpl=Q.fetcher??NN.create({baseURL:this.baseUrl,timeout:this.timeoutMs,headers:{Authorization:`Bearer ${A.token}`,"Content-Type":"application/json"},retry:0,onRequest({request:I}){FE(B,`${I.method} ${I.url}`)},onResponse({response:I}){FE(B,`→ ${I.status} (${I.headers.get("content-length")??"?"} bytes)`)}})}static fromOptions(A){let{timeoutSec:Q,debug:B,fetcher:I,...E}=A,D=GB(E);return new PA(D,{timeoutSec:Q,debug:B,fetcher:I})}async get(A,Q){let B=A.startsWith("/")?A:`/${A}`;return L0(this.fetchImpl(B,{method:"GET",query:Q??void 0}))}async post(A,Q){let B=A.startsWith("/")?A:`/${A}`;if(this.debug&&Q!==void 0&&Q!==null)FE(this.debug,`body: ${JSON.stringify(Q)}`);return L0(this.fetchImpl(B,{method:"POST",body:Q===void 0||Q===null?void 0:Q}))}async postForm(A,Q){let B=A.startsWith("/")?A:`/${A}`,I={};for(let[Y,M]of Object.entries(Q??{}))if(M!==void 0&&M!==null)I[Y]=String(M);if(this.debug)FE(this.debug,`POST ${B}`),FE(this.debug,`form: ${JSON.stringify(I)}`);let E=`${this.baseUrl}${B}`,D=new URLSearchParams(I),C=new AbortController,F=this.timeoutMs,U=F===void 0?null:setTimeout(()=>C.abort(),F);try{let Y=await fetch(E,{method:"POST",headers:{Authorization:`Bearer ${this.bearerToken}`,"Content-Type":"application/x-www-form-urlencoded"},body:D,signal:C.signal});if(FE(this.debug,`→ ${Y.status} (${Y.headers.get("content-length")??"?"} bytes)`),Y.ok){if((Y.headers.get("content-type")??"").includes("application/json"))return Y.json();return Y.text()}let M=`HTTP ${Y.status}`,V;try{let w=await Y.json();M=typeof w.message==="string"?w.message:M,V=w.detail??w.error}catch{}throw new WD(Y.status,M,V)}catch(Y){if(Y instanceof WD)throw Y;if(Y instanceof Error&&Y.name==="AbortError")throw new WD(599,"Request aborted or timed out");throw Y}finally{if(U)clearTimeout(U)}}async patch(A,Q){let B=A.startsWith("/")?A:`/${A}`;if(this.debug&&Q!==void 0&&Q!==null)FE(this.debug,`body: ${JSON.stringify(Q)}`);return L0(this.fetchImpl(B,{method:"PATCH",body:Q===void 0||Q===null?void 0:Q}))}async put(A,Q){let B=A.startsWith("/")?A:`/${A}`;if(this.debug&&Q!==void 0&&Q!==null)FE(this.debug,`body: ${JSON.stringify(Q)}`);return L0(this.fetchImpl(B,{method:"PUT",body:Q===void 0||Q===null?void 0:Q}))}async delete(A){let Q=A.startsWith("/")?A:`/${A}`;return L0(this.fetchImpl(Q,{method:"DELETE"}))}}var cJ=!1;function UA(A){cJ=A}function eS(){return cJ}function A7(){return process.stdout.isTTY===!0}function EA(A,Q){if(cJ){process.stdout.write(`${JSON.stringify(A,$i)}
|
|
@@ -269,7 +269,7 @@ Interrupted.
|
|
|
269
269
|
`)}else process.stdout.write(`${JSON.stringify({ts:A.timestamp,type:A.event_type,raw:A.data})}
|
|
270
270
|
`);else B7(A)}async function NC(A){let Q=Date.now(),B=[],I="unknown",E=null,D=[],C=[],F=A.stream_output??!1,U=A.json_mode??eS(),Y=A.event_filter??null,M=A.debug??!1,V=A.eventStream==null,w=V?new AbortController:null,L=()=>{w?.abort()};if(V)process.once("SIGINT",L);let R=`/api/agent-run/${A.agent_run_id}/stream`,S=A.eventStream??C7({endpoint:A.endpoint,path:R,token:A.token,timeoutSec:A.timeout??void 0,debug:M,signal:w?.signal});try{try{for await(let $ of S){if(B.push({type:$.event_type,data:$.data}),A.on_event?.($),F)Oi($,U,Y);if(typeof $.data==="object"&&$.data!==null){let{data:O,event_type:P}=$;if(P==="status"){let x=typeof O.status==="string"?O.status:"";if(x==="completed"){I="succeeded";break}if(x==="failed"||x==="error"){I="failed",E=(typeof O.content==="string"?O.content:null)??(typeof O.error==="string"?O.error:null)??null;break}}else if(P==="error"){I="failed",E=(typeof O.content==="string"?O.content:null)??String($.data);break}else if(P==="assistant"||P==="text"||P==="message"){let x=typeof O.content==="string"?O.content:"";if(x)D.push(x)}else if(P==="tool_call"||P==="tool_result")C.push(O)}}}catch($){if($!==null&&typeof $==="object"&&$.name==="AbortError"){if(!U)process.stderr.write(`
|
|
271
271
|
\x1B[2mDisconnected from stream (run continues in background)\x1B[0m
|
|
272
|
-
`);I="disconnected"}else throw $}}finally{if(V)process.off("SIGINT",L)}let K=Date.now()-Q,H={status:I,agent_run_id:A.agent_run_id,duration_ms:K,events_count:B.length};if(D.length>0)H.assistant_message=D.join("");if(C.length>0)H.tool_calls=C;if(E)H.error=E;if(E7(F,U))I7(H);if(I==="failed")throw new e(`Run failed: ${E??"unknown error"}`,1,H);return H}function YA(A){
|
|
272
|
+
`);I="disconnected"}else throw $}}finally{if(V)process.off("SIGINT",L)}let K=Date.now()-Q,H={status:I,agent_run_id:A.agent_run_id,duration_ms:K,events_count:B.length};if(D.length>0)H.assistant_message=D.join("");if(C.length>0)H.tool_calls=C;if(E)H.error=E;if(E7(F,U))I7(H);if(I==="failed")throw new e(`Run failed: ${E??"unknown error"}`,1,H);return H}function YA(A){let Q=A.optsWithGlobals();return Q.endpoint=Q.endpoint??process.env.MITSEIN_API_URL,Q.token=Q.token??process.env.MITSEIN_TOKEN,Q}function ZD(A){if(!A)return null;let Q=A.split(",").map((B)=>B.trim()).filter((B)=>B.length>0);return Q.length>0?new Set(Q):null}function bA(A){let Q=A.timeout??"30",B=Number.parseFloat(Q);if(!Number.isFinite(B))return 30;if(B===0)return;return B}function D7(A){A.command("agent").description("Agent operations").command("invoke <thread_id> <prompt>").description("Send a message, start the agent, optional wait/stream").option("--wait","Block until run completes",!1).option("--stream","Stream run events",!1).option("--cancel-on-interrupt","Cancel run on Ctrl-C (reserved)",!1).option("--filter <types>","Comma-separated SSE event types").option("--model <name>","Model override").option("--timeout <sec>","Wait/stream timeout (0 = no limit)","120").action(NA(async function(I,E){let D=YA(this),C=this.opts();if(UA(Boolean(D.json)),C.wait&&C.stream)throw new e("--wait and --stream are mutually exclusive",2);let F=GB({token:D.token,endpoint:D.endpoint,profile:D.profile??"e2e",real:D.real}),U=new PA(F,{debug:D.debug,timeoutSec:bA(D)}),Y=await U.post("/api/message/add",{thread_id:I,content:E}),M={};if(C.model)M.model_name=C.model;let w=(await U.postForm(`/api/thread/${I}/agent/start`,M)).agent_run_id??"";if(!C.wait&&!C.stream){EA({message:Y,agent_run_id:w,status:"started"});return}let L=C.timeout??"120",R=Number.parseFloat(L),S=Number.isFinite(R)&&R===0?null:Number.isFinite(R)?R:120,K=await NC({endpoint:F.endpoint,token:F.token,agent_run_id:w,timeout:S??void 0,stream_output:Boolean(C.stream),json_mode:Boolean(D.json),debug:D.debug,event_filter:ZD(C.filter)});if(C.wait&&!C.stream)EA(K)}))}import{readFileSync as N7}from"node:fs";FC();import{existsSync as g7,readFileSync as qi,writeFileSync as Pi}from"node:fs";function pJ(A){let Q=A.replace(/([a-z0-9])([A-Z])/g,"$1-$2");return Q=Q.replace(/[_\s/]+/g,"-"),Q=Q.replace(/-+/g,"-"),Q=Q.replace(/^-+|-+$/g,""),Q.toLowerCase()}class F7{_spec;_operations=new Map;_byId=new Map;constructor(A){this._spec=A,this.parse()}parse(){let A=this._spec.paths;if(A===null||typeof A!=="object"||Array.isArray(A))return;for(let[Q,B]of Object.entries(A)){if(B===null||typeof B!=="object"||Array.isArray(B))continue;let I=B;if("$ref"in I&&Object.keys(I).length===1)continue;for(let E of["get","post","put","patch","delete"]){let D=I[E];if(D===null||typeof D!=="object"||Array.isArray(D))continue;let C=D,F=typeof C.operationId==="string"?C.operationId:"",U=Array.isArray(C.tags)?C.tags:["untagged"],Y=typeof U[0]==="string"?U[0]:"untagged",M=pJ(Y),V=typeof C.summary==="string"?C.summary:"",w=Array.isArray(C.parameters)?C.parameters:[],L=C.requestBody!==null&&typeof C.requestBody==="object"&&!Array.isArray(C.requestBody)?C.requestBody:null,R=F?pJ(F):`${E}-${pJ(Q)}`,S={operation_id:R,tag:M,method:E,path:Q,summary:V,parameters:w,request_body:L},K=this._operations.get(M)??[];K.push(S),this._operations.set(M,K),this._byId.set(R,S)}}}get tags(){return[...this._operations.keys()].sort()}operationsForTag(A){return this._operations.get(A)??[]}getOperation(A){return this._byId.get(A)}get allOperations(){return[...this._byId.values()]}}function lJ(A){let Q=qi(A,"utf8");try{return JSON.parse(Q)}catch{let B=Q.trim();if(B.startsWith("openapi:")||B.startsWith("swagger:"))throw new e(`File ${A} appears to be YAML; install a YAML parser or use JSON.`,2);throw new e(`Failed to parse ${A} as JSON`,2)}}async function ki(A,Q){let B=`${A.replace(/\/$/,"")}/openapi.json`,I;try{I=await fetch(B,{signal:AbortSignal.timeout(1e4)})}catch(D){throw new e(`Failed to fetch OpenAPI spec from ${B}: ${D}`,3)}if(!I.ok)throw new e(`Failed to fetch OpenAPI spec from ${B}: HTTP ${I.status}`,3);let E=await I.json();try{w0(),Pi(Q,`${JSON.stringify(E,null,2)}
|
|
273
273
|
`,"utf8")}catch{}return E}async function iJ(A={}){let Q=process.env.MITSEIN_OPENAPI_PATH;if(Q)return lJ(Q);let B=R0();if(!A.refresh&&g7(B))try{return lJ(B)}catch{}if(A.endpoint)return ki(A.endpoint,B);if(g7(B))return lJ(B);throw new e("No OpenAPI spec available. Run `mitsein dev openapi --refresh` or set MITSEIN_OPENAPI_PATH.",2)}async function UN(A={}){let Q=await iJ(A);return new F7(Q)}function hi(A){let Q={},B=0;while(B<A.length){let I=A[B];if(I===void 0)break;if(I.startsWith("--")){let E=I.replace(/^-+/,""),D=A[B+1];if(D!==void 0&&!D.startsWith("--"))Q[E]=D,B+=2;else Q[E]="true",B+=1}else B+=1}return Q}function fi(A,Q){if(Q){let B=N7(0,"utf8");try{return JSON.parse(B)}catch(I){throw new e(`Invalid JSON from stdin: ${I}`,2)}}if(A===void 0)return;if(A.startsWith("@")){let B=A.slice(1);try{let I=N7(B,"utf8");return JSON.parse(I)}catch(I){if(I.code==="ENOENT")throw new e(`File not found: ${B}`,2);throw new e(`Invalid JSON in ${B}: ${I}`,2)}}try{return JSON.parse(A)}catch(B){throw new e(`Invalid JSON body: ${B}`,2)}}async function vi(A,Q,B,I){let{path:E,method:D}=Q,C=[...E.matchAll(/\{(\w+)\}/g)].map((U)=>U[1]??""),F={...I};for(let U of C)if(U in F){let Y=F[U];delete F[U],E=E.replace(`{${U}}`,Y??"")}else throw new e(`Missing required path parameter: --${U}`,2);if(D==="get"){let U=Object.keys(F).length>0?{...F}:void 0;return A.get(E,U)}if(D==="post")return A.post(E,B);if(D==="patch")return A.patch(E,B);if(D==="put")return A.put(E,B);if(D==="delete")return A.delete(E);throw new e(`Unsupported HTTP method: ${D}`,2)}function xi(A){let Q=A;wA.log(` \x1B[1m${Q.tag??""}\x1B[0m (${Q.operations??0} operations)`)}function bi(A){let Q=A,B=Q.method??"",I=B==="GET"?"\x1B[32m":B==="POST"?"\x1B[34m":B==="PATCH"?"\x1B[33m":B==="DELETE"?"\x1B[31m":"\x1B[37m",E=(Q.operation??"").padEnd(30);wA.log(` ${I}${B.padEnd(6)}\x1B[0m ${E} ${Q.summary??""}`)}function U7(A){let Q=A.command("api").description("Auto-generated API commands from OpenAPI spec");Q.command("list-tags").description("List all available API tags").option("--endpoint <url>","API base URL").action(NA(async function(){let I=YA(this),E=this.opts();UA(Boolean(I.json));let D=await UN({endpoint:E.endpoint??I.endpoint});for(let C of D.tags){let F=D.operationsForTag(C);EA({tag:C,operations:F.length},xi)}})),Q.command("list-ops <tag>").description("List operations for a tag").option("--endpoint <url>","API base URL").action(NA(async function(I){let E=YA(this),D=this.opts();UA(Boolean(E.json));let C=await UN({endpoint:D.endpoint??E.endpoint}),F=C.operationsForTag(I);if(F.length===0)throw new e(`Unknown tag '${I}'. Available: ${C.tags.join(", ")}`,2);for(let U of F)EA({operation:U.operation_id,method:U.method.toUpperCase(),path:U.path,summary:U.summary},bi)})),Q.command("api-call <tag> <operation>").description(`Execute an API operation (examples: mitsein api api-call threads list-threads --body '{"limit":20}')`).allowUnknownOption(!0).allowExcessArguments(!0).option("--body <json>","JSON body: inline or @file.json").option("--body-stdin","Read JSON body from stdin",!1).option("--endpoint <url>","API base URL").option("--token <token>","Bearer token").option("--timeout <sec>","HTTP timeout (0 = none)","30").option("--debug","Print HTTP details",!1).action(NA(async function(I,E){let D=YA(this),C=this.opts();UA(Boolean(D.json));let F=await UN({endpoint:C.endpoint??D.endpoint}),U=F.getOperation(E);if(U===void 0){let K=F.operationsForTag(I);if(K.length===0){let $=F.tags.length>0?F.tags.join(", "):"(none — run `mitsein dev openapi --refresh`)";throw new e(`Unknown tag '${I}'. Available tags: ${$}`,2)}let H=K.map(($)=>$.operation_id).join(", ");throw new e(`Unknown operation '${E}' in tag '${I}'. Available: ${H}`,2)}if(U.tag!==I)throw new e(`Operation '${E}' belongs to tag '${U.tag}', not '${I}'.`,2);let Y=fi(C.body,Boolean(C.bodyStdin)),M=hi(this.args.slice(2)),V=C.timeout??D.timeout??"30",w=Number.parseFloat(V),L=Number.isFinite(w)&&w===0?void 0:Number.isFinite(w)?w:30,R=PA.fromOptions({token:C.token??D.token,endpoint:C.endpoint??D.endpoint,profile:D.profile??"e2e",real:D.real,timeoutSec:L,debug:Boolean(C.debug??D.debug)}),S=await vi(R,U,Y,M);EA(S)}))}import{existsSync as w7,readFileSync as ni,unlinkSync as si}from"node:fs";FC();import{createServer as li}from"node:http";import{parse as ii}from"node:querystring";FC();import{execFileSync as dJ}from"node:child_process";import{chmodSync as ui,mkdirSync as mi,writeFileSync as ci}from"node:fs";import{dirname as pi}from"node:path";var Y7=19284;function YN(A,Q,B){w0();let I=gE(A);mi(pi(I),{recursive:!0,mode:448});let E={access_token:B.access_token??"",user_email:B.user_email??"",user_id:B.user_id??"",endpoint:Q,created_at:Date.now()/1000,expires_in:B.expires_in??86400};ci(I,`${JSON.stringify(E,null,2)}
|
|
274
274
|
`,"utf8"),ui(I,384)}function MN(A){try{if(process.platform==="darwin")dJ("open",[A],{stdio:"ignore"});else if(process.platform==="win32")dJ("cmd",["/c","start","",A],{stdio:"ignore"});else dJ("xdg-open",[A],{stdio:"ignore"})}catch{}}function M7(A){return(A??process.env.MITSEIN_API_URL??DE).replace(/\/$/,"")}function XD(A,Q){let B=A[Q];if(Array.isArray(B))return B[0];return B}async function G7(A,Q,B,I){let E={};if(await new Promise((D,C)=>{let F=!1,U,Y=()=>{if(F)return;if(F=!0,U!==void 0)clearTimeout(U);M.close(()=>D())},M=li((V,w)=>{let L=V.url??"",R="";try{R=new URL(L,"http://127.0.0.1").pathname}catch{R=""}if(R!=="/callback"){w.writeHead(404),w.end(),Y();return}let S=L.includes("?")?ii(L.split("?",2)[1]??""):{};if(S.error){w.writeHead(200,{"Content-Type":"text/html"});let K=XD(S,"error_description")??XD(S,"error")??"Unknown error";w.end(`<html><body><h2>Login failed</h2><p>${String(K)}</p></body></html>`),E.error=String(K),Y();return}if(S.account)E.account=XD(S,"account")??"";if(S.email)E.email=XD(S,"email")??"";if(S.token)E.token=XD(S,"token")??"";if(S.session_id)E.session_id=XD(S,"session_id")??"";w.writeHead(200,{"Content-Type":"text/html"}),w.end("<html><body><h2>Login successful!</h2><p>You can close this window.</p></body></html>"),E.success=!0,Y()});M.once("error",(V)=>{if(!F){if(F=!0,U!==void 0)clearTimeout(U);C(V)}}),U=setTimeout(()=>Y(),300000),M.listen(Y7,"127.0.0.1",()=>{let V=`${A}/api/auth/cognito/login?provider=${encodeURIComponent(Q)}`;if(!I)wA.log(`
|
|
275
275
|
Opening browser for login...`),wA.log(`If browser does not open, visit: ${V}
|
package/package.json
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
"ofetch": "^1.4.1",
|
|
9
9
|
"undici": "^8.0.2"
|
|
10
10
|
},
|
|
11
|
-
"description": "Mitsein CLI
|
|
11
|
+
"description": "Mitsein CLI \u2014 dev tooling, API helpers, and workflow automation",
|
|
12
12
|
"devDependencies": {
|
|
13
13
|
"@types/bun": "latest",
|
|
14
14
|
"typescript": "^5.3.3"
|
|
@@ -46,5 +46,5 @@
|
|
|
46
46
|
"typecheck": "tsc --noEmit"
|
|
47
47
|
},
|
|
48
48
|
"type": "module",
|
|
49
|
-
"version": "0.1.
|
|
49
|
+
"version": "0.1.4"
|
|
50
50
|
}
|
|
@@ -12,7 +12,11 @@ export interface MitseinGlobalOpts {
|
|
|
12
12
|
}
|
|
13
13
|
|
|
14
14
|
export function readGlobals(cmd: Command): MitseinGlobalOpts {
|
|
15
|
-
|
|
15
|
+
const raw = cmd.optsWithGlobals() as MitseinGlobalOpts;
|
|
16
|
+
// Commander doesn't support envvar fallback — apply manually
|
|
17
|
+
raw.endpoint = raw.endpoint ?? process.env.MITSEIN_API_URL;
|
|
18
|
+
raw.token = raw.token ?? process.env.MITSEIN_TOKEN;
|
|
19
|
+
return raw;
|
|
16
20
|
}
|
|
17
21
|
|
|
18
22
|
/** HTTP client timeout from `--timeout` (0 = no limit). */
|
package/src/core/errors.ts
CHANGED
|
@@ -62,7 +62,10 @@ export function handleErrors<T extends unknown[]>(
|
|
|
62
62
|
if (e instanceof CliError) {
|
|
63
63
|
consola.error(`Error: ${e.message}`);
|
|
64
64
|
if (e.detail != null && e.detail !== '') {
|
|
65
|
-
|
|
65
|
+
const detailStr = typeof e.detail === 'object'
|
|
66
|
+
? JSON.stringify(e.detail, null, 2)
|
|
67
|
+
: String(e.detail);
|
|
68
|
+
consola.error(detailStr);
|
|
66
69
|
}
|
|
67
70
|
process.exit(e.code);
|
|
68
71
|
}
|