@culvii/cli 0.0.3 → 0.0.5
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/{HelpView-6UXIMG5B.js → HelpView-IV4PD2JG.js} +1 -1
- package/dist/chunk-WB3426JN.js +3 -0
- package/dist/index.js +3 -3
- package/dist/{login-XF2XNUSH.js → login-DFT7D637.js} +1 -1
- package/dist/{logout-XKOUVYZ3.js → logout-OZBKJPQM.js} +1 -1
- package/package.json +1 -1
- package/dist/chunk-KNDIA7WD.js +0 -3
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {p as p$1}from'./chunk-
|
|
2
|
+
import {p as p$1}from'./chunk-WB3426JN.js';import'./chunk-HX54IFSD.js';import {a}from'./chunk-FQVHJUX4.js';import {q,r as r$1}from'./chunk-YKFGEPLO.js';import'./chunk-YPLDPHHD.js';import'./chunk-7UWDMECF.js';import {useEffect}from'react';import {useApp,Box,Text}from'ink';import {jsxs,jsx}from'react/jsx-runtime';function p({children:i}){return jsx(Text,{color:q,children:i})}function s({children:i}){return jsx(Text,{color:r$1,children:i})}var r={Flag:p,Arg:s};function P(){let{exit:i}=useApp();return useEffect(()=>{i();},[i]),jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{flexDirection:"row",gap:1,children:[jsx(a.OutStrong,{children:"culvii"}),jsx(a.Dim,{children:"\u2014 the operating system for governed agents"})]}),jsxs(a.Dim,{children:["0.0.5"," \xB7 https://culvii.dev"]}),jsx(a.Sep,{}),jsxs(Box,{paddingBottom:1,children:[jsx(a.OutStrong,{children:"USAGE"}),jsxs(a.Out,{children:[" culvii ","<command>"," [subcommand] [flags]"]})]}),jsxs(Box,{paddingBottom:1,flexDirection:"column",children:[jsx(a.OutStrong,{children:"CORE COMMANDS"}),jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{flexDirection:"row",children:[jsx(Box,{width:15,children:jsx(Text,{children:jsx(r.Flag,{children:" auth"})})}),jsx(a.Out,{children:"login, rotate keys, inspect identity"})]}),jsxs(Box,{flexDirection:"row",children:[jsx(Box,{width:15,children:jsx(Text,{children:jsx(r.Flag,{children:" init"})})}),jsx(a.Out,{children:"scaffold a new agent from a template"})]}),jsxs(Box,{flexDirection:"row",children:[jsx(Box,{width:15,children:jsx(Text,{children:jsx(r.Flag,{children:" deploy"})})}),jsx(a.Out,{children:"push an agent to an environment"})]})]})]}),jsxs(Box,{paddingBottom:1,flexDirection:"column",children:[jsx(a.OutStrong,{children:"FLAGS"}),jsxs(Box,{flexDirection:"column",children:[jsxs(Box,{flexDirection:"row",children:[jsx(Box,{width:26,children:jsxs(Text,{children:[jsx(r.Flag,{children:" --env "}),jsx(r.Arg,{children:"<name>"})]})}),jsxs(a.Out,{children:["target environment (default: ",p$1,")"]})]}),jsxs(Box,{flexDirection:"row",children:[jsx(Box,{width:26,children:jsx(Text,{children:jsx(r.Flag,{children:" --json"})})}),jsx(a.Out,{children:"machine-readable output"})]}),jsxs(Box,{flexDirection:"row",children:[jsx(Box,{width:26,children:jsx(Text,{children:jsx(r.Flag,{children:" --no-color"})})}),jsx(a.Out,{children:"disable ANSI colors"})]}),jsxs(Box,{flexDirection:"row",children:[jsx(Box,{width:26,children:jsx(Text,{children:jsx(r.Flag,{children:" -h, --help"})})}),jsx(a.Out,{children:"help for any command"})]})]})]}),jsxs(a.Dim,{children:["Run `culvii ","<command>"," --help` for more. Everything here respects your policy bundle."]})]})}
|
|
3
3
|
export{P as HelpView};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {a}from'./chunk-HX54IFSD.js';import {Analytics}from'@segment/analytics-node';var h={CLI_INSTALLED:"cli_installed",CLI_VERSION_VIEWED:"cli_version_viewed",CLI_HELP_VIEWED:"cli_help_viewed",CLI_UNHANDLED_ERROR:"cli_unhandled_error",LOGIN_STARTED:"login_started",LOGIN_SUCCEEDED:"login_succeeded",LOGIN_FAILED:"login_failed",LOGOUT:"logout",DEV_STARTED:"dev_started",DEV_STOPPED:"dev_stopped",DEV_FAILED:"dev_failed",DEPLOY_STARTED:"deploy_started",DEPLOY_SUCCEEDED:"deploy_succeeded",DEPLOY_FAILED:"deploy_failed",DEPLOY_ABORTED:"deploy_aborted",API_KEY_CREATED:"api_key_created",API_KEY_LISTED:"api_key_listed",API_KEY_REVOKED:"api_key_revoked",API_KEY_ROTATED:"api_key_rotated",API_KEY_CREATE_FAILED:"api_key_create_failed",API_KEY_LIST_FAILED:"api_key_list_failed",API_KEY_ROTATE_FAILED:"api_key_rotate_failed",API_KEY_REVOKE_FAILED:"api_key_revoke_failed",TENANT_SWITCHED:"tenant_switched",ENV_SWITCHED:"env_switched",ENV_SWITCH_FAILED:"env_switch_failed",WORKSPACE_CREATED:"workspace_created",WORKSPACE_LISTED:"workspace_listed",TENANT_SWITCH_FAILED:"tenant_switch_failed",WORKSPACE_CREATE_FAILED:"workspace_create_failed",WORKSPACE_LIST_FAILED:"workspace_list_failed",WHOAMI_VIEWED:"whoami_viewed",RENAME_STARTED:"rename_started",RENAME_SUCCEEDED:"rename_succeeded",RENAME_FAILED:"rename_failed",INIT_STARTED:"init_started",INIT_SUCCEEDED:"init_succeeded",INIT_FAILED:"init_failed"},D="byn3jQco5axUIlfeohbQYYPGrZgGpw7A",x=process.env.CULVII_TELEMETRY!=="false",r=x?new Analytics({writeKey:D,flushAt:1,flushInterval:0}):null;function g(){return {surface:"cli",cli_version:"0.0.5",node_version:process.version,os:process.platform,arch:process.arch}}var c=null;async function w(){if(c)return c;try{let{ConfigStore:n}=await import('./config-store-WSXGIIJ4.js');c=(await new n().read({exitOnError:!1})).anonymousId??"unknown";}catch{c="unknown";}return c}var d=null,E=null,f=false;function U(){f=false;}async function y(){if(f)return {userId:d,tenantId:E};try{let{ConfigStore:n}=await import('./config-store-WSXGIIJ4.js'),e=await new n().read({exitOnError:!1}),i=e.contexts[e.active];E=i?.tenant_id??null,d=i?.user_id??e.anonymousId??null;}catch{d=null,E=null;}finally{f=true;}return {userId:d,tenantId:E}}async function C(n,t={},e,i){if(r)try{let o=await y(),a=e??o.userId,s=i!==void 0?i:o.tenantId,_=await w();a?r.track({userId:a,event:n,properties:{...g(),...s?{tenant_id:s}:{},...t}}):r.track({anonymousId:_,event:n,properties:{...g(),...t}});}catch{}}async function V(n,t,e,i={}){await C(n,i,t,e);}async function b(n,t={}){if(r)try{r.identify({userId:n,traits:t});}catch{}}async function F(n,t){if(r)try{r.alias({userId:n,previousId:t});}catch{}}async function K(n,t,e={}){if(r)try{r.group({userId:n,groupId:t,traits:e});}catch{}}var l=null;async function p(){if(r)return l||(l=r.flush({timeout:3e3}).catch(()=>{}).finally(()=>{l=null;}),l)}var u={dev:"development",sandbox:"sandbox",prod:"production"};function k(n){let t=Object.entries(u).find(([,e])=>e===n);return t?t[0]:null}var L=["dev","sandbox","prod"];function W(n){let t=new Set(n.map(k).filter(e=>e!==null));return L.find(e=>t.has(e))??null}var v;function G(n){v=n&&n in u?n:void 0;}function H(){return v}var R="https://api.platform.culvii.com",S={apiBaseUrl:R,clientId:"7fklt2iomn19epdbhpmfblk820",cognitoDomain:"culvii-console.auth.us-east-2.amazoncognito.com"},I=process.env.CULVII_ENV,N=I&&I in u?I:"dev",O={...S,logicalEnvironment:N,scopes:["openid","email","profile"],callbackPorts:[52700,52701,52702,52703,52704,52705,52706,52707,52708,52709],callbackPath:"/callback"};async function M(n){let e=await new a().read(),i=e.contexts[e.active];i||(console.error("Error: Active context key not found in contexts in ~/.culvii/config."),console.error("Please run `culvii login` to authenticate and configure your active context."),await p(),process.exit(1));let o={...i},a$1=n?.env??v;a$1&&(o.environment=a$1);let s=o.environment||"dev";o.environment_id=o.environment_ids?.[s]??o.environment_id,o.workspace_ids&&s in o.workspace_ids&&(o.workspace_id=o.workspace_ids[s]??null),o.workspace_slugs&&s in o.workspace_slugs&&(o.workspace_slug=o.workspace_slugs[s]??null),n?.workspace&&(o.workspace_id=n.workspace);let _=O.apiBaseUrl;return _||(console.error("Error: No API URL found for the configured platform."),await p(),process.exit(1)),{apiUrl:_,context:o}}function j(n){let t=n.environment||"dev",e=n.environment_ids?.[t]??n.environment_id;return {...n.tenant_id?{"x-tenant-id":n.tenant_id}:{},...e?{"x-environment-id":e}:{"x-environment-slug":u[t]}}}
|
|
3
|
+
export{h as a,w as b,U as c,y as d,C as e,V as f,b as g,F as h,K as i,p as j,u as k,k as l,W as m,G as n,H as o,N as p,O as q,M as r,j as s};
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {a as a$5}from'./chunk-JFIFRAAR.js';import {a as a$4,b as b$1,c as c$1}from'./chunk-KZG5CFSB.js';import {n,e,a as a$2,j as j$1,d,f,c,q,r,s,o,k,l}from'./chunk-KNDIA7WD.js';import {a as a$3}from'./chunk-HX54IFSD.js';import'./chunk-57XLDHK6.js';import {x,w,y,z}from'./chunk-YKFGEPLO.js';import {a as a$1}from'./chunk-YPLDPHHD.js';import {a,b}from'./chunk-7UWDMECF.js';import {Command}from'commander';import Ee,{realpathSync,existsSync}from'fs';import {fileURLToPath}from'url';import ge from'react';import {render}from'ink';import tt from'ws';import X,{dirname,join}from'path';import ne from'fs/promises';import {createHash}from'crypto';import {spawn}from'child_process';import hn from'chokidar';import {createRequire}from'module';import Ut from'readline';import ut from'os';import {createInterface}from'readline/promises';import {stdout,stdin}from'process';import {jsx}from'react/jsx-runtime';var Tt=a(F=>{Object.defineProperty(F,"__esModule",{value:true});F.SINGLE_CHILD_SURFACE_COMPONENTS=F.SURFACE_COMPONENT_TYPES=F.SURFACE_COMPONENT_CATALOG=F.SURFACE_SLOTS=F.SURFACE_SLOT_POLICY=void 0;F.getSurfaceBindingPaths=_t;F.validateSurfaceDefinition=It;F.validateSurfaceResource=yn;F.SURFACE_SLOT_POLICY={output:{actions:["navigate"],form:false},wait:{actions:["navigate","node.resume","node.stop"],form:true}};F.SURFACE_SLOTS=Object.keys(F.SURFACE_SLOT_POLICY);F.SURFACE_COMPONENT_CATALOG={Stack:{children:"list"},Row:{children:"list"},Grid:{children:"list"},Card:{children:"single"},Section:{children:"single"},Tabs:{children:"list"},Accordion:{children:"single"},Divider:{children:"none"},Spacer:{children:"none"},Text:{children:"none"},Heading:{children:"none"},Markdown:{children:"none"},Badge:{children:"none"},KeyValue:{children:"none"},Stat:{children:"none"},Avatar:{children:"none"},Icon:{children:"none"},Image:{children:"none"},Code:{children:"none"},Timestamp:{children:"none"},Duration:{children:"none"},Money:{children:"none"},Table:{children:"none"},List:{children:"list"},Tree:{children:"none"},JsonInspector:{children:"none"},FileChip:{children:"none",interaction:"single-action"},StatusPill:{children:"none"},ProgressBar:{children:"none"},Spinner:{children:"none"},ErrorPanel:{children:"none"},Timeline:{children:"list"},Button:{children:"none",interaction:"single-action"},TextField:{children:"none",interaction:"input"},TextArea:{children:"none",interaction:"input"},Select:{children:"none",interaction:"input"},Checkbox:{children:"none",interaction:"input"},RadioGroup:{children:"none",interaction:"input"},DatePicker:{children:"none",interaction:"input"},Form:{children:"list"},DiffView:{children:"none"},ApproveRejectBar:{children:"none",interaction:"multi-action"},EmailMessageCard:{children:"none"},SlackMessageCard:{children:"none"},SlackThread:{children:"list"},CalendarEventCard:{children:"none"},AgentRunPanel:{children:"none"},ToolCallCard:{children:"none"}};F.SURFACE_COMPONENT_TYPES=Object.keys(F.SURFACE_COMPONENT_CATALOG);F.SINGLE_CHILD_SURFACE_COMPONENTS=F.SURFACE_COMPONENT_TYPES.filter(e=>F.SURFACE_COMPONENT_CATALOG[e].children==="single");var Et=300,At=12,dn=new Set(F.SURFACE_COMPONENT_TYPES),un=new Set(["$output","$input","$binary"]),pn=new Set(["text","number","date","datetime","json"]),fn=new Set(["text","textarea","number","email","url","checkbox","select","file"]);function gn(e){return (e.startsWith("/")?e.slice(1):e).split("/",1)[0]}function Ce(e,t){if(Array.isArray(e))for(let n of e)Ce(n,t);else if(e&&typeof e=="object"){let n=e;if(typeof n.path=="string")t.push(n.path);else for(let r of Object.values(n))Ce(r,t);}}function Re(e,t){if(Array.isArray(e)){for(let r of e)Re(r,t);return}if(!e||typeof e!="object")return;let n=e;if("path"in n){typeof n.path!="string"&&t.push("Surface binding path must be a string."),n.format!==void 0&&!pn.has(String(n.format))&&t.push(`Unknown surface binding format "${String(n.format)}".`);return}for(let r of Object.values(n))Re(r,t);}function _t(e){let t=[];for(let n of e.components??[])!n||typeof n!="object"||(Ce(n.props,t),Ce(n.actions,t));return Ce(e.form,t),Array.from(new Set(t))}function It(e,t){let n=[];try{new TextEncoder().encode(JSON.stringify(e)).byteLength>256*1024&&n.push("Surface definition exceeds 256 KiB.");}catch{return ["Surface definition must be JSON serializable."]}if(e?.schema!=="kit.ui/v1"&&n.push('Surface schema must be "kit.ui/v1".'),!Array.isArray(e?.components)||e.components.length===0)return [...n,"Surface requires at least one component."];e.components.length>Et&&n.push(`Surface cannot exceed ${Et} components.`);let r=new Map;for(let o of e.components){if(!o||typeof o!="object"||Array.isArray(o)){n.push("Every surface component must be an object.");continue}let a=o;if(typeof a.id!="string"||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(a.id)||typeof a.type!="string"){n.push("Every surface component requires id and type.");continue}r.has(a.id)&&n.push(`Duplicate component id "${a.id}".`),r.set(a.id,a),dn.has(a.type)||n.push(`Unknown component type "${a.type}".`);let l=F.SURFACE_COMPONENT_CATALOG[a.type];a.props!==void 0&&(!a.props||typeof a.props!="object"||Array.isArray(a.props))&&n.push(`Component "${a.id}" props must be an object.`),a.children!==void 0&&!Array.isArray(a.children)?n.push(`Component "${a.id}" children must be an array.`):a.children?.length&&l?.children==="none"?n.push(`Component "${a.id}" cannot have children.`):a.children&&a.children.length>1&&l?.children==="single"&&n.push(`Component "${a.id}" can have at most one child.`);let c=a.props?.bind;if(c!==void 0&&(l?.interaction!=="input"?n.push(`Component "${a.id}" cannot bind form state.`):(!F.SURFACE_SLOT_POLICY[t].form||typeof c!="string"||!(c==="/$form"||c.startsWith("/$form/")||c.startsWith("$form.")))&&n.push(`Component "${a.id}" requires a wait-surface $form binding.`)),a.actions!==void 0&&(!a.actions||typeof a.actions!="object"||Array.isArray(a.actions))){n.push(`Component "${a.id}" actions must be an object.`);continue}let w=Object.keys(a.actions??{}).length;w&&!["single-action","multi-action"].includes(l?.interaction??"")?n.push(`Component "${a.id}" cannot have actions.`):w>1&&l?.interaction==="single-action"&&n.push(`Component "${a.id}" can have at most one action.`),Re(a.props,n);for(let p of Object.values(a.actions??{})){if(!p||typeof p!="object"||Array.isArray(p)){n.push(`Component "${a.id}" has an invalid action.`);continue}let y=p;if(!["navigate","node.resume","node.stop"].includes(y.type)){n.push(`Unknown surface action "${String(y.type)}".`);continue}F.SURFACE_SLOT_POLICY[t].actions.includes(y.type)||n.push(`Action "${y.type}" is not allowed on "${t}" surfaces.`),y.type==="navigate"&&(!y.href||typeof y.href!="object"||typeof y.href.path!="string")&&n.push("Navigate actions require an href binding."),Re(y,n);}}(typeof e.root!="string"||!r.has(e.root))&&n.push(`Surface root "${String(e.root)}" is missing.`);let i=new Set,s=new Set,u=(o,a)=>{if(a>At)return void n.push(`Surface component depth exceeds ${At}.`);if(s.has(o))return void n.push(`Surface component cycle includes "${o}".`);if(i.has(o))return;let l=r.get(o);if(l){s.add(o);for(let c of Array.isArray(l.children)?l.children:[]){if(typeof c!="string"){n.push(`Component "${o}" has a non-string child reference.`);continue}r.has(c)?u(c,a+1):n.push(`Component "${o}" references missing child "${c}".`);}s.delete(o),i.add(o);}};typeof e.root=="string"&&u(e.root,1);for(let o of r.keys())i.has(o)||n.push(`Component "${o}" is unreachable from root.`);for(let o of _t(e)){let a=gn(o);a==="$form"&&!F.SURFACE_SLOT_POLICY[t].form?n.push(`Binding "${o}" is only allowed on wait surfaces.`):a!=="$form"&&!un.has(a)&&n.push(`Invalid surface binding path "${o}".`);}if(e.form!==void 0)if(F.SURFACE_SLOT_POLICY[t].form||n.push("Forms are only allowed on wait surfaces."),!Array.isArray(e.form?.fields))n.push("Surface form fields must be an array.");else {let o=new Set;for(let a of e.form.fields){if(!a||typeof a!="object"||Array.isArray(a)){n.push("Every surface form field must be an object.");continue}let l=a,c=l?.name,w=l?.type;typeof c!="string"||!c||o.has(c)?n.push(`Surface form field name "${String(c)}" is invalid or duplicated.`):o.add(c),fn.has(String(w))||n.push(`Unknown surface form field type "${String(w)}".`),(typeof l.label!="string"||!l.label.trim())&&n.push(`Surface form field "${String(c)}" requires a label.`),w==="file"&&"default"in l&&n.push(`File field "${String(c)}" cannot have a default binding.`),w==="file"&&(l.maxFiles!==void 0&&(!Number.isInteger(l.maxFiles)||Number(l.maxFiles)<1||Number(l.maxFiles)>5)&&n.push(`File field "${String(c)}" maxFiles must be between 1 and 5.`),l.maxBytes!==void 0&&(!Number.isInteger(l.maxBytes)||Number(l.maxBytes)<1||Number(l.maxBytes)>10*1024*1024)&&n.push(`File field "${String(c)}" maxBytes exceeds platform limits.`),l.accept!==void 0&&(!Array.isArray(l.accept)||l.accept.some(p=>typeof p!="string"||!/^[a-z0-9.+-]+\/(?:[a-z0-9.+-]+|\*)$/i.test(p)))&&n.push(`File field "${String(c)}" has invalid MIME types.`)),w==="select"&&(!Array.isArray(l.options)||l.options.length===0?n.push(`Select field "${String(c)}" requires options.`):l.options.some(p=>!p||typeof p!="object"||typeof p.label!="string"||typeof p.value!="string")&&n.push(`Select field "${String(c)}" has invalid options.`));}Re(e.form,n);}return Array.from(new Set(n))}function yn(e){let t=e;if(!t||typeof t!="object")return ["Surface must be an object."];let n=[];return (typeof t.id!="string"||!/^[a-z0-9][a-z0-9-]{0,62}$/.test(t.id))&&n.push("Surface requires a kebab-case id."),(typeof t.name!="string"||!t.name.trim())&&n.push("Surface requires a name."),F.SURFACE_SLOTS.includes(t.slot)?n.push(...It(t.definition,t.slot)):n.push(`Surface requires slot ${F.SURFACE_SLOTS.map(r=>`"${r}"`).join(" or ")}.`),Array.from(new Set(n))}});var St=a(ke=>{var wn=ke&&ke.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:true,get:function(){return t[n]}}),Object.defineProperty(e,r,i);}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n];})),mn=ke&&ke.__exportStar||function(e,t){for(var n in e)n!=="default"&&!Object.prototype.hasOwnProperty.call(t,n)&&wn(t,e,n);};Object.defineProperty(ke,"__esModule",{value:true});mn(Tt(),ke);});var Ue=class extends Error{constructor(){super("401 Unauthorized"),this.name="UnauthorizedError";}};function ln(e,t=Date.now()){return e-t<3e4}async function B(e$1){let t=new a$4,r=await(async()=>await t.withLock(async()=>{b$1.info("Tokens read from disk for auth check");let i=await t.get();if(i||(b$1.error("No tokens found on disk"),render(ge.createElement(c$1,{state:{type:"login_error",message:"Not logged in",detail:"run `culvii login`"}})),await e(a$2.LOGIN_FAILED,{reason:"session_expired"}),await j$1(),process.exit(1)),!ln(i.expiresAt))return b$1.info("Access token valid, skipping refresh"),i.accessToken;b$1.info("Access token expired, attempting refresh");let s=`https://${q.cognitoDomain}/oauth2/token`,u=new URLSearchParams;u.set("grant_type","refresh_token"),u.set("refresh_token",i.refreshToken),u.set("client_id",q.clientId);let o;try{o=await fetch(s,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:u.toString()});}catch(w){b$1.error("Network error during refresh",{error:w.message}),render(ge.createElement(c$1,{state:{type:"login_error",message:"Refresh failed",detail:"Cannot reach auth server \u2014 check your connection"}})),await e(a$2.LOGIN_FAILED,{reason:"session_expired"}),await j$1(),process.exit(1);}let a=await o.json();(!o.ok||a.error==="invalid_grant")&&(b$1.warn("Refresh failed with invalid_grant"),await t.delete(),render(ge.createElement(c$1,{state:{type:"login_error",message:"Session expired",detail:"run `culvii login` to authenticate"}})),await e(a$2.LOGIN_FAILED,{reason:"session_expired"}),await j$1(),process.exit(1));let l=Date.now(),c=l+a.expires_in*1e3;return b$1.info("Refresh succeeded",{expiresAt:c}),await t.set({accessToken:a.access_token,refreshToken:a.refresh_token||i.refreshToken,idToken:a.id_token||i.idToken,expiresAt:c,tokenType:"Bearer",scope:i.scope,issuedAt:l,issuer:i.issuer}),a.access_token}))();try{await e$1(r);}catch(i){if(!(i instanceof Ue))throw i;b$1.info("Mid-session 401 detected, attempting refresh");let s=await t.withLock(async()=>{b$1.info("Tokens read from disk for retry");let u=await t.get();u||(b$1.error("No tokens found on disk during retry"),render(ge.createElement(c$1,{state:{type:"login_error",message:"Not logged in",detail:"run `culvii login`"}})),await e(a$2.LOGIN_FAILED,{reason:"session_expired"}),await j$1(),process.exit(1)),b$1.info("Access token expired (forced by 401), attempting refresh");let o=`https://${q.cognitoDomain}/oauth2/token`,a=new URLSearchParams;a.set("grant_type","refresh_token"),a.set("refresh_token",u.refreshToken),a.set("client_id",q.clientId);let l;try{l=await fetch(o,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:a.toString()});}catch(y){b$1.error("Network error during refresh retry",{error:y.message}),render(ge.createElement(c$1,{state:{type:"login_error",message:"Refresh failed",detail:"Cannot reach auth server \u2014 check your connection"}})),await e(a$2.LOGIN_FAILED,{reason:"session_expired"}),await j$1(),process.exit(1);}let c=await l.json();(!l.ok||c.error==="invalid_grant")&&(b$1.warn("Refresh retry failed with invalid_grant"),await t.delete(),render(ge.createElement(c$1,{state:{type:"login_error",message:"Session expired",detail:"run `culvii login` to authenticate"}})),await e(a$2.LOGIN_FAILED,{reason:"session_expired"}),await j$1(),process.exit(1));let w=Date.now(),p=w+c.expires_in*1e3;return b$1.info("Refresh retry succeeded",{expiresAt:p}),await t.set({accessToken:c.access_token,refreshToken:c.refresh_token||u.refreshToken,idToken:c.id_token||u.idToken,expiresAt:p,tokenType:"Bearer",scope:u.scope,issuedAt:w,issuer:u.issuer}),c.access_token});try{b$1.info("Retry after refresh succeeded"),await e$1(s);}catch(u){throw u instanceof Ue&&(b$1.error("Retry after refresh failed (still 401)"),await t.withLock(async()=>{await t.delete();}),render(ge.createElement(c$1,{state:{type:"login_error",message:"Session invalidated",detail:"run `culvii login` to authenticate"}})),await e(a$2.LOGIN_FAILED,{reason:"session_expired"}),await j$1(),process.exit(1)),u}}}async function et(){let e=new a$4;return e.withLock(async()=>{let t=await e.get();if(!t)return null;let n=`https://${q.cognitoDomain}/oauth2/token`,r=new URLSearchParams;r.set("grant_type","refresh_token"),r.set("refresh_token",t.refreshToken),r.set("client_id",q.clientId);let i;try{i=await fetch(n,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r.toString()});}catch(a){return b$1.error("Network error during silent refresh",{error:a.message}),null}let s=await i.json();if(!i.ok||s.error==="invalid_grant")return b$1.warn("Silent refresh failed",{error:s.error}),null;let u=Date.now(),o=u+s.expires_in*1e3;return await e.set({accessToken:s.access_token,refreshToken:s.refresh_token||t.refreshToken,idToken:s.id_token||t.idToken,expiresAt:o,tokenType:"Bearer",scope:t.scope,issuedAt:u,issuer:t.issuer}),s.access_token})}async function Y(e){let t=await e.text();try{let n=JSON.parse(t);if(n.error)return n.error}catch{}return t}async function j(e,t,n={}){let{skipEnvironmentHeader:r,...i}=n,u=await new a$3().read({exitOnError:false}),o$1=u.contexts[u.active],a=o$1?.tenant_id,l=o$1?.environment||"dev",c=o()??l,w=o$1?.environment_ids?.[c]??(c===l?o$1?.environment_id:void 0),p=k[c],y=r?{}:w?{"x-environment-id":w}:{"x-environment-slug":p},k$1={Authorization:`Bearer ${t}`,...a?{"x-tenant-id":a}:{},...y,...i.headers||{}};return fetch(e,{...i,headers:k$1})}function kt(){let e=a$1();return e.isTTY&&!e.isCI&&e.supportsColor&&e.supportsUnicode}function ht(e$1){let t=e$1.command("workspace").description("Workspace commands").option("--env <env>","Target environment (sandbox or prod)");t.command("create").description("Create a new workspace").requiredOption("--name <name>","Workspace name").requiredOption("--slug <slug>","Workspace slug").action(async n=>{if(kt()){let u=function(){let[o,a]=ge.useState({type:"loading"});return ge.useEffect(()=>(s$1=a,()=>{s$1=null;}),[]),ge.createElement(i,{state:o})};let{WorkspaceCreateView:i}=await import('./WorkspaceView-RNFALIPM.js'),s$1=null;await V(Promise.resolve(ge.createElement(u))),await B(async o=>{let{apiUrl:a,context:l}=await r({env:t.opts().env}),c=s(l);try{let w=await j(`${a}/api/workspaces`,o,{method:"POST",headers:{...c,"Content-Type":"application/json"},body:JSON.stringify({name:n.name,slug:n.slug,tenantId:l.tenant_id})});if(!w.ok){let A=await Y(w);s$1?.({type:"error",message:"Failed to create workspace",detail:`Server responded with ${w.status}: ${A}`});let{userId:v,tenantId:D}=await d();v?await f(a$2.WORKSPACE_CREATE_FAILED,v,D,{error_class:"ApiError",slug:n.slug,env:l.environment}):await e(a$2.WORKSPACE_CREATE_FAILED,{error_class:"ApiError",slug:n.slug,env:l.environment}),await j$1();return}let p=await w.json();s$1?.({type:"success",id:p?.data?.workspaceId,slug:p?.data?.workspaceSlug||n.slug,name:n.name});let{userId:y,tenantId:k}=await d();y?await f(a$2.WORKSPACE_CREATED,y,k,{slug:n.slug,env:l.environment}):await e(a$2.WORKSPACE_CREATED,{slug:n.slug,env:l.environment}),await j$1();}catch(w){s$1?.({type:"error",message:"Unexpected error",detail:w.message});let{userId:p,tenantId:y}=await d();p?await f(a$2.WORKSPACE_CREATE_FAILED,p,y,{error_class:w?.constructor?.name,env:l.environment}):await e(a$2.WORKSPACE_CREATE_FAILED,{error_class:w?.constructor?.name,env:l.environment}),await j$1();}});return}await B(async i=>{let{apiUrl:s$1,context:u}=await r({env:t.opts().env}),o=s(u);console.log(`tenant: ${u.tenant_slug} | workspace: N/A | env: ${u.environment}`);try{let a=await j(`${s$1}/api/workspaces`,i,{method:"POST",headers:{...o,"Content-Type":"application/json"},body:JSON.stringify({name:n.name,slug:n.slug,tenantId:u.tenant_id})});if(!a.ok){let p=await Y(a);console.error(`Error: Failed to create workspace. Server responded with ${a.status}: ${p}`);let{userId:y,tenantId:k}=await d();y?await f(a$2.WORKSPACE_CREATE_FAILED,y,k,{error_class:"ApiError",slug:n.slug,env:u.environment}):await e(a$2.WORKSPACE_CREATE_FAILED,{error_class:"ApiError",slug:n.slug,env:u.environment}),await j$1(),process.exit(1);}let l=await a.json();console.log(`${w} Workspace created successfully.`),console.log(` ID: ${l?.data?.workspaceId}`),l?.data?.workspaceSlug&&console.log(` Slug: ${l?.data?.workspaceSlug}`);let{userId:c,tenantId:w$1}=await d();c?await f(a$2.WORKSPACE_CREATED,c,w$1,{slug:n.slug,env:u.environment}):await e(a$2.WORKSPACE_CREATED,{slug:n.slug,env:u.environment}),await j$1();}catch(a){console.error(`Error: Network or unexpected error: ${a.message}`);let{userId:l,tenantId:c}=await d();l?await f(a$2.WORKSPACE_CREATE_FAILED,l,c,{error_class:a?.constructor?.name,env:u.environment}):await e(a$2.WORKSPACE_CREATE_FAILED,{error_class:a?.constructor?.name,env:u.environment}),await j$1(),process.exit(1);}});}),t.command("list").description("List workspaces").action(async()=>{if(kt()){let s$1=function(){let[u,o]=ge.useState({type:"loading"});return ge.useEffect(()=>(i=o,()=>{i=null;}),[]),ge.createElement(r$1,{state:u})};let{WorkspaceListView:r$1}=await import('./WorkspaceView-RNFALIPM.js'),i=null;await V(Promise.resolve(ge.createElement(s$1))),await B(async u=>{let{apiUrl:o,context:a}=await r({env:t.opts().env}),l=s(a);try{let c=await j(`${o}/api/workspaces?tenantId=${a.tenant_id}`,u,{headers:l});if(!c.ok){let A=await Y(c);i?.({type:"error",message:"Failed to list workspaces",detail:`Server responded with ${c.status}: ${A}`});let{userId:v,tenantId:D}=await d();v?await f(a$2.WORKSPACE_LIST_FAILED,v,D,{error_class:"ApiError",env:a.environment}):await e(a$2.WORKSPACE_LIST_FAILED,{error_class:"ApiError",env:a.environment}),await j$1();return}let p=(await c.json())?.data?.workspaces;if(!Array.isArray(p)){i?.({type:"error",message:"Unexpected response format"});let{userId:A,tenantId:v}=await d();A?await f(a$2.WORKSPACE_LIST_FAILED,A,v,{error_class:"UnexpectedResponse",env:a.environment}):await e(a$2.WORKSPACE_LIST_FAILED,{error_class:"UnexpectedResponse",env:a.environment}),await j$1();return}i?.({type:"success",workspaces:p.map(A=>({id:A.id,name:A.name,slug:A.slug??""}))});let{userId:y,tenantId:k}=await d();y?await f(a$2.WORKSPACE_LISTED,y,k,{env:a.environment}):await e(a$2.WORKSPACE_LISTED,{env:a.environment}),await j$1();}catch(c){i?.({type:"error",message:"Unexpected error",detail:c.message});let{userId:w,tenantId:p}=await d();w?await f(a$2.WORKSPACE_LIST_FAILED,w,p,{error_class:c?.constructor?.name,env:a.environment}):await e(a$2.WORKSPACE_LIST_FAILED,{error_class:c?.constructor?.name,env:a.environment}),await j$1();}});return}await B(async r$1=>{let{apiUrl:i,context:s$1}=await r({env:t.opts().env}),u=s(s$1);console.log(`tenant: ${s$1.tenant_slug} | workspace: N/A | env: ${s$1.environment}`);try{let o=await j(`${i}/api/workspaces?tenantId=${s$1.tenant_id}`,r$1,{headers:u});if(!o.ok){let p=await Y(o);console.error(`Error: Failed to list workspaces. Server responded with ${o.status}: ${p}`);let{userId:y,tenantId:k}=await d();y?await f(a$2.WORKSPACE_LIST_FAILED,y,k,{error_class:"ApiError",env:s$1.environment}):await e(a$2.WORKSPACE_LIST_FAILED,{error_class:"ApiError",env:s$1.environment}),await j$1(),process.exit(1);}let l=(await o.json())?.data?.workspaces;if(!Array.isArray(l)){console.error("Error: Unexpected response format");let{userId:p,tenantId:y}=await d();p?await f(a$2.WORKSPACE_LIST_FAILED,p,y,{error_class:"UnexpectedResponse",env:s$1.environment}):await e(a$2.WORKSPACE_LIST_FAILED,{error_class:"UnexpectedResponse",env:s$1.environment}),await j$1(),process.exit(1);}for(let p of l)console.log(`${p.id} ${p.name} ${p.slug}`);let{userId:c,tenantId:w}=await d();c?await f(a$2.WORKSPACE_LISTED,c,w,{env:s$1.environment}):await e(a$2.WORKSPACE_LISTED,{env:s$1.environment}),await j$1();}catch(o){console.error(`Error: Network or unexpected error: ${o.message}`);let{userId:a,tenantId:l}=await d();a?await f(a$2.WORKSPACE_LIST_FAILED,a,l,{error_class:o?.constructor?.name,env:s$1.environment}):await e(a$2.WORKSPACE_LIST_FAILED,{error_class:o?.constructor?.name,env:s$1.environment}),await j$1(),process.exit(1);}});});}function nt(e,t,n){let r=null,i=0,s=false,u=[],o=new Map,a=null,l=null,c=0,w=[1e3,2e3,4e3,8e3,16e3];function p(){a&&(clearInterval(a),a=null),l&&(clearTimeout(l),l=null),c=0;}function y(){p(),a=setInterval(()=>{if(!r||r.readyState!==tt.OPEN)return;let R=Date.now().toString()+"-"+Math.random().toString();r.send(JSON.stringify({type:"client-ping",requestId:R})),l=setTimeout(()=>{c++,c>=2&&(b$1.warn("devSync WebSocket dead (missed 2 pongs), terminating"),p(),r?.terminate());},5e3);},2e4);}function k(R){R.removeAllListeners(),R.on("error",()=>{});try{R.terminate();}catch(L){b$1.warn("devSync error terminating stale socket",{error:L.message});}}let A=0;async function v(){if(s)return;let R=++A,L;try{L=await t();}catch(I){b$1.error("devSync failed to obtain headers for connection",{error:I.message}),R===A&&D();return}if(s||R!==A)return;r&&k(r);let f=new tt(e,{headers:L});r=f,f.on("open",()=>{if(r===f){i=0,b$1.info("devSync WebSocket connected",{url:e}),n.onOpen();for(let I of u)f.send(JSON.stringify(I));u=[],y();}}),f.on("message",I=>{if(r!==f)return;let E=Buffer.isBuffer(I)?I.toString("utf-8"):I instanceof ArrayBuffer?Buffer.from(I).toString("utf-8"):Buffer.concat(I).toString("utf-8"),g;try{g=JSON.parse(E);}catch{b$1.warn("Received invalid JSON from devSync",{raw:E});return}if(g.ok===true&&g.slug&&typeof g.warning=="string"){n.onWarning?.(g.slug,g.warning);return}if(g.type==="session-probe"&&typeof g.requestId=="string"){f.send(JSON.stringify({type:"session-pong",requestId:g.requestId}));return}if(g.type==="client-pong"){l&&(clearTimeout(l),l=null),c=0;return}if(g.ok===true&&g.slug&&g.type==="validation-error"){n.onValidationErrorAck?.(g.slug);return}if(g.ok===true&&g.slug){g.resourceId&&o.set(g.slug,g.resourceId),n.onAck(g.slug,g.resourceId,g.orphaned===true);return}if(g.ok===false&&g.slug){n.onError(g.slug,g.error||"Unknown error");return}if(g.ok===false&&!g.slug){n.onFatal(g.error||"Fatal error from server"),s=true,p(),f.close();return}}),f.on("unexpected-response",(I,E)=>{if(r===f){if(E.statusCode===401){b$1.error("devSync credentials rejected (401)"),s=true,p(),f.terminate(),n.onAuthFailure?n.onAuthFailure():n.onFatal("Credentials rejected by server (401)");return}b$1.warn("devSync unexpected handshake response",{statusCode:E.statusCode}),p(),f.terminate(),D();}}),f.on("close",I=>{r!==f||s||(b$1.warn("devSync WebSocket closed",{code:I}),p(),D());}),f.on("error",I=>{r===f&&b$1.error("devSync WebSocket error",{error:I.message});});}function D(){if(p(),s)return;if(i>=w.length){let f=`devSync PERMANENT FAILURE: giving up after ${w.length} retries`;b$1.error(f,{retryCount:i,retryDelaysMs:w}),n.onFatal(f),s=true;return}let R=w[i];i++;let L=w.length-i;b$1.info(`devSync reconnecting in ${R}ms (attempt ${i}/${w.length}, ${L} left before permanent failure)`),setTimeout(()=>{v();},R);}function $(R){r&&r.readyState===tt.OPEN?r.send(JSON.stringify(R)):u.push(R);}function M(){s=true,p(),r&&k(r),b$1.info("devSync WebSocket closed by client");}function S(){s||(p(),i=0,r&&k(r),v());}return v(),{send:$,close:M,reconnectNow:S}}var Ct=b(St(),1);var Tn=fileURLToPath(import.meta.url),Sn=dirname(Tn),Dn=join(Sn,"lib","evaluator.js"),Cn=createRequire(import.meta.url),Rn=Cn.resolve("tsx/cli");function Pe(e){return (0, Ct.validateSurfaceResource)(e)}function st(e){if(Array.isArray(e))return e.map(st);if(e!==null&&typeof e=="object"){let t={};for(let n of Object.keys(e).sort())t[n]=st(e[n]);return t}return e}function xn(e){if(!e||typeof e!="object")return e;let t={...e};return Array.isArray(t.nodes)&&(t.nodes=t.nodes.map(({id:n,...r})=>r)),t}function Ln(e){return createHash("sha256").update(JSON.stringify(st(xn(e)))).digest("hex")}function ye(e){return (Array.isArray(e?.nodes)?e.nodes:[]).filter(n=>n?.type==="core.agent").map(n=>n?.nodeParams?.agentReferenceKey??n?.nodeParams?.agentId).filter(n=>typeof n=="string"&&!n.startsWith("agt_"))}function Fe(e){return (Array.isArray(e?.nodes)?e.nodes:[]).flatMap(n=>["output","wait"].map(r=>n?.ui?.[r]).filter(r=>r?.kind==="custom"&&typeof r.surfaceKey=="string").map(r=>({surfaceKey:r.surfaceKey,...Number.isInteger(r.version)?{version:r.version}:{}})))}function $n(e){return Array.isArray(e)?e:e&&typeof e=="object"?Object.entries(e).map(([t,n])=>n&&typeof n=="object"&&!Array.isArray(n)?{name:t,...n}:n):[]}function Ie(e){return $n(e?.tools).filter(t=>t&&typeof t=="object"&&!Array.isArray(t)).map(t=>({referenceKey:t.workflowReferenceKey??t.workflowId,toolName:t.name,triggerNodeName:t.triggerNodeName})).filter(t=>typeof t.referenceKey=="string"&&!t.referenceKey.startsWith("wfl_"))}function Te(e){return Ie(e).map(t=>t.referenceKey)}function bn(e){return typeof e?.type=="string"&&e.type!=="manualTrigger"&&e.type.endsWith("Trigger")}function On(e,t){return e.get(t)??e.get(W(t))}function Rt(e){let t=new Set,n=[];for(let r of e.values())t.has(r.id)||(t.add(r.id),n.push(r));return n}function xt(e,t){let n=typeof e?.id=="string"?e.id:"unknown";if(Ie(e).length>0)return {id:n,definition:e};let r=n==="unknown"?void 0:On(t,n);return r?{id:n,definition:r.definition}:e&&typeof e=="object"&&!Array.isArray(e)?{id:n,definition:e}:null}function at(e,t){let n=[e];for(let r of e.definition?.secondaryAgents??[]){let i=xt(r,t);i&&n.push(i);}return n}function We(e){let t=new Map,n=new Map;for(let s of e){let u=s.definition?.id;typeof u=="string"&&(s.type==="agent"?(t.set(u,{id:u,definition:s.definition}),t.set(W(u),{id:u,definition:s.definition})):s.type==="workflow"&&(n.set(u,s.definition),n.set(W(u),s.definition)));}let r=new Set;for(let s of Rt(t))for(let u of at(s,t))for(let o of Te(u.definition))r.add(W(o));let i=new Set;for(let s of r){let u=n.get(s);if(u)for(let o of ye(u))i.add(W(o));}for(let s of i){let u=t.get(s);if(u){if(Ie(u.definition).length>0)return `agent '${u.id}' cannot define workflow tools when invoked by an agent workflow tool.`;for(let o of u.definition?.secondaryAgents??[]){let a=xt(o,t);if(a&&Ie(a.definition).length>0)return `secondary agent '${a.id}' referenced by agent '${u.id}' cannot define workflow tools when '${u.id}' is invoked by an agent workflow tool.`}}}return null}function Me(e){let t=new Map,n=new Map;for(let i of e){let s=i.definition?.id;typeof s=="string"&&(i.type==="agent"?(t.set(s,{id:s,definition:i.definition}),t.set(W(s),{id:s,definition:i.definition})):i.type==="workflow"&&(n.set(s,i.definition),n.set(W(s),i.definition)));}let r=new Set;for(let i of n.values())for(let s of ye(i))r.add(W(s));for(let i of r){let s=t.get(i);if(!s)continue;let u=at(s,t);for(let o of u)for(let a of Ie(o.definition)){let l=n.get(a.referenceKey)??n.get(W(a.referenceKey));if(!(!l||ye(l).length===0))return `workflow tool '${a.toolName??"unknown"}' on agent '${o.id}' cannot reference workflow '${a.referenceKey}' because '${s.id}' is invoked by a workflow and the target workflow contains an agent node.`}}return null}function je(e){let t=new Map,n=new Map;for(let r of e){let i=r.definition?.id;typeof i=="string"&&(r.type==="agent"?(t.set(i,{id:i,definition:r.definition}),t.set(W(i),{id:i,definition:r.definition})):r.type==="workflow"&&(n.set(i,r.definition),n.set(W(i),r.definition)));}for(let r of Rt(t))for(let i of at(r,t))for(let s of Ie(i.definition)){let u=n.get(s.referenceKey)??n.get(W(s.referenceKey));if(!u)continue;let o=Array.isArray(u.nodes)?u.nodes:[],a=o.find(bn);if(a)return `workflow tool '${s.toolName??"unknown"}' on agent '${i.id}' references workflow '${s.referenceKey}' with non-manual trigger '${a.name??a.type}'.`;if(s.triggerNodeName){if(o.find(w=>w?.name===s.triggerNodeName)?.type==="manualTrigger")continue;return `workflow tool '${s.toolName??"unknown"}' on agent '${i.id}' must use a manual trigger in workflow '${s.referenceKey}'.`}let l=o.filter(c=>c?.type==="manualTrigger");if(l.length!==1)return l.length===0?`workflow tool '${s.toolName??"unknown"}' on agent '${i.id}' references workflow '${s.referenceKey}' without a manual trigger.`:`workflow tool '${s.toolName??"unknown"}' on agent '${i.id}' must specify triggerNodeName because workflow '${s.referenceKey}' has multiple manual triggers.`}return null}function Ve(e){let t=[],n=(r,i)=>{let s=i&&typeof i=="object"&&!Array.isArray(i)?i.credentialId:void 0;(typeof s!="string"||!s.trim())&&t.push(`agent '${r}' model must include a credentialId \u2014 use model: { provider, modelId, credentialId }.`);};e?.modelConfig!==void 0&&e?.modelConfig!==null&&n(e?.id,e.modelConfig);for(let r of e?.secondaryAgents??[])r?.modelConfig!==void 0&&r?.modelConfig!==null&&n(r?.id??e?.id,r.modelConfig);return t}function Ke(e){let t=new Map;for(let i of e){let s=i.definition?.id;if(!s)continue;let u=i.type==="agent"?Te(i.definition).map(o=>`workflow:${o}`):i.type==="workflow"?ye(i.definition).map(o=>`agent:${o}`):[];t.set(`${i.type}:${s}`,u);}let n=null;function r(i,s){if(!n)for(let u of t.get(i)??[]){if(!t.has(u))continue;let o=[...s,u];if(s.length>=3){n=`Unsupported nested SDK reference chain: ${o.join(" -> ")}. Only workflow -> agent -> workflow or agent -> workflow -> agent is supported.`;return}r(u,o);}}for(let i of t.keys())r(i,[i]);return n}async function Nn(e){try{let r=X.join(e,"culvii.yaml"),s=(await ne.readFile(r,"utf-8")).split(`
|
|
2
|
+
import {a as a$5}from'./chunk-JFIFRAAR.js';import {a as a$4,b as b$1,c as c$1}from'./chunk-KZG5CFSB.js';import {n,e,a as a$2,j as j$1,d,f,c,q,r,s,o,k,l}from'./chunk-WB3426JN.js';import {a as a$3}from'./chunk-HX54IFSD.js';import'./chunk-57XLDHK6.js';import {x,w,y,z}from'./chunk-YKFGEPLO.js';import {a as a$1}from'./chunk-YPLDPHHD.js';import {a,b}from'./chunk-7UWDMECF.js';import {Command}from'commander';import Ee,{realpathSync,existsSync}from'fs';import {fileURLToPath}from'url';import ge from'react';import {render}from'ink';import tt from'ws';import X,{dirname,join}from'path';import ne from'fs/promises';import {createHash}from'crypto';import {spawn}from'child_process';import hn from'chokidar';import {createRequire}from'module';import Ut from'readline';import ut from'os';import {createInterface}from'readline/promises';import {stdout,stdin}from'process';import {jsx}from'react/jsx-runtime';var Tt=a(F=>{Object.defineProperty(F,"__esModule",{value:true});F.SINGLE_CHILD_SURFACE_COMPONENTS=F.SURFACE_COMPONENT_TYPES=F.SURFACE_COMPONENT_CATALOG=F.SURFACE_SLOTS=F.SURFACE_SLOT_POLICY=void 0;F.getSurfaceBindingPaths=_t;F.validateSurfaceDefinition=It;F.validateSurfaceResource=yn;F.SURFACE_SLOT_POLICY={output:{actions:["navigate"],form:false},wait:{actions:["navigate","node.resume","node.stop"],form:true}};F.SURFACE_SLOTS=Object.keys(F.SURFACE_SLOT_POLICY);F.SURFACE_COMPONENT_CATALOG={Stack:{children:"list"},Row:{children:"list"},Grid:{children:"list"},Card:{children:"single"},Section:{children:"single"},Tabs:{children:"list"},Accordion:{children:"single"},Divider:{children:"none"},Spacer:{children:"none"},Text:{children:"none"},Heading:{children:"none"},Markdown:{children:"none"},Badge:{children:"none"},KeyValue:{children:"none"},Stat:{children:"none"},Avatar:{children:"none"},Icon:{children:"none"},Image:{children:"none"},Code:{children:"none"},Timestamp:{children:"none"},Duration:{children:"none"},Money:{children:"none"},Table:{children:"none"},List:{children:"list"},Tree:{children:"none"},JsonInspector:{children:"none"},FileChip:{children:"none",interaction:"single-action"},StatusPill:{children:"none"},ProgressBar:{children:"none"},Spinner:{children:"none"},ErrorPanel:{children:"none"},Timeline:{children:"list"},Button:{children:"none",interaction:"single-action"},TextField:{children:"none",interaction:"input"},TextArea:{children:"none",interaction:"input"},Select:{children:"none",interaction:"input"},Checkbox:{children:"none",interaction:"input"},RadioGroup:{children:"none",interaction:"input"},DatePicker:{children:"none",interaction:"input"},Form:{children:"list"},DiffView:{children:"none"},ApproveRejectBar:{children:"none",interaction:"multi-action"},EmailMessageCard:{children:"none"},SlackMessageCard:{children:"none"},SlackThread:{children:"list"},CalendarEventCard:{children:"none"},AgentRunPanel:{children:"none"},ToolCallCard:{children:"none"}};F.SURFACE_COMPONENT_TYPES=Object.keys(F.SURFACE_COMPONENT_CATALOG);F.SINGLE_CHILD_SURFACE_COMPONENTS=F.SURFACE_COMPONENT_TYPES.filter(e=>F.SURFACE_COMPONENT_CATALOG[e].children==="single");var Et=300,At=12,dn=new Set(F.SURFACE_COMPONENT_TYPES),un=new Set(["$output","$input","$binary"]),pn=new Set(["text","number","date","datetime","json"]),fn=new Set(["text","textarea","number","email","url","checkbox","select","file"]);function gn(e){return (e.startsWith("/")?e.slice(1):e).split("/",1)[0]}function Ce(e,t){if(Array.isArray(e))for(let n of e)Ce(n,t);else if(e&&typeof e=="object"){let n=e;if(typeof n.path=="string")t.push(n.path);else for(let r of Object.values(n))Ce(r,t);}}function Re(e,t){if(Array.isArray(e)){for(let r of e)Re(r,t);return}if(!e||typeof e!="object")return;let n=e;if("path"in n){typeof n.path!="string"&&t.push("Surface binding path must be a string."),n.format!==void 0&&!pn.has(String(n.format))&&t.push(`Unknown surface binding format "${String(n.format)}".`);return}for(let r of Object.values(n))Re(r,t);}function _t(e){let t=[];for(let n of e.components??[])!n||typeof n!="object"||(Ce(n.props,t),Ce(n.actions,t));return Ce(e.form,t),Array.from(new Set(t))}function It(e,t){let n=[];try{new TextEncoder().encode(JSON.stringify(e)).byteLength>256*1024&&n.push("Surface definition exceeds 256 KiB.");}catch{return ["Surface definition must be JSON serializable."]}if(e?.schema!=="kit.ui/v1"&&n.push('Surface schema must be "kit.ui/v1".'),!Array.isArray(e?.components)||e.components.length===0)return [...n,"Surface requires at least one component."];e.components.length>Et&&n.push(`Surface cannot exceed ${Et} components.`);let r=new Map;for(let o of e.components){if(!o||typeof o!="object"||Array.isArray(o)){n.push("Every surface component must be an object.");continue}let a=o;if(typeof a.id!="string"||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(a.id)||typeof a.type!="string"){n.push("Every surface component requires id and type.");continue}r.has(a.id)&&n.push(`Duplicate component id "${a.id}".`),r.set(a.id,a),dn.has(a.type)||n.push(`Unknown component type "${a.type}".`);let l=F.SURFACE_COMPONENT_CATALOG[a.type];a.props!==void 0&&(!a.props||typeof a.props!="object"||Array.isArray(a.props))&&n.push(`Component "${a.id}" props must be an object.`),a.children!==void 0&&!Array.isArray(a.children)?n.push(`Component "${a.id}" children must be an array.`):a.children?.length&&l?.children==="none"?n.push(`Component "${a.id}" cannot have children.`):a.children&&a.children.length>1&&l?.children==="single"&&n.push(`Component "${a.id}" can have at most one child.`);let c=a.props?.bind;if(c!==void 0&&(l?.interaction!=="input"?n.push(`Component "${a.id}" cannot bind form state.`):(!F.SURFACE_SLOT_POLICY[t].form||typeof c!="string"||!(c==="/$form"||c.startsWith("/$form/")||c.startsWith("$form.")))&&n.push(`Component "${a.id}" requires a wait-surface $form binding.`)),a.actions!==void 0&&(!a.actions||typeof a.actions!="object"||Array.isArray(a.actions))){n.push(`Component "${a.id}" actions must be an object.`);continue}let w=Object.keys(a.actions??{}).length;w&&!["single-action","multi-action"].includes(l?.interaction??"")?n.push(`Component "${a.id}" cannot have actions.`):w>1&&l?.interaction==="single-action"&&n.push(`Component "${a.id}" can have at most one action.`),Re(a.props,n);for(let p of Object.values(a.actions??{})){if(!p||typeof p!="object"||Array.isArray(p)){n.push(`Component "${a.id}" has an invalid action.`);continue}let y=p;if(!["navigate","node.resume","node.stop"].includes(y.type)){n.push(`Unknown surface action "${String(y.type)}".`);continue}F.SURFACE_SLOT_POLICY[t].actions.includes(y.type)||n.push(`Action "${y.type}" is not allowed on "${t}" surfaces.`),y.type==="navigate"&&(!y.href||typeof y.href!="object"||typeof y.href.path!="string")&&n.push("Navigate actions require an href binding."),Re(y,n);}}(typeof e.root!="string"||!r.has(e.root))&&n.push(`Surface root "${String(e.root)}" is missing.`);let i=new Set,s=new Set,u=(o,a)=>{if(a>At)return void n.push(`Surface component depth exceeds ${At}.`);if(s.has(o))return void n.push(`Surface component cycle includes "${o}".`);if(i.has(o))return;let l=r.get(o);if(l){s.add(o);for(let c of Array.isArray(l.children)?l.children:[]){if(typeof c!="string"){n.push(`Component "${o}" has a non-string child reference.`);continue}r.has(c)?u(c,a+1):n.push(`Component "${o}" references missing child "${c}".`);}s.delete(o),i.add(o);}};typeof e.root=="string"&&u(e.root,1);for(let o of r.keys())i.has(o)||n.push(`Component "${o}" is unreachable from root.`);for(let o of _t(e)){let a=gn(o);a==="$form"&&!F.SURFACE_SLOT_POLICY[t].form?n.push(`Binding "${o}" is only allowed on wait surfaces.`):a!=="$form"&&!un.has(a)&&n.push(`Invalid surface binding path "${o}".`);}if(e.form!==void 0)if(F.SURFACE_SLOT_POLICY[t].form||n.push("Forms are only allowed on wait surfaces."),!Array.isArray(e.form?.fields))n.push("Surface form fields must be an array.");else {let o=new Set;for(let a of e.form.fields){if(!a||typeof a!="object"||Array.isArray(a)){n.push("Every surface form field must be an object.");continue}let l=a,c=l?.name,w=l?.type;typeof c!="string"||!c||o.has(c)?n.push(`Surface form field name "${String(c)}" is invalid or duplicated.`):o.add(c),fn.has(String(w))||n.push(`Unknown surface form field type "${String(w)}".`),(typeof l.label!="string"||!l.label.trim())&&n.push(`Surface form field "${String(c)}" requires a label.`),w==="file"&&"default"in l&&n.push(`File field "${String(c)}" cannot have a default binding.`),w==="file"&&(l.maxFiles!==void 0&&(!Number.isInteger(l.maxFiles)||Number(l.maxFiles)<1||Number(l.maxFiles)>5)&&n.push(`File field "${String(c)}" maxFiles must be between 1 and 5.`),l.maxBytes!==void 0&&(!Number.isInteger(l.maxBytes)||Number(l.maxBytes)<1||Number(l.maxBytes)>10*1024*1024)&&n.push(`File field "${String(c)}" maxBytes exceeds platform limits.`),l.accept!==void 0&&(!Array.isArray(l.accept)||l.accept.some(p=>typeof p!="string"||!/^[a-z0-9.+-]+\/(?:[a-z0-9.+-]+|\*)$/i.test(p)))&&n.push(`File field "${String(c)}" has invalid MIME types.`)),w==="select"&&(!Array.isArray(l.options)||l.options.length===0?n.push(`Select field "${String(c)}" requires options.`):l.options.some(p=>!p||typeof p!="object"||typeof p.label!="string"||typeof p.value!="string")&&n.push(`Select field "${String(c)}" has invalid options.`));}Re(e.form,n);}return Array.from(new Set(n))}function yn(e){let t=e;if(!t||typeof t!="object")return ["Surface must be an object."];let n=[];return (typeof t.id!="string"||!/^[a-z0-9][a-z0-9-]{0,62}$/.test(t.id))&&n.push("Surface requires a kebab-case id."),(typeof t.name!="string"||!t.name.trim())&&n.push("Surface requires a name."),F.SURFACE_SLOTS.includes(t.slot)?n.push(...It(t.definition,t.slot)):n.push(`Surface requires slot ${F.SURFACE_SLOTS.map(r=>`"${r}"`).join(" or ")}.`),Array.from(new Set(n))}});var St=a(ke=>{var wn=ke&&ke.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:true,get:function(){return t[n]}}),Object.defineProperty(e,r,i);}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n];})),mn=ke&&ke.__exportStar||function(e,t){for(var n in e)n!=="default"&&!Object.prototype.hasOwnProperty.call(t,n)&&wn(t,e,n);};Object.defineProperty(ke,"__esModule",{value:true});mn(Tt(),ke);});var Ue=class extends Error{constructor(){super("401 Unauthorized"),this.name="UnauthorizedError";}};function ln(e,t=Date.now()){return e-t<3e4}async function B(e$1){let t=new a$4,r=await(async()=>await t.withLock(async()=>{b$1.info("Tokens read from disk for auth check");let i=await t.get();if(i||(b$1.error("No tokens found on disk"),render(ge.createElement(c$1,{state:{type:"login_error",message:"Not logged in",detail:"run `culvii login`"}})),await e(a$2.LOGIN_FAILED,{reason:"session_expired"}),await j$1(),process.exit(1)),!ln(i.expiresAt))return b$1.info("Access token valid, skipping refresh"),i.accessToken;b$1.info("Access token expired, attempting refresh");let s=`https://${q.cognitoDomain}/oauth2/token`,u=new URLSearchParams;u.set("grant_type","refresh_token"),u.set("refresh_token",i.refreshToken),u.set("client_id",q.clientId);let o;try{o=await fetch(s,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:u.toString()});}catch(w){b$1.error("Network error during refresh",{error:w.message}),render(ge.createElement(c$1,{state:{type:"login_error",message:"Refresh failed",detail:"Cannot reach auth server \u2014 check your connection"}})),await e(a$2.LOGIN_FAILED,{reason:"session_expired"}),await j$1(),process.exit(1);}let a=await o.json();(!o.ok||a.error==="invalid_grant")&&(b$1.warn("Refresh failed with invalid_grant"),await t.delete(),render(ge.createElement(c$1,{state:{type:"login_error",message:"Session expired",detail:"run `culvii login` to authenticate"}})),await e(a$2.LOGIN_FAILED,{reason:"session_expired"}),await j$1(),process.exit(1));let l=Date.now(),c=l+a.expires_in*1e3;return b$1.info("Refresh succeeded",{expiresAt:c}),await t.set({accessToken:a.access_token,refreshToken:a.refresh_token||i.refreshToken,idToken:a.id_token||i.idToken,expiresAt:c,tokenType:"Bearer",scope:i.scope,issuedAt:l,issuer:i.issuer}),a.access_token}))();try{await e$1(r);}catch(i){if(!(i instanceof Ue))throw i;b$1.info("Mid-session 401 detected, attempting refresh");let s=await t.withLock(async()=>{b$1.info("Tokens read from disk for retry");let u=await t.get();u||(b$1.error("No tokens found on disk during retry"),render(ge.createElement(c$1,{state:{type:"login_error",message:"Not logged in",detail:"run `culvii login`"}})),await e(a$2.LOGIN_FAILED,{reason:"session_expired"}),await j$1(),process.exit(1)),b$1.info("Access token expired (forced by 401), attempting refresh");let o=`https://${q.cognitoDomain}/oauth2/token`,a=new URLSearchParams;a.set("grant_type","refresh_token"),a.set("refresh_token",u.refreshToken),a.set("client_id",q.clientId);let l;try{l=await fetch(o,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:a.toString()});}catch(y){b$1.error("Network error during refresh retry",{error:y.message}),render(ge.createElement(c$1,{state:{type:"login_error",message:"Refresh failed",detail:"Cannot reach auth server \u2014 check your connection"}})),await e(a$2.LOGIN_FAILED,{reason:"session_expired"}),await j$1(),process.exit(1);}let c=await l.json();(!l.ok||c.error==="invalid_grant")&&(b$1.warn("Refresh retry failed with invalid_grant"),await t.delete(),render(ge.createElement(c$1,{state:{type:"login_error",message:"Session expired",detail:"run `culvii login` to authenticate"}})),await e(a$2.LOGIN_FAILED,{reason:"session_expired"}),await j$1(),process.exit(1));let w=Date.now(),p=w+c.expires_in*1e3;return b$1.info("Refresh retry succeeded",{expiresAt:p}),await t.set({accessToken:c.access_token,refreshToken:c.refresh_token||u.refreshToken,idToken:c.id_token||u.idToken,expiresAt:p,tokenType:"Bearer",scope:u.scope,issuedAt:w,issuer:u.issuer}),c.access_token});try{b$1.info("Retry after refresh succeeded"),await e$1(s);}catch(u){throw u instanceof Ue&&(b$1.error("Retry after refresh failed (still 401)"),await t.withLock(async()=>{await t.delete();}),render(ge.createElement(c$1,{state:{type:"login_error",message:"Session invalidated",detail:"run `culvii login` to authenticate"}})),await e(a$2.LOGIN_FAILED,{reason:"session_expired"}),await j$1(),process.exit(1)),u}}}async function et(){let e=new a$4;return e.withLock(async()=>{let t=await e.get();if(!t)return null;let n=`https://${q.cognitoDomain}/oauth2/token`,r=new URLSearchParams;r.set("grant_type","refresh_token"),r.set("refresh_token",t.refreshToken),r.set("client_id",q.clientId);let i;try{i=await fetch(n,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r.toString()});}catch(a){return b$1.error("Network error during silent refresh",{error:a.message}),null}let s=await i.json();if(!i.ok||s.error==="invalid_grant")return b$1.warn("Silent refresh failed",{error:s.error}),null;let u=Date.now(),o=u+s.expires_in*1e3;return await e.set({accessToken:s.access_token,refreshToken:s.refresh_token||t.refreshToken,idToken:s.id_token||t.idToken,expiresAt:o,tokenType:"Bearer",scope:t.scope,issuedAt:u,issuer:t.issuer}),s.access_token})}async function Y(e){let t=await e.text();try{let n=JSON.parse(t);if(n.error)return n.error}catch{}return t}async function j(e,t,n={}){let{skipEnvironmentHeader:r,...i}=n,u=await new a$3().read({exitOnError:false}),o$1=u.contexts[u.active],a=o$1?.tenant_id,l=o$1?.environment||"dev",c=o()??l,w=o$1?.environment_ids?.[c]??(c===l?o$1?.environment_id:void 0),p=k[c],y=r?{}:w?{"x-environment-id":w}:{"x-environment-slug":p},k$1={Authorization:`Bearer ${t}`,...a?{"x-tenant-id":a}:{},...y,...i.headers||{}};return fetch(e,{...i,headers:k$1})}function kt(){let e=a$1();return e.isTTY&&!e.isCI&&e.supportsColor&&e.supportsUnicode}function ht(e$1){let t=e$1.command("workspace").description("Workspace commands").option("--env <env>","Target environment (sandbox or prod)");t.command("create").description("Create a new workspace").requiredOption("--name <name>","Workspace name").requiredOption("--slug <slug>","Workspace slug").action(async n=>{if(kt()){let u=function(){let[o,a]=ge.useState({type:"loading"});return ge.useEffect(()=>(s$1=a,()=>{s$1=null;}),[]),ge.createElement(i,{state:o})};let{WorkspaceCreateView:i}=await import('./WorkspaceView-RNFALIPM.js'),s$1=null;await V(Promise.resolve(ge.createElement(u))),await B(async o=>{let{apiUrl:a,context:l}=await r({env:t.opts().env}),c=s(l);try{let w=await j(`${a}/api/workspaces`,o,{method:"POST",headers:{...c,"Content-Type":"application/json"},body:JSON.stringify({name:n.name,slug:n.slug,tenantId:l.tenant_id})});if(!w.ok){let A=await Y(w);s$1?.({type:"error",message:"Failed to create workspace",detail:`Server responded with ${w.status}: ${A}`});let{userId:v,tenantId:D}=await d();v?await f(a$2.WORKSPACE_CREATE_FAILED,v,D,{error_class:"ApiError",slug:n.slug,env:l.environment}):await e(a$2.WORKSPACE_CREATE_FAILED,{error_class:"ApiError",slug:n.slug,env:l.environment}),await j$1();return}let p=await w.json();s$1?.({type:"success",id:p?.data?.workspaceId,slug:p?.data?.workspaceSlug||n.slug,name:n.name});let{userId:y,tenantId:k}=await d();y?await f(a$2.WORKSPACE_CREATED,y,k,{slug:n.slug,env:l.environment}):await e(a$2.WORKSPACE_CREATED,{slug:n.slug,env:l.environment}),await j$1();}catch(w){s$1?.({type:"error",message:"Unexpected error",detail:w.message});let{userId:p,tenantId:y}=await d();p?await f(a$2.WORKSPACE_CREATE_FAILED,p,y,{error_class:w?.constructor?.name,env:l.environment}):await e(a$2.WORKSPACE_CREATE_FAILED,{error_class:w?.constructor?.name,env:l.environment}),await j$1();}});return}await B(async i=>{let{apiUrl:s$1,context:u}=await r({env:t.opts().env}),o=s(u);console.log(`tenant: ${u.tenant_slug} | workspace: N/A | env: ${u.environment}`);try{let a=await j(`${s$1}/api/workspaces`,i,{method:"POST",headers:{...o,"Content-Type":"application/json"},body:JSON.stringify({name:n.name,slug:n.slug,tenantId:u.tenant_id})});if(!a.ok){let p=await Y(a);console.error(`Error: Failed to create workspace. Server responded with ${a.status}: ${p}`);let{userId:y,tenantId:k}=await d();y?await f(a$2.WORKSPACE_CREATE_FAILED,y,k,{error_class:"ApiError",slug:n.slug,env:u.environment}):await e(a$2.WORKSPACE_CREATE_FAILED,{error_class:"ApiError",slug:n.slug,env:u.environment}),await j$1(),process.exit(1);}let l=await a.json();console.log(`${w} Workspace created successfully.`),console.log(` ID: ${l?.data?.workspaceId}`),l?.data?.workspaceSlug&&console.log(` Slug: ${l?.data?.workspaceSlug}`);let{userId:c,tenantId:w$1}=await d();c?await f(a$2.WORKSPACE_CREATED,c,w$1,{slug:n.slug,env:u.environment}):await e(a$2.WORKSPACE_CREATED,{slug:n.slug,env:u.environment}),await j$1();}catch(a){console.error(`Error: Network or unexpected error: ${a.message}`);let{userId:l,tenantId:c}=await d();l?await f(a$2.WORKSPACE_CREATE_FAILED,l,c,{error_class:a?.constructor?.name,env:u.environment}):await e(a$2.WORKSPACE_CREATE_FAILED,{error_class:a?.constructor?.name,env:u.environment}),await j$1(),process.exit(1);}});}),t.command("list").description("List workspaces").action(async()=>{if(kt()){let s$1=function(){let[u,o]=ge.useState({type:"loading"});return ge.useEffect(()=>(i=o,()=>{i=null;}),[]),ge.createElement(r$1,{state:u})};let{WorkspaceListView:r$1}=await import('./WorkspaceView-RNFALIPM.js'),i=null;await V(Promise.resolve(ge.createElement(s$1))),await B(async u=>{let{apiUrl:o,context:a}=await r({env:t.opts().env}),l=s(a);try{let c=await j(`${o}/api/workspaces?tenantId=${a.tenant_id}`,u,{headers:l});if(!c.ok){let A=await Y(c);i?.({type:"error",message:"Failed to list workspaces",detail:`Server responded with ${c.status}: ${A}`});let{userId:v,tenantId:D}=await d();v?await f(a$2.WORKSPACE_LIST_FAILED,v,D,{error_class:"ApiError",env:a.environment}):await e(a$2.WORKSPACE_LIST_FAILED,{error_class:"ApiError",env:a.environment}),await j$1();return}let p=(await c.json())?.data?.workspaces;if(!Array.isArray(p)){i?.({type:"error",message:"Unexpected response format"});let{userId:A,tenantId:v}=await d();A?await f(a$2.WORKSPACE_LIST_FAILED,A,v,{error_class:"UnexpectedResponse",env:a.environment}):await e(a$2.WORKSPACE_LIST_FAILED,{error_class:"UnexpectedResponse",env:a.environment}),await j$1();return}i?.({type:"success",workspaces:p.map(A=>({id:A.id,name:A.name,slug:A.slug??""}))});let{userId:y,tenantId:k}=await d();y?await f(a$2.WORKSPACE_LISTED,y,k,{env:a.environment}):await e(a$2.WORKSPACE_LISTED,{env:a.environment}),await j$1();}catch(c){i?.({type:"error",message:"Unexpected error",detail:c.message});let{userId:w,tenantId:p}=await d();w?await f(a$2.WORKSPACE_LIST_FAILED,w,p,{error_class:c?.constructor?.name,env:a.environment}):await e(a$2.WORKSPACE_LIST_FAILED,{error_class:c?.constructor?.name,env:a.environment}),await j$1();}});return}await B(async r$1=>{let{apiUrl:i,context:s$1}=await r({env:t.opts().env}),u=s(s$1);console.log(`tenant: ${s$1.tenant_slug} | workspace: N/A | env: ${s$1.environment}`);try{let o=await j(`${i}/api/workspaces?tenantId=${s$1.tenant_id}`,r$1,{headers:u});if(!o.ok){let p=await Y(o);console.error(`Error: Failed to list workspaces. Server responded with ${o.status}: ${p}`);let{userId:y,tenantId:k}=await d();y?await f(a$2.WORKSPACE_LIST_FAILED,y,k,{error_class:"ApiError",env:s$1.environment}):await e(a$2.WORKSPACE_LIST_FAILED,{error_class:"ApiError",env:s$1.environment}),await j$1(),process.exit(1);}let l=(await o.json())?.data?.workspaces;if(!Array.isArray(l)){console.error("Error: Unexpected response format");let{userId:p,tenantId:y}=await d();p?await f(a$2.WORKSPACE_LIST_FAILED,p,y,{error_class:"UnexpectedResponse",env:s$1.environment}):await e(a$2.WORKSPACE_LIST_FAILED,{error_class:"UnexpectedResponse",env:s$1.environment}),await j$1(),process.exit(1);}for(let p of l)console.log(`${p.id} ${p.name} ${p.slug}`);let{userId:c,tenantId:w}=await d();c?await f(a$2.WORKSPACE_LISTED,c,w,{env:s$1.environment}):await e(a$2.WORKSPACE_LISTED,{env:s$1.environment}),await j$1();}catch(o){console.error(`Error: Network or unexpected error: ${o.message}`);let{userId:a,tenantId:l}=await d();a?await f(a$2.WORKSPACE_LIST_FAILED,a,l,{error_class:o?.constructor?.name,env:s$1.environment}):await e(a$2.WORKSPACE_LIST_FAILED,{error_class:o?.constructor?.name,env:s$1.environment}),await j$1(),process.exit(1);}});});}function nt(e,t,n){let r=null,i=0,s=false,u=[],o=new Map,a=null,l=null,c=0,w=[1e3,2e3,4e3,8e3,16e3];function p(){a&&(clearInterval(a),a=null),l&&(clearTimeout(l),l=null),c=0;}function y(){p(),a=setInterval(()=>{if(!r||r.readyState!==tt.OPEN)return;let R=Date.now().toString()+"-"+Math.random().toString();r.send(JSON.stringify({type:"client-ping",requestId:R})),l=setTimeout(()=>{c++,c>=2&&(b$1.warn("devSync WebSocket dead (missed 2 pongs), terminating"),p(),r?.terminate());},5e3);},2e4);}function k(R){R.removeAllListeners(),R.on("error",()=>{});try{R.terminate();}catch(L){b$1.warn("devSync error terminating stale socket",{error:L.message});}}let A=0;async function v(){if(s)return;let R=++A,L;try{L=await t();}catch(I){b$1.error("devSync failed to obtain headers for connection",{error:I.message}),R===A&&D();return}if(s||R!==A)return;r&&k(r);let f=new tt(e,{headers:L});r=f,f.on("open",()=>{if(r===f){i=0,b$1.info("devSync WebSocket connected",{url:e}),n.onOpen();for(let I of u)f.send(JSON.stringify(I));u=[],y();}}),f.on("message",I=>{if(r!==f)return;let E=Buffer.isBuffer(I)?I.toString("utf-8"):I instanceof ArrayBuffer?Buffer.from(I).toString("utf-8"):Buffer.concat(I).toString("utf-8"),g;try{g=JSON.parse(E);}catch{b$1.warn("Received invalid JSON from devSync",{raw:E});return}if(g.ok===true&&g.slug&&typeof g.warning=="string"){n.onWarning?.(g.slug,g.warning);return}if(g.type==="session-probe"&&typeof g.requestId=="string"){f.send(JSON.stringify({type:"session-pong",requestId:g.requestId}));return}if(g.type==="client-pong"){l&&(clearTimeout(l),l=null),c=0;return}if(g.ok===true&&g.slug&&g.type==="validation-error"){n.onValidationErrorAck?.(g.slug);return}if(g.ok===true&&g.slug){g.resourceId&&o.set(g.slug,g.resourceId),n.onAck(g.slug,g.resourceId,g.orphaned===true);return}if(g.ok===false&&g.slug){n.onError(g.slug,g.error||"Unknown error");return}if(g.ok===false&&!g.slug){n.onFatal(g.error||"Fatal error from server"),s=true,p(),f.close();return}}),f.on("unexpected-response",(I,E)=>{if(r===f){if(E.statusCode===401){b$1.error("devSync credentials rejected (401)"),s=true,p(),f.terminate(),n.onAuthFailure?n.onAuthFailure():n.onFatal("Credentials rejected by server (401)");return}b$1.warn("devSync unexpected handshake response",{statusCode:E.statusCode}),p(),f.terminate(),D();}}),f.on("close",I=>{r!==f||s||(b$1.warn("devSync WebSocket closed",{code:I}),p(),D());}),f.on("error",I=>{r===f&&b$1.error("devSync WebSocket error",{error:I.message});});}function D(){if(p(),s)return;if(i>=w.length){let f=`devSync PERMANENT FAILURE: giving up after ${w.length} retries`;b$1.error(f,{retryCount:i,retryDelaysMs:w}),n.onFatal(f),s=true;return}let R=w[i];i++;let L=w.length-i;b$1.info(`devSync reconnecting in ${R}ms (attempt ${i}/${w.length}, ${L} left before permanent failure)`),setTimeout(()=>{v();},R);}function $(R){r&&r.readyState===tt.OPEN?r.send(JSON.stringify(R)):u.push(R);}function M(){s=true,p(),r&&k(r),b$1.info("devSync WebSocket closed by client");}function S(){s||(p(),i=0,r&&k(r),v());}return v(),{send:$,close:M,reconnectNow:S}}var Ct=b(St(),1);var Tn=fileURLToPath(import.meta.url),Sn=dirname(Tn),Dn=join(Sn,"lib","evaluator.js"),Cn=createRequire(import.meta.url),Rn=Cn.resolve("tsx/cli");function Pe(e){return (0, Ct.validateSurfaceResource)(e)}function st(e){if(Array.isArray(e))return e.map(st);if(e!==null&&typeof e=="object"){let t={};for(let n of Object.keys(e).sort())t[n]=st(e[n]);return t}return e}function xn(e){if(!e||typeof e!="object")return e;let t={...e};return Array.isArray(t.nodes)&&(t.nodes=t.nodes.map(({id:n,...r})=>r)),t}function Ln(e){return createHash("sha256").update(JSON.stringify(st(xn(e)))).digest("hex")}function ye(e){return (Array.isArray(e?.nodes)?e.nodes:[]).filter(n=>n?.type==="core.agent").map(n=>n?.nodeParams?.agentReferenceKey??n?.nodeParams?.agentId).filter(n=>typeof n=="string"&&!n.startsWith("agt_"))}function Fe(e){return (Array.isArray(e?.nodes)?e.nodes:[]).flatMap(n=>["output","wait"].map(r=>n?.ui?.[r]).filter(r=>r?.kind==="custom"&&typeof r.surfaceKey=="string").map(r=>({surfaceKey:r.surfaceKey,...Number.isInteger(r.version)?{version:r.version}:{}})))}function $n(e){return Array.isArray(e)?e:e&&typeof e=="object"?Object.entries(e).map(([t,n])=>n&&typeof n=="object"&&!Array.isArray(n)?{name:t,...n}:n):[]}function Ie(e){return $n(e?.tools).filter(t=>t&&typeof t=="object"&&!Array.isArray(t)).map(t=>({referenceKey:t.workflowReferenceKey??t.workflowId,toolName:t.name,triggerNodeName:t.triggerNodeName})).filter(t=>typeof t.referenceKey=="string"&&!t.referenceKey.startsWith("wfl_"))}function Te(e){return Ie(e).map(t=>t.referenceKey)}function bn(e){return typeof e?.type=="string"&&e.type!=="manualTrigger"&&e.type.endsWith("Trigger")}function On(e,t){return e.get(t)??e.get(W(t))}function Rt(e){let t=new Set,n=[];for(let r of e.values())t.has(r.id)||(t.add(r.id),n.push(r));return n}function xt(e,t){let n=typeof e?.id=="string"?e.id:"unknown";if(Ie(e).length>0)return {id:n,definition:e};let r=n==="unknown"?void 0:On(t,n);return r?{id:n,definition:r.definition}:e&&typeof e=="object"&&!Array.isArray(e)?{id:n,definition:e}:null}function at(e,t){let n=[e];for(let r of e.definition?.secondaryAgents??[]){let i=xt(r,t);i&&n.push(i);}return n}function We(e){let t=new Map,n=new Map;for(let s of e){let u=s.definition?.id;typeof u=="string"&&(s.type==="agent"?(t.set(u,{id:u,definition:s.definition}),t.set(W(u),{id:u,definition:s.definition})):s.type==="workflow"&&(n.set(u,s.definition),n.set(W(u),s.definition)));}let r=new Set;for(let s of Rt(t))for(let u of at(s,t))for(let o of Te(u.definition))r.add(W(o));let i=new Set;for(let s of r){let u=n.get(s);if(u)for(let o of ye(u))i.add(W(o));}for(let s of i){let u=t.get(s);if(u){if(Ie(u.definition).length>0)return `agent '${u.id}' cannot define workflow tools when invoked by an agent workflow tool.`;for(let o of u.definition?.secondaryAgents??[]){let a=xt(o,t);if(a&&Ie(a.definition).length>0)return `secondary agent '${a.id}' referenced by agent '${u.id}' cannot define workflow tools when '${u.id}' is invoked by an agent workflow tool.`}}}return null}function Me(e){let t=new Map,n=new Map;for(let i of e){let s=i.definition?.id;typeof s=="string"&&(i.type==="agent"?(t.set(s,{id:s,definition:i.definition}),t.set(W(s),{id:s,definition:i.definition})):i.type==="workflow"&&(n.set(s,i.definition),n.set(W(s),i.definition)));}let r=new Set;for(let i of n.values())for(let s of ye(i))r.add(W(s));for(let i of r){let s=t.get(i);if(!s)continue;let u=at(s,t);for(let o of u)for(let a of Ie(o.definition)){let l=n.get(a.referenceKey)??n.get(W(a.referenceKey));if(!(!l||ye(l).length===0))return `workflow tool '${a.toolName??"unknown"}' on agent '${o.id}' cannot reference workflow '${a.referenceKey}' because '${s.id}' is invoked by a workflow and the target workflow contains an agent node.`}}return null}function je(e){let t=new Map,n=new Map;for(let r of e){let i=r.definition?.id;typeof i=="string"&&(r.type==="agent"?(t.set(i,{id:i,definition:r.definition}),t.set(W(i),{id:i,definition:r.definition})):r.type==="workflow"&&(n.set(i,r.definition),n.set(W(i),r.definition)));}for(let r of Rt(t))for(let i of at(r,t))for(let s of Ie(i.definition)){let u=n.get(s.referenceKey)??n.get(W(s.referenceKey));if(!u)continue;let o=Array.isArray(u.nodes)?u.nodes:[],a=o.find(bn);if(a)return `workflow tool '${s.toolName??"unknown"}' on agent '${i.id}' references workflow '${s.referenceKey}' with non-manual trigger '${a.name??a.type}'.`;if(s.triggerNodeName){if(o.find(w=>w?.name===s.triggerNodeName)?.type==="manualTrigger")continue;return `workflow tool '${s.toolName??"unknown"}' on agent '${i.id}' must use a manual trigger in workflow '${s.referenceKey}'.`}let l=o.filter(c=>c?.type==="manualTrigger");if(l.length!==1)return l.length===0?`workflow tool '${s.toolName??"unknown"}' on agent '${i.id}' references workflow '${s.referenceKey}' without a manual trigger.`:`workflow tool '${s.toolName??"unknown"}' on agent '${i.id}' must specify triggerNodeName because workflow '${s.referenceKey}' has multiple manual triggers.`}return null}function Ve(e){let t=[],n=(r,i)=>{let s=i&&typeof i=="object"&&!Array.isArray(i)?i.credentialId:void 0;(typeof s!="string"||!s.trim())&&t.push(`agent '${r}' model must include a credentialId \u2014 use model: { provider, modelId, credentialId }.`);};e?.modelConfig!==void 0&&e?.modelConfig!==null&&n(e?.id,e.modelConfig);for(let r of e?.secondaryAgents??[])r?.modelConfig!==void 0&&r?.modelConfig!==null&&n(r?.id??e?.id,r.modelConfig);return t}function Ke(e){let t=new Map;for(let i of e){let s=i.definition?.id;if(!s)continue;let u=i.type==="agent"?Te(i.definition).map(o=>`workflow:${o}`):i.type==="workflow"?ye(i.definition).map(o=>`agent:${o}`):[];t.set(`${i.type}:${s}`,u);}let n=null;function r(i,s){if(!n)for(let u of t.get(i)??[]){if(!t.has(u))continue;let o=[...s,u];if(s.length>=3){n=`Unsupported nested SDK reference chain: ${o.join(" -> ")}. Only workflow -> agent -> workflow or agent -> workflow -> agent is supported.`;return}r(u,o);}}for(let i of t.keys())r(i,[i]);return n}async function Nn(e){try{let r=X.join(e,"culvii.yaml"),s=(await ne.readFile(r,"utf-8")).split(`
|
|
3
3
|
`),u=[],o=!1;for(let a of s){if(a.trim().startsWith("entrypoints:")){o=!0;continue}if(o){let l=a.match(/^\s+-\s+(.+)$/);l?u.push(X.resolve(e,l[1].trim())):a.trim()&&!a.trim().startsWith("#")&&(o=!1);}}if(u.length>0)return b$1.info("Using entrypoints from culvii.yaml",{count:u.length}),u}catch{}let t=[];async function n(r){let i;try{i=await ne.readdir(r,{withFileTypes:!0});}catch{return}for(let s of i){if(s.name==="node_modules"||s.name==="dist"||s.name===".git")continue;let u=X.join(r,s.name);s.isDirectory()?await n(u):s.isFile()&&s.name.endsWith(".culvii.ts")&&t.push(u);}}return await n(e),b$1.info("Found .culvii.ts entrypoints",{count:t.length}),t}function Un(e,t){return new Promise((n,r)=>{if(e.length===0){n([]);return}let i=spawn(process.execPath,[Rn,Dn,...e],{env:{...process.env,...t,CULVII_DEV:"true"},stdio:["ignore","pipe","pipe"]}),s="",u="";i.stdout.on("data",o=>{s+=o.toString();}),i.stderr.on("data",o=>{u+=o.toString();}),i.on("close",o=>{if(u.trim()&&b$1.warn("Evaluator stderr",{stderr:u.trim()}),o!==0){r(new Error(`Evaluator exited with code ${o}. ${u.trim()||"Check your files for syntax errors."}`));return}let a=s.split(`
|
|
4
4
|
`).filter(w=>w.includes("__culvii_dev_definitions__"));if(a.length===0){n([]);return}let l=[],c=new Set;for(let w of a)try{let p=JSON.parse(w);for(let y of p.__culvii_dev_definitions__||[]){let k=y?.definition?.id,A=y?.type&&k?`${y.type}:${k}`:null;if(A){if(c.has(A))continue;c.add(A);}l.push(y);}}catch{b$1.warn("Failed to parse evaluator output",{line:w});}n(l);});})}function W(e){return e.toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/^-+|-+$/g,"").replace(/-{2,}/g,"-").slice(0,63)}function ot(e){let t=process.cwd(),n=new Map,r=null,i=false,s=false,u=false;async function o(){if(i){s=true;return}i=true;try{u&&(u=!1,n.clear()),await l();}catch(p){b$1.error("Evaluation failed",{error:p.message});}finally{i=false,s&&(s=false,o());}}function a(p,y,k){e.onLog?e.onLog(y,k):(k==="error"?process.stderr:process.stdout).write(`${p} ${y}
|
|
5
5
|
`);}async function l(){let p=await Nn(t),y$1;try{y$1=await Un(p,{});}catch(g){a(x,`Evaluation failed, skipping this sync cycle: ${g.message}`,"error");return}let k=new Map,A=new Set,v=new Set(y$1.map(g=>g.definition.id).filter(Boolean)),D=new Set(y$1.filter(g=>g.type==="surface").flatMap(g=>{let C=g.definition.id;return typeof C=="string"?[C,W(C)]:[]})),$=false,M=false;for(let g of y$1){let C=g.definition.id;if(!C){a(y,`Skipping ${g.type}: referenced resources require an explicit id.`,"warn");continue}let x$1=typeof C=="string"?W(C):String(C);if(!x$1){a(y,`Skipping definition: could not derive a valid slug from "${C}". Add an explicit id field.`,"warn");continue}if(g.type==="surface"){let P=Pe(g.definition);if(P.length){a(x,`Invalid surface '${x$1}': ${P.join("; ")}.`,"error");return}}let N=`${g.type}:${x$1}`;if(A.has(N)){a(x,`Duplicate slug '${x$1}' detected in ${g.type}s. Fix all collisions before syncing.`,"error");return}A.add(N);let G=Ln(g.definition);k.set(N,{slug:x$1,type:g.type,definition:g.definition,hash:G});let re=g.type==="agent"?Te(g.definition):[],pe=g.type==="workflow"?ye(g.definition):[],ee=g.type==="workflow"?Fe(g.definition):[];if(g.type==="agent"){for(let P of Ve(g.definition))a(x,P,"error"),M=true;for(let P of g.definition.secondaryAgents||[]){let K=P?.id,O=!!(P?.systemPrompt||P?.modelConfig);if(typeof K=="string"&&!O&&!v.has(K)){let te=`Dangling ref: agent '${x$1}' references secondary agent '${K}' which is not defined locally.`;a(x,te,"error"),$=true,e.onValidationError?.({resourceType:"agent",slug:x$1,missingReferenceId:K,message:te});}}}for(let P of re)if(!v.has(P)){let K=`Dangling ref: agent '${x$1}' references workflow '${P}' which is not defined locally.`;a(x,K,"error"),$=true,e.onValidationError?.({resourceType:"agent",slug:x$1,missingReferenceId:P,message:K});}for(let P of pe)if(!v.has(P)){let K=`Dangling ref: workflow '${x$1}' references agent '${P}' which is not defined locally.`;a(x,K,"error"),$=true,e.onValidationError?.({resourceType:"workflow",slug:x$1,missingReferenceId:P,message:K});}for(let P of ee)if(P.version===void 0&&!D.has(P.surfaceKey)){let K=`Dangling ref: workflow '${x$1}' references local surface '${P.surfaceKey}' which is not defined locally. Pin a published version or define the surface.`;a(x,K,"error"),$=true,e.onValidationError?.({resourceType:"workflow",slug:x$1,missingReferenceId:P.surfaceKey,message:K});}}if($){a(x,"Fix all dangling references before syncing.","error");return}if(M){a(x,"Fix the model configuration before syncing.","error");return}let S=We(y$1);if(S){a(x,S,"error"),a(x,"Fix the secondary agent tools before syncing.","error");return}let R=je(y$1);if(R){a(x,R,"error"),a(x,"Fix the workflow tool trigger before syncing.","error");return}let L=Me(y$1);if(L){a(x,L,"error"),a(x,"Fix the workflow tool target before syncing.","error");return}let f=Ke(y$1);if(f){a(x,f,"error"),a(x,"Fix the reference chain before syncing.","error");return}let I=0;for(let[g,{hash:C,type:x}]of n.entries())if(!k.has(g)){let N=g.slice(g.indexOf(":")+1),G=x==="surface"?void 0:[...k.values()].find(re=>re.hash===C&&re.type===x);G?a(y,`Looks like '${N}' was renamed to '${G.slug}'.
|
|
@@ -840,5 +840,5 @@ createCoordinationWorkflow();
|
|
|
840
840
|
Select a template:`),ae.forEach((v,D)=>{console.log(` ${D+1}) ${v.padEnd(16)} ${Xt[v]}`);});!o;){let v=await gt(A,"Template [1-4] (2): "),D=v?parseInt(v,10)-1:1;D>=0&&D<ae.length?o=ae[D]:console.log(` Please enter a number between 1 and ${ae.length}.`);}if(!a)for(console.log(`
|
|
841
841
|
Select a model provider:`),oe.forEach((v,D)=>{console.log(` ${D+1}) ${v}`);});!a;){let v=await gt(A,"Provider [1-4] (1): "),D=v?parseInt(v,10)-1:0;D>=0&&D<oe.length?a=oe[D]:console.log(` Please enter a number between 1 and ${oe.length}.`);}}finally{A.close();}}else !u&&!n.here&&(u="my-culvii-project"),o||(o="agent-workflow"),a||(a="openai");let c=n.here?process.cwd():X.join(process.cwd(),u);existsSync(c)?(await ne.readdir(c)).filter(D=>!D.startsWith(".")).length>0&&(console.error(`${x} Directory '${X.relative(process.cwd(),c)||"."}' already exists and is not empty.`),await s(a$2.INIT_FAILED,{error_class:"DirectoryNotEmpty"}),await j$1(),process.exit(1)):await ne.mkdir(c,{recursive:!0});let w$1=X.join(c,"src");await ne.mkdir(w$1,{recursive:!0});let p=Zt[a],y=[];await ne.writeFile(X.join(c,"package.json"),en(n.here?X.basename(c):u),"utf-8"),await ne.writeFile(X.join(c,"tsconfig.json"),Qt,"utf-8"),y.push("package.json"),y.push("tsconfig.json");let k=async(A,v)=>{await ne.writeFile(X.join(w$1,A),v,"utf-8"),y.push(X.join("src",A));};o==="agent-only"?await k("greeter-agent.culvii.ts",Xe(p)):o==="agent-workflow"?(await k("greeter-agent.culvii.ts",Xe(p)),await k("greeting-workflow.culvii.ts",tn)):o==="agent-workflow-tool"?(await k("research-agent.culvii.ts",rn(p)),await k("research-workflow.culvii.ts",sn)):o==="multi-agent"&&(await k("coordinator-agent.culvii.ts",nn(p)),await k("coordination-workflow.culvii.ts",an())),console.log(`${w} Initialized '${o}' project${n.here?"":` in ./${u}`}`),y.forEach(A=>console.log(` + ${A}`)),n.here||console.log(` cd ${u}`),console.log(" 1. Run `npm install`"),console.log(" 2. Replace YOUR_CREDENTIAL_ID and YOUR_MODEL_ID with your actual values from the Culvii console"),console.log(" 3. Run `culvii dev`"),await s(a$2.INIT_SUCCEEDED,{template:o,provider:a}),await j$1();}catch(l){console.error(`${x} Initialization failed: ${l.message}`),await s(a$2.INIT_FAILED,{error_class:l?.constructor?.name??"UnknownError"}),await j$1(),process.exit(1);}});}var yt=a$1();yt.noColor&&(process.env.FORCE_COLOR="0");var _e=null;function kr(e){_e=e;}async function he(e=0,t){t&&process.stderr.write(t.endsWith(`
|
|
842
842
|
`)?t:`${t}
|
|
843
|
-
`),_e&&(_e(),_e=null),await j$1(),process.exit(e);}var J=new Command;J.exitOverride(e=>{(e.code==="commander.helpDisplayed"||e.code==="commander.version")&&he(0),he(e.exitCode);});J.hook("preAction",(e,t)=>{n(t.optsWithGlobals().env);});J.name("culvii").description("Culvii CLI").version("0.0.
|
|
844
|
-
`),he(0);else {let e$1=J.command("auth").description("Authentication commands");e$1.command("login").description("Login to Culvii").action(async()=>{let{login:n}=await import('./login-
|
|
843
|
+
`),_e&&(_e(),_e=null),await j$1(),process.exit(e);}var J=new Command;J.exitOverride(e=>{(e.code==="commander.helpDisplayed"||e.code==="commander.version")&&he(0),he(e.exitCode);});J.hook("preAction",(e,t)=>{n(t.optsWithGlobals().env);});J.name("culvii").description("Culvii CLI").version("0.0.5").option("--debug","Enable debug logging to ~/.culvii/logs/cli.log").configureOutput({writeOut:e=>process.stdout.write(e),writeErr:e=>process.stderr.write(e)});async function V(e){if(_e&&(_e(),_e=null),(!yt.isTTY||yt.isCI)&&!(ie.includes("--help")||ie.includes("-h"))){console.log("Running in non-interactive mode.");return}let{render:t}=await import('ink'),n=await e,{unmount:r}=t(n);kr(r);}var ie=process.argv.slice(2);(async()=>{try{let{ConfigStore:e}=await import('./config-store-WSXGIIJ4.js');await new e().read({exitOnError:!1});}catch{await e(a$2.CLI_INSTALLED),await j$1();}})();if(ie.length===0)import('./OnboardingView-QWEF3FJU.js').then(async({OnboardingView:e})=>{let t=await import('react');await V(Promise.resolve(t.createElement(e)));});else if(ie.includes("--help")||ie.includes("-h"))import('./HelpView-IV4PD2JG.js').then(async({HelpView:e$1})=>{let t=ie[0]&&!ie[0].startsWith("-")?ie[0]:"culvii";await e(a$2.CLI_HELP_VIEWED,{command:t}),await j$1();let n=await import('react');await V(Promise.resolve(n.createElement(e$1)));});else if(ie.includes("--version")||ie.includes("-V")||ie.includes("-v"))await e(a$2.CLI_VERSION_VIEWED),process.stdout.write(J.version()+`
|
|
844
|
+
`),he(0);else {let e$1=J.command("auth").description("Authentication commands");e$1.command("login").description("Login to Culvii").action(async()=>{let{login:n}=await import('./login-DFT7D637.js');await n();}),e$1.command("logout").description("Logout of Culvii").action(async()=>{let{logout:n}=await import('./logout-OZBKJPQM.js');await n();}),J.command("login").description("Login to Culvii").action(async()=>{let{login:n}=await import('./login-DFT7D637.js');await n();}),J.command("logout").description("Logout of Culvii").action(async()=>{let{logout:n}=await import('./logout-OZBKJPQM.js');await n();}),ht(J),$t(J),Mt(J),jt(J),Yt(J),Ht(J),qt(J),Jt(J),on(J);let t=false;try{t=!!process.argv[1]&&realpathSync(process.argv[1])===fileURLToPath(import.meta.url);}catch{t=false;}t&&J.parseAsync(process.argv).catch(async n=>{let{userId:r,tenantId:i}=await d();r?await f(a$2.CLI_UNHANDLED_ERROR,r,i,{error_class:n?.constructor?.name||"UnknownError",command:process.argv.slice(2).join(" ")}):await e(a$2.CLI_UNHANDLED_ERROR,{error_class:n?.constructor?.name||"UnknownError",command:process.argv.slice(2).join(" ")}),await j$1(),console.error(n),await he(1);});}export{_e as activeUnmount,he as exit,J as program,V as renderApp,kr as setActiveUnmount};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {a as a$4}from'./chunk-JFIFRAAR.js';import {b,c,a as a$2}from'./chunk-KZG5CFSB.js';import {e,a,j,q,l,m,b as b$1,h,g,i,c as c$1,f}from'./chunk-
|
|
2
|
+
import {a as a$4}from'./chunk-JFIFRAAR.js';import {b,c,a as a$2}from'./chunk-KZG5CFSB.js';import {e,a,j,q,l,m,b as b$1,h,g,i,c as c$1,f}from'./chunk-WB3426JN.js';import {a as a$3}from'./chunk-HX54IFSD.js';import {a as a$1}from'./chunk-JYNOILCD.js';import'./chunk-57XLDHK6.js';import'./chunk-YKFGEPLO.js';import'./chunk-YPLDPHHD.js';import'./chunk-7UWDMECF.js';import ue from'open';import s from'react';import {render}from'ink';import j$1,{timingSafeEqual}from'crypto';import se from'http';import {jsx}from'react/jsx-runtime';function z(a){return a.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function ne(){let a=j$1.randomBytes(64);return z(a)}function ae(a){let E=j$1.createHash("sha256").update(a).digest();return z(E)}function oe(){let a=j$1.randomBytes(32);return z(a)}var de=`<!DOCTYPE html>
|
|
3
3
|
<html>
|
|
4
4
|
<head>
|
|
5
5
|
<meta charset="utf-8">
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {b,a,c}from'./chunk-KZG5CFSB.js';import {q,d,f,a as a$1,e,j}from'./chunk-
|
|
2
|
+
import {b,a,c}from'./chunk-KZG5CFSB.js';import {q,d,f,a as a$1,e,j}from'./chunk-WB3426JN.js';import'./chunk-HX54IFSD.js';import'./chunk-YKFGEPLO.js';import'./chunk-YPLDPHHD.js';import'./chunk-7UWDMECF.js';import w from'react';import {render}from'ink';async function S(){b.info("Logout flow started");let e$1=new a,o=false;await e$1.withLock(async()=>{let a=await e$1.get();if(!a){o=false;return}if(a.refreshToken){b.info("Revocation attempted");let g=`https://${q.cognitoDomain}/oauth2/revoke`,r=new URLSearchParams;r.set("token",a.refreshToken),r.set("client_id",q.clientId);try{await fetch(g,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r.toString()}),b.info("Revocation completed");}catch{b.info("Revocation network error ignored");}}await e$1.delete(),b.info("Tokens deleted"),o=true;let{userId:c,tenantId:u}=await d();c?await f(a$1.LOGOUT,c,u):await e(a$1.LOGOUT),await j();}),o?render(w.createElement(c,{state:{type:"logout_success"}})):render(w.createElement(c,{state:{type:"already_logged_out"}}));}
|
|
3
3
|
export{S as logout};
|
package/package.json
CHANGED
package/dist/chunk-KNDIA7WD.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import {a}from'./chunk-HX54IFSD.js';import {Analytics}from'@segment/analytics-node';var P={CLI_INSTALLED:"cli_installed",CLI_VERSION_VIEWED:"cli_version_viewed",CLI_HELP_VIEWED:"cli_help_viewed",CLI_UNHANDLED_ERROR:"cli_unhandled_error",LOGIN_STARTED:"login_started",LOGIN_SUCCEEDED:"login_succeeded",LOGIN_FAILED:"login_failed",LOGOUT:"logout",DEV_STARTED:"dev_started",DEV_STOPPED:"dev_stopped",DEV_FAILED:"dev_failed",DEPLOY_STARTED:"deploy_started",DEPLOY_SUCCEEDED:"deploy_succeeded",DEPLOY_FAILED:"deploy_failed",DEPLOY_ABORTED:"deploy_aborted",API_KEY_CREATED:"api_key_created",API_KEY_LISTED:"api_key_listed",API_KEY_REVOKED:"api_key_revoked",API_KEY_ROTATED:"api_key_rotated",API_KEY_CREATE_FAILED:"api_key_create_failed",API_KEY_LIST_FAILED:"api_key_list_failed",API_KEY_ROTATE_FAILED:"api_key_rotate_failed",API_KEY_REVOKE_FAILED:"api_key_revoke_failed",TENANT_SWITCHED:"tenant_switched",ENV_SWITCHED:"env_switched",ENV_SWITCH_FAILED:"env_switch_failed",WORKSPACE_CREATED:"workspace_created",WORKSPACE_LISTED:"workspace_listed",TENANT_SWITCH_FAILED:"tenant_switch_failed",WORKSPACE_CREATE_FAILED:"workspace_create_failed",WORKSPACE_LIST_FAILED:"workspace_list_failed",WHOAMI_VIEWED:"whoami_viewed",RENAME_STARTED:"rename_started",RENAME_SUCCEEDED:"rename_succeeded",RENAME_FAILED:"rename_failed",INIT_STARTED:"init_started",INIT_SUCCEEDED:"init_succeeded",INIT_FAILED:"init_failed"},D="byn3jQco5axUIlfeohbQYYPGrZgGpw7A",x=process.env.CULVII_TELEMETRY!=="false",o=x?new Analytics({writeKey:D,flushAt:1,flushInterval:0}):null;function m(){return {surface:"cli",cli_version:"0.0.3",node_version:process.version,os:process.platform,arch:process.arch}}var c=null;async function w(){if(c)return c;try{let{ConfigStore:n}=await import('./config-store-WSXGIIJ4.js');c=(await new n().read({exitOnError:!1})).anonymousId??"unknown";}catch{c="unknown";}return c}var d=null,E=null,f=false;function U(){f=false;}async function y(){if(f)return {userId:d,tenantId:E};try{let{ConfigStore:n}=await import('./config-store-WSXGIIJ4.js'),e=await new n().read({exitOnError:!1}),i=e.contexts[e.active];E=i?.tenant_id??null,d=i?.user_id??e.anonymousId??null;}catch{d=null,E=null;}finally{f=true;}return {userId:d,tenantId:E}}async function C(n,t={},e,i){if(o)try{let r=await y(),a=e??r.userId,s=i!==void 0?i:r.tenantId,_=await w();a?o.track({userId:a,event:n,properties:{...m(),...s?{tenant_id:s}:{},...t}}):o.track({anonymousId:_,event:n,properties:{...m(),...t}});}catch{}}async function V(n,t,e,i={}){await C(n,i,t,e);}async function F(n,t={}){if(o)try{o.identify({userId:n,traits:t});}catch{}}async function K(n,t){if(o)try{o.alias({userId:n,previousId:t});}catch{}}async function Y(n,t,e={}){if(o)try{o.group({userId:n,groupId:t,traits:e});}catch{}}var l=null;async function p(){if(o)return l||(l=o.flush({timeout:3e3}).catch(()=>{}).finally(()=>{l=null;}),l)}var u={dev:"development",sandbox:"sandbox",prod:"production"};function L(n){let t=Object.entries(u).find(([,e])=>e===n);return t?t[0]:null}var k=["dev","sandbox","prod"];function W(n){let t=new Set(n.map(L).filter(e=>e!==null));return k.find(e=>t.has(e))??null}var v;function G(n){v=n&&n in u?n:void 0;}function H(){return v}var R="https://api.platform.culvii.com",S={apiBaseUrl:R,clientId:"375hlin7p89s5g57d5lacffl4k",cognitoDomain:"https://us-east-23rroc3geo.auth.us-east-2.amazoncognito.com"},I=process.env.CULVII_ENV,N=I&&I in u?I:"dev",O={...S,logicalEnvironment:N,scopes:["openid","email","profile"],callbackPorts:[52700,52701,52702,52703,52704,52705,52706,52707,52708,52709],callbackPath:"/callback"};async function M(n){let e=await new a().read(),i=e.contexts[e.active];i||(console.error("Error: Active context key not found in contexts in ~/.culvii/config."),console.error("Please run `culvii login` to authenticate and configure your active context."),await p(),process.exit(1));let r={...i},a$1=n?.env??v;a$1&&(r.environment=a$1);let s=r.environment||"dev";r.environment_id=r.environment_ids?.[s]??r.environment_id,r.workspace_ids&&s in r.workspace_ids&&(r.workspace_id=r.workspace_ids[s]??null),r.workspace_slugs&&s in r.workspace_slugs&&(r.workspace_slug=r.workspace_slugs[s]??null),n?.workspace&&(r.workspace_id=n.workspace);let _=O.apiBaseUrl;return _||(console.error("Error: No API URL found for the configured platform."),await p(),process.exit(1)),{apiUrl:_,context:r}}function j(n){let t=n.environment||"dev",e=n.environment_ids?.[t]??n.environment_id;return {...n.tenant_id?{"x-tenant-id":n.tenant_id}:{},...e?{"x-environment-id":e}:{"x-environment-slug":u[t]}}}
|
|
3
|
-
export{P as a,w as b,U as c,y as d,C as e,V as f,F as g,K as h,Y as i,p as j,u as k,L as l,W as m,G as n,H as o,N as p,O as q,M as r,j as s};
|