@cognite/cli 1.10.0-alpha.2 → 1.11.0
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/chunk-E5SIBEEX.js +12 -0
- package/dist/cli/cli.js +134 -134
- package/dist/deploy/index.js +1 -1
- package/dist/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-NZKQBLAX.js +0 -12
package/dist/cli/cli.js
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
3
|
-
Cancelled.`),process.exit(130)),console.error(e),process.exit(1)}),process.on("unhandledRejection",e=>{
|
|
4
|
-
Cancelled.`),process.exit(130)),console.error(e),process.exit(1)}))}r(
|
|
5
|
-
${e}`,{hint:"Run this command from an agent project directory, or pass the directory as an argument.",shouldReport:!1});if(t.length===1)return
|
|
2
|
+
var $l=Object.defineProperty;var Gr=e=>{throw TypeError(e)};var r=(e,t)=>$l(e,"name",{value:t,configurable:!0});var Yr=(e,t,n)=>t.has(e)||Gr("Cannot "+n);var Pt=(e,t,n)=>(Yr(e,t,"read from private field"),n?n.call(e):t.get(e)),zr=(e,t,n)=>t.has(e)?Gr("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),qr=(e,t,n,o)=>(Yr(e,t,"write to private field"),o?o.call(e,n):t.set(e,n),n);import{writeSync as tv}from"fs";import{Command as nv}from"commander";var Jn=class Jn extends Error{constructor(t,n={}){super(t),this.name="HintedError",n.cause!==void 0&&(this.cause=n.cause);let o=this.deriveDefaults(n);this.hint=n.hint??o.hint,this.helpUrl=n.helpUrl??o.helpUrl,this.shouldReport=n.shouldReport??!0}deriveDefaults(t){return{hint:Ml(t.cause)}}};r(Jn,"HintedError");var m=Jn;function ue(e){return e instanceof m}r(ue,"isHintedError");var Jr="https://docs.cognite.com/cdf/access/",Ol="https://status.cognite.com";function Fl(e){switch(e){case 401:return{hint:"Your credentials are invalid or expired. Check your client ID and secret.",helpUrl:Jr};case 403:return{hint:"You don't have the required CDF capabilities. Please contact your CDF admin.",helpUrl:Jr};case 413:return{hint:"The deployment exceeds the App Hosting size limit. Reduce the build output \u2014 remove unused assets, code-split bundles, or strip source maps."};case 429:return{hint:"You are being rate limited. Wait a few moments and retry. If this persists, contact CDF support."};case 500:case 502:case 503:case 504:return{hint:"CDF service error. The issue is on the server side. Check the status page and retry shortly.",helpUrl:Ol};default:return{}}}r(Fl,"defaultHintForStatus");var Wn=class Wn extends m{constructor(t,n){super(t,n),this.name="HintedHttpError",this.httpStatusCode=n.httpStatusCode,this.requestUrl=n.requestUrl,this.responseBody=n.responseBody}deriveDefaults(t){let{httpStatusCode:n}=t,o=Fl(n),i=super.deriveDefaults(t);return{hint:o.hint??i.hint,helpUrl:o.helpUrl}}};r(Wn,"HintedHttpError");var ie=Wn;function Tt(e){return e instanceof ie}r(Tt,"isHintedHttpError");function Ll(e,t){if(e)switch(e){case"ENOTFOUND":return t.hostname?`DNS lookup failed for ${t.hostname}. Check your network, VPN, or proxy settings.`:"DNS lookup failed. Check your network, VPN, or proxy settings.";case"ECONNREFUSED":return t.hostname&&t.port?`Connection refused by ${t.hostname}:${t.port}. The service may be down or the port may be wrong.`:"Connection refused. The service may be down or the port may be wrong.";case"ECONNRESET":return"Connection was reset. The server closed the connection unexpectedly; check for proxy/firewall interference and retry.";case"ETIMEDOUT":return"Connection timed out. Check your network, VPN, or proxy settings, and retry.";case"EAI_AGAIN":return"Temporary DNS failure. Retry shortly; if it persists, check your DNS configuration.";case"CERT_HAS_EXPIRED":case"UNABLE_TO_VERIFY_LEAF_SIGNATURE":case"SELF_SIGNED_CERT_IN_CHAIN":return"TLS certificate validation failed. Check system clock and CA trust store; if you use a corporate proxy, ensure its root cert is trusted.";case"EACCES":return t.path?`Permission denied: ${t.path}. Check file ownership and permissions.`:"Permission denied. Check file ownership and permissions.";case"ENOENT":return t.path?`File or directory not found: ${t.path}.`:"File or directory not found.";case"EISDIR":return t.path?`Expected a file but found a directory: ${t.path}.`:"Expected a file but found a directory.";case"ENOSPC":return"No space left on device. Free up disk space and retry.";case"EADDRINUSE":return t.port?`Port ${t.port} is already in use. Stop the process using it or pick a different port.`:"Address is already in use. Stop the conflicting process or change the port.";case"EMFILE":case"ENFILE":return"Too many open files. Close other programs or raise the file descriptor limit.";default:return}}r(Ll,"hintForErrno");function Ml(e){let t=e,n=new Set;for(;t!=null&&!n.has(t)&&(n.add(t),typeof t=="object");){let o=t,i=Ll(o.code,o);if(i!==void 0)return i;t=o.cause}}r(Ml,"hintForCause");import{Command as Ul,Option as Rt}from"commander";var Wr=Object.freeze({interactive:new Rt("--interactive","Use browser-based authentication instead of env-var credentials").default(!1),baseUrl:new Rt("--base-url <url>","CDF base URL (only with --interactive)"),project:new Rt("--project <project>","CDF project name (only with --interactive)"),org:new Rt("--org <org>","Organization hint for login (only with --interactive)")}),lv=Object.values(Wr).map(e=>e.long),Dt=class Dt extends Ul{constructor(t){super(t);for(let n of Object.values(Wr))this.addOption(n)}createCommand(t){return new Dt(t)}};r(Dt,"BaseCommand");var be=Dt,Zn=class Zn extends be{constructor(t){super(t),this.configure()}};r(Zn,"CommandGroup");var It=Zn;import{performance as ei}from"perf_hooks";import{existsSync as zl,readFileSync as ql}from"fs";import{resolve as Jl}from"path";import{array as Zr,boolean as _l,check as Ye,forward as ze,literal as Nl,maxLength as jl,minLength as Hl,nonEmpty as De,object as Xr,optional as xe,picklist as Bl,pipe as me,safeParse as Kl,string as Q,url as Qr}from"valibot";var Xn=me(Q(),De("must not be empty")),Qn=me(Q(),De("must not be empty"),jl(256,"must be 256 characters or fewer")),eo=me(Q(),De("must not be empty"),Qr("must be a valid URL")),Vl=me(Q(),De("must not be empty"),Qr("must be a valid URL")),to=me(Q(),De("must not be empty")),no=me(Q(),De("must not be empty")),Gl=me(Xr({org:to,project:no,baseUrl:eo,deployClientId:xe(Q(),""),deploySecretName:xe(Q(),""),published:xe(_l(),!1),idpType:xe(Bl(["cdf","entra_id","oauth"]),"cdf"),tenantId:xe(Q()),scopes:xe(Zr(me(Q(),De("must not be empty")))),tokenUrl:xe(Vl)}),ze(Ye(e=>e.idpType!=="entra_id"||!!e.tenantId,'must be set when idpType is "entra_id"'),["tenantId"]),ze(Ye(e=>e.idpType!=="oauth"||!!e.tokenUrl,'must be set when idpType is "oauth"'),["tokenUrl"]),ze(Ye(e=>!e.tokenUrl||e.idpType==="oauth",'must only be set when idpType is "oauth"'),["tokenUrl"]),ze(Ye(e=>e.idpType!=="oauth"||!!e.deployClientId,'must be set when idpType is "oauth"'),["deployClientId"]),ze(Ye(e=>e.idpType!=="oauth"||!!e.deploySecretName,'must be set when idpType is "oauth"'),["deploySecretName"]),ze(Ye(e=>!e.deployClientId||!!e.deploySecretName,"must be set when deployClientId is set"),["deploySecretName"])),Yl=Xr({name:Xn,externalId:Qn,versionTag:me(Q(),De("must not be empty")),description:xe(Q(),""),deployments:me(Zr(Gl),Hl(1,"must contain at least one deployment")),infra:xe(Nl("appsApi"))});function oo(e){let t=Kl(Yl,e);if(t.success)return t.output;let n=t.issues[0],o=n.path?.map(s=>s.key).join(".")??"",i=o?`"${o}" `:"";throw new Error(`app.json: ${i}${n.message}`)}r(oo,"validateAppConfig");function k(e,t={}){let{validator:n=oo,existsSync:o=zl,readFileSync:i=ql}=t,s=Jl(e,"app.json");if(!o(s))throw new Error(`No app.json found at ${s}. Make sure you're running this command from your app's root directory.`);let a=i(s,"utf-8"),c;try{c=JSON.parse(a)}catch{throw new Error("Failed to parse app.json \u2014 check that it contains valid JSON.")}return n(c)}r(k,"loadAppConfig");var qe=1e3,$t;function Wl(){$t=ei.now()}r(Wl,"markActionStart");function Zl(){$t=void 0}r(Zl,"resetActionStart");function ro(){if($t!==void 0)return Math.max(0,Math.round(ei.now()-$t))}r(ro,"snapshotActionDurationMs");function ti(){let e=ro();return Zl(),{...e!==void 0&&{actionDurationMs:e}}}r(ti,"takePerformanceFields");var Xl=new Set(["baseUrl","url","project","deployment","source","path","name","displayName","description","externalId"]);function io(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>typeof n=="boolean"?[t,n]:Xl.has(t)?[t,n]:[t,"[REDACTED]"]))}r(io,"sanitizeOptions");function Ql(e){let t=[],n=e;for(;n;)n.parent&&t.unshift(n.name()),n=n.parent;return t.join(" ")}r(Ql,"getCommandPath");function ni(e){try{let t=e(process.cwd()),n=t.deployments[0];return{appName:t.name,appExternalId:t.externalId,appVersionTag:t.versionTag,...n&&{cogniteOrg:n.org,cogniteProject:n.project}}}catch{return{}}}r(ni,"tryLoadAppConfig");function so(e){return e.filter(t=>!t.startsWith("-")).join(" ")||"unknown"}r(so,"commandFromArgv");function oi(e,t,n=k){e.hook("preAction",()=>{Wl()}),e.hook("postAction",async(o,i)=>{try{let s={command:Ql(i),options:io(i.opts()),success:!0,...ni(n),...ti()};t.track("Flows.CLI.Command",{...s}),await t.flush(qe)}catch{}})}r(oi,"instrument");async function ri(e,t,n=k){try{let o={command:so(t),options:{},success:!1,...ni(n),...ti()};e.track("Flows.CLI.Command",{...o}),await e.flush(qe)}catch{}}r(ri,"trackFailure");var ep=Object.freeze({create:"Flows.CLI.Agents.Create",push:"Flows.CLI.Agents.Push",open:"Flows.CLI.Agents.Open",publish:"Flows.CLI.Agents.Publish",unpublish:"Flows.CLI.Agents.Unpublish",pull:"Flows.CLI.Agents.Pull",list:"Flows.CLI.Agents.List",status:"Flows.CLI.Agents.Status",eval:"Flows.CLI.Agents.Eval"});async function ii(e,t){if(!e||t.name()==="eval")return;let n=ep[t.name()];if(n)try{e.track(n,{command:t.name(),options:io(t.optsWithGlobals()),success:!0}),await e.flush(qe)}catch{}}r(ii,"trackAgentsCommand");import{existsSync as fs}from"fs";import{cp as yu,mkdir as hs,readFile as Oo,writeFile as rn}from"fs/promises";import{basename as Fo,dirname as Su,join as he,resolve as Lo}from"path";import{fileURLToPath as vu}from"url";import{Option as Be}from"commander";import tp,{Chalk as np}from"chalk";var rt=new np({level:0});function P(e){return e.isTTY?tp:rt}r(P,"chalkForStream");var op="ERR_USE_AFTER_CLOSE";function ai(e){return e instanceof Error&&"code"in e&&e.code===op}r(ai,"isReadlineClosedError");function rp(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}r(rp,"isPlainObject");function ao(e){return e==null||ai(e)?!0:e instanceof Error?!1:!!(typeof e=="object"&&e!==null&&rp(e)&&Object.keys(e).length===0)}r(ao,"isPromptCancel");var si=!1;function Ot(){si||(si=!0,process.on("uncaughtException",e=>{ai(e)&&(console.error(`
|
|
3
|
+
Cancelled.`),process.exit(130)),console.error(e),process.exit(1)}),process.on("unhandledRejection",e=>{ao(e)&&(console.error(`
|
|
4
|
+
Cancelled.`),process.exit(130)),console.error(e),process.exit(1)}))}r(Ot,"installCancelHandler");import{readdir as ip,readFile as sp}from"fs/promises";import{basename as di,join as ui}from"path";import{array as st,looseObject as mi,nullable as ap,object as gi,optional as se,parse as fi,record as cp,string as G,unknown as lp}from"valibot";import{parse as pp,stringify as dp}from"yaml";var w=Object.freeze({configSuffix:".agent.yaml",configGlob:"*.agent.yaml",readme:"README.md",readmeTemplate:"README_TEMPLATE.md",agentsMd:"AGENTS.md",agentsMdTemplate:"AGENTS_TEMPLATE.md",evalDir:"eval",evalCases:"eval.yaml",evalCasesTemplate:"EVAL_CASES_TEMPLATE.yaml"});function $e(e){return`${e.replace(/[^A-Za-z0-9._-]/g,"_")}${w.configSuffix}`}r($e,"agentConfigFileName");var it=`${w.evalDir}/${w.evalCases}`,ci={dirName:"my-agent"},li=[".cursor/skills",".claude/skills"];var pi="cdf_industrial_v4";var up=gi({agentExternalId:G()}),mp=gi({question:G()}),gp=mi({name:G(),type:G(),description:G(),instructions:se(G()),configuration:se(ap(cp(G(),lp())))}),hi=mi({externalId:G(),name:G(),description:se(G()),instructions:se(G()),model:se(G()),runtimeVersion:se(G()),labels:se(st(G())),exampleQuestions:se(st(mp)),skills:se(st(G())),subagents:se(st(up)),tools:se(st(gp),[])});function fp(e){let t=pp(e);return fi(hi,t)}r(fp,"parseAgentYaml");function ge(e){let t=fi(hi,e);return dp(t,{lineWidth:0})}r(ge,"serializeAgentYaml");async function at(e){let t;try{t=await ip(e,{withFileTypes:!0})}catch{return[]}let n=w.configSuffix.toLowerCase();return t.filter(o=>o.name.toLowerCase().endsWith(n)&&!o.isDirectory()).map(o=>o.name).sort()}r(at,"findAgentYamlNames");async function hp(e){let t=await at(e);if(t.length===0)throw new m(`No ${w.configGlob} found in:
|
|
5
|
+
${e}`,{hint:"Run this command from an agent project directory, or pass the directory as an argument.",shouldReport:!1});if(t.length===1)return ui(e,t[0]);let n=$e(di(e)).toLowerCase(),o=t.find(i=>i.toLowerCase()===n);if(o!==void 0)return ui(e,o);throw new m(`Found multiple ${w.configGlob} files in:
|
|
6
6
|
${e}
|
|
7
7
|
${t.map(i=>` - ${i}`).join(`
|
|
8
|
-
`)}`,{hint:`Each agent needs its own directory. Move the extra definitions elsewhere, or name the one you want after its folder (${
|
|
9
|
-
`);function
|
|
10
|
-
`,{mode:384});try{n.renameSync(i,n.sessionFile)}catch(s){throw n.rmSync(i,{force:!0}),s}}r(
|
|
11
|
-
`),
|
|
12
|
-
`);let g=r(()=>{},"finish"),h=new Promise(
|
|
13
|
-
`)}}}r(
|
|
8
|
+
`)}`,{hint:`Each agent needs its own directory. Move the extra definitions elsewhere, or name the one you want after its folder (${$e(di(e))}).`,shouldReport:!1})}r(hp,"resolveAgentYamlPath");async function Oe(e){return(await ct(e)).agent}r(Oe,"readAgentYaml");async function ct(e){let t=await hp(e),n=await sp(t,"utf8");return{path:t,agent:fp(n)}}r(ct,"loadAgentYaml");function Ue(e){let{createdTime:t,lastUpdatedTime:n,ownerId:o,...i}=e;return i}r(Ue,"toAgentCreate");import yi from"enquirer";var co=class co{constructor(t,n,o,i=[],s=yi.prompt.bind(yi)){this.dirArg=t;this.flags=n;this.isInteractive=o;this.availableModels=i;this.promptFn=s}async resolve(){let t=await this.getDirName();return{dirName:t,externalId:this.flags.externalId?.trim()||t,name:await this.getDisplayName(t),description:await this.getDescription(),model:await this.getModel(),instructions:await this.getInstructions(),runtimeVersion:this.flags.runtimeVersion?.trim()||void 0}}async getDirName(){return this.dirArg?this.dirArg:this.isInteractive?lt(this.promptFn,{message:"Agent name (used as directory and externalId)",initial:"my-agent",validate:Si("Agent name")}):ci.dirName}async getDisplayName(t){let n=this.flags.displayName?.trim();return n||(this.isInteractive?lt(this.promptFn,{message:"Display name",initial:t,validate:Si("Display name")}):t)}async getDescription(){let t=this.flags.description?.trim();if(t)return t;if(this.isInteractive){let n=await lt(this.promptFn,{message:"Description (optional)",initial:"",validate:r(()=>!0,"validate")});if(n)return n}}async getModel(){let t=this.flags.model?.trim();if(t)return t;if(this.isInteractive&&this.availableModels.length>0)return lt(this.promptFn,{message:"Model",choices:this.availableModels,initial:0})}async getInstructions(){let t=this.flags.instructions?.trim();if(t)return t;if(this.isInteractive){let n=await lt(this.promptFn,{message:"Agent instructions (custom behavior; built-in platform guidance applies automatically)",initial:"",validate:r(()=>!0,"validate")});if(n)return n}return yp}};r(co,"AgentCreateResolver");var Ft=co,yp=["Help users explore and understand the data in this project.","Use the available tools to retrieve data before answering.","When the data is insufficient, say so rather than guessing."].join(`
|
|
9
|
+
`);function Si(e){return r(function(n){return n.trim()?!0:`${e} is required`},"_requiredInner")}r(Si,"required");async function lt(e,t){if("choices"in t){let{value:o}=await e({type:"select",name:"value",...t});return o.trim()}let{value:n}=await e({type:"input",name:"value",...t});return n.trim()}r(lt,"ask");var Lt={"cdf-version":"beta"};function ee(e){async function t(l){let p=c(e.project).concat("/ai/agents");return(await e.post(p,{data:{items:[l]},headers:Lt})).data.items[0]}r(t,"upsert");async function n(l){let p=c(e.project).concat("/ai/agents/byids"),d;try{d=await e.post(p,{data:{items:[{externalId:l}]},headers:Lt})}catch(f){throw o(f)&&f.status===422?new m(`Agent "${l}" not found.`,{hint:"Check the externalId and try again.",shouldReport:!1}):f}let u=d.data?.items??[];if(!u.length)throw new m(`Agent "${l}" not found.`,{hint:"Check the externalId and try again.",shouldReport:!1});return u[0]}r(n,"getByExternalId");function o(l){return typeof l=="object"&&l!==null&&"status"in l&&typeof l.status=="number"}r(o,"isHttpError");async function i(){let l=c(e.project).concat("/ai/agents");return(await e.get(l,{headers:Lt})).data}r(i,"list");async function s(){let l=c(e.project).concat("/ai/availability");return(await e.get(l,{headers:Lt})).data}r(s,"getServiceAvailability");async function a(){return(await s()).items.find(d=>d.path==="/ai/agents")?.supportedLanguageModels??[]}r(a,"getAvailableModels");function c(l){return`/api/v1/projects/${encodeURIComponent(l)}`}return r(c,"getBaseUrl"),{upsert:t,getByExternalId:n,list:i,getServiceAvailability:s,getAvailableModels:a}}r(ee,"getAgentsService");import{CogniteClient as mu}from"@cognite/sdk";import{existsSync as Ep,mkdirSync as bp,readFileSync as xp,renameSync as kp,rmSync as Pp,writeFileSync as Tp}from"fs";import{dirname as Rp}from"path";import{isoTimestamp as Ip,literal as Dp,nonEmpty as Ei,object as $p,pipe as bi,safeParse as Op,string as xi}from"valibot";import{homedir as Sp}from"os";import{join as lo}from"path";function D(e={}){let{env:t=process.env,homedir:n=Sp}=e,o=t.COGNITE_CLI_HOME?.trim()||lo(n(),".cognite-cli");return{home:o,keysDir:lo(o,"keys"),sessionFile:lo(o,"session.json")}}r(D,"getConfig");import{inspect as vp}from"util";var po="[REDACTED]",_e,Mt=class Mt{constructor(t){zr(this,_e);qr(this,_e,t)}toString(){return po}toJSON(){return po}[vp.custom](){return po}expose(){return Pt(this,_e)}equals(t){return Pt(this,_e)===Pt(t,_e)}static from(t){return new Mt(t)}};_e=new WeakMap,r(Mt,"SensitiveString");var b=Mt;var Ne="cognite-cli-session",wp=1280,Cp=process.platform==="win32"?wp:1/0,uo="cognite-session/chunks=";function Ut(e,t){return`${e}/chunk/${t}`}r(Ut,"chunkAccount");function mo(e){if(!e.startsWith(uo))return null;let t=Number(e.slice(uo.length));return Number.isFinite(t)&&t>0?t:null}r(mo,"parseChunkCount");async function Ap(e,t){let{Entry:n}=await import("@napi-rs/keyring"),o=new n(e,t);return{setPassword:r(i=>o.setPassword(i),"setPassword"),getPassword:r(()=>o.getPassword(),"getPassword"),deleteCredential:r(()=>o.deleteCredential(),"deleteCredential")}}r(Ap,"defaultCreateEntry");function go(e){return{createEntry:e.createEntry??Ap,chunkSize:e.chunkSize??Cp}}r(go,"resolveDeps");async function vi(e,t,n={}){let{createEntry:o,chunkSize:i}=go(n),s=await o(Ne,e),a=s.getPassword();if(a!==null){let p=mo(a);if(p!==null)for(let d=0;d<p;d++)(await o(Ne,Ut(e,d))).deleteCredential()}let c=t.expose();if(c.length<=i){s.setPassword(c);return}let l=[];for(let p=0;p<c.length;p+=i)l.push(c.slice(p,p+i));s.setPassword(`${uo}${l.length}`);for(let p=0;p<l.length;p++)(await o(Ne,Ut(e,p))).setPassword(l[p])}r(vi,"storeSessionToken");async function wi(e,t={}){let{createEntry:n}=go(t),o=(await n(Ne,e)).getPassword();if(o===null)return null;let i=mo(o);if(i===null)return b.from(o);let s=[];for(let a=0;a<i;a++){let c=(await n(Ne,Ut(e,a))).getPassword();if(c===null)return null;s.push(c)}return b.from(s.join(""))}r(wi,"readSessionToken");async function Ci(e,t={}){let{createEntry:n}=go(t),o=await n(Ne,e),i=o.getPassword();if(i!==null){let s=mo(i);if(s!==null)for(let a=0;a<s;a++)(await n(Ne,Ut(e,a))).deleteCredential()}o.deleteCredential()}r(Ci,"deleteSessionToken");var _t=1,ho=r(e=>`${e}/accessToken`,"accessTokenAccount"),yo=r(e=>`${e}/refreshToken`,"refreshTokenAccount"),Ai=bi(xi(),Ei("must not be empty"),Ip("must be an ISO 8601 timestamp")),Fp=$p({version:Dp(_t),org:bi(xi(),Ei("must not be empty")),accessTokenExpiresAt:Ai,refreshTokenExpiresAt:Ai});function Nt(e){return{sessionFile:e.sessionFile??D().sessionFile,existsSync:e.existsSync??Ep,readFileSync:e.readFileSync??xp,writeFileSync:e.writeFileSync??Tp,mkdirSync:e.mkdirSync??bp,renameSync:e.renameSync??kp,rmSync:e.rmSync??Pp,storeSecret:e.storeSecret??vi,readSecret:e.readSecret??wi,deleteSecret:e.deleteSecret??Ci}}r(Nt,"resolveDeps");var fo="Run `npx @cognite/cli auth logout` to clear it, then `npx @cognite/cli auth login` to sign in again.";function ke(e={}){let t=Nt(e);if(!t.existsSync(t.sessionFile))return null;let n=t.readFileSync(t.sessionFile,"utf-8"),o;try{o=JSON.parse(n)}catch{throw new Error(`Session file at ${t.sessionFile} is not valid JSON. ${fo}`)}let i=Op(Fp,o);if(!i.success){let s=i.issues[0],a=s.path?.map(l=>l.key).join(".")??"",c=a?`"${a}" `:"";throw new Error(`Session file is invalid: ${c}${s.message}. ${fo}`)}return i.output}r(ke,"readSessionMetadata");async function pt(e={}){let t=Nt(e),n=ke(e);if(!n)return null;let[o,i]=await Promise.all([t.readSecret(ho(n.org)),t.readSecret(yo(n.org))]);if(!o||!i)throw new Error(`Session metadata exists but its tokens are missing from the keychain. ${fo}`);return{...n,accessToken:o,refreshToken:i}}r(pt,"readSession");async function jt(e,t={}){let n=Nt(t);await n.storeSecret(ho(e.org),e.accessToken),await n.storeSecret(yo(e.org),e.refreshToken);let o={version:_t,org:e.org,accessTokenExpiresAt:e.accessTokenExpiresAt,refreshTokenExpiresAt:e.refreshTokenExpiresAt};n.mkdirSync(Rp(n.sessionFile),{recursive:!0,mode:448});let i=`${n.sessionFile}.tmp`;n.writeFileSync(i,`${JSON.stringify(o,null,2)}
|
|
10
|
+
`,{mode:384});try{n.renameSync(i,n.sessionFile)}catch(s){throw n.rmSync(i,{force:!0}),s}}r(jt,"writeSession");function Lp(e){if(!e.existsSync(e.sessionFile))return null;try{let t=JSON.parse(e.readFileSync(e.sessionFile,"utf-8"));if(t&&typeof t=="object"&&"org"in t){let n=t.org;return typeof n=="string"&&n.length>0?n:null}}catch{}return null}r(Lp,"readOrgLoosely");async function Ht(e={}){let t=Nt(e),n=Lp(t);t.rmSync(t.sessionFile,{force:!0}),n&&(await t.deleteSecret(ho(n)),await t.deleteSecret(yo(n)))}r(Ht,"clearSession");var Mp=300*1e3;function je(e,t=new Date){let n=t.getTime();return Date.parse(e.refreshTokenExpiresAt)<=n?"EXPIRED":Date.parse(e.accessTokenExpiresAt)-n<=Mp?"EXPIRING":"VALID"}r(je,"tokenState");import bd from"path";import{lock as xd}from"proper-lockfile";import{None as md,discovery as gd,tokenRevocation as fd,refreshTokenGrant as hd}from"openid-client";import{buildAuthorizationUrl as td,calculatePKCECodeChallenge as nd,discovery as od,None as rd,randomPKCECodeVerifier as id,randomState as sd}from"openid-client";import ki from"mixpanel";var Up="5c4d853e7c3b77b1eb4468d5329b278c",_p="api-eu.mixpanel.com",dt="cognite-cli",Np=2e3,Pi={env:process.env,init:ki.init.bind(ki)},jp={track:r(()=>{},"track"),flush:r(async()=>{},"flush")};function So(e=process.env){return e.COGNITE_TELEMETRY_DISABLED==="1"||e.DO_NOT_TRACK==="1"}r(So,"isTelemetryDisabled");function Hp(e=process.env){if(e.GITHUB_ACTIONS)return"github-actions";if(e.TF_BUILD)return"azure-devops";if(e.GITLAB_CI)return"gitlab-ci";if(e.CIRCLECI)return"circleci";if(e.TRAVIS)return"travis-ci";if(e.BUILDKITE)return"buildkite";if(e.DRONE)return"drone";if(e.SEMAPHORE)return"semaphore";if(e.TEAMCITY_VERSION)return"teamcity";if(e.APPVEYOR)return"appveyor";if(e.CODEBUILD_BUILD_ID)return"aws-codebuild";if(e.HEROKU_TEST_RUN_ID)return"heroku-ci";if(e.BITBUCKET_BUILD_NUMBER)return"bitbucket-pipelines";if(e.JENKINS_URL||e.JENKINS_HOME)return"jenkins";if(e.CI&&e.CI!=="false"&&e.CI!=="0")return"ci-generic"}r(Hp,"detectCiEnvironment");function Bp(e){return e.COGNITE_TELEMETRY_DEBUG==="1"}r(Bp,"isDebug");function Bt(e={}){let t=e.env??Pi.env,n=e.init??Pi.init,o=e.packageName,i=e.cliVersion,s=Bp(t),a=Hp(t);if(So(t))return s&&process.stderr.write(`[telemetry] disabled \u2014 noop tracker
|
|
11
|
+
`),jp;let c,l=new Set;function p(){if(c)return c;try{return c=n(Up,{geolocate:!1,keepAlive:!1,host:_p}),c}catch{return}}return r(p,"getClient"),{track(d,u={}){let f=p();if(!f)return;let y={...u,applicationId:dt,...o&&{packageName:o},...i&&{cliVersion:i},nodeVersion:process.version,platform:process.platform,...a&&{ciEnvironment:a}};s&&process.stderr.write(`[telemetry] track ${d} ${JSON.stringify(y)}
|
|
12
|
+
`);let g=r(()=>{},"finish"),h=new Promise(v=>{g=v});l.add(h);try{f.track(d,y,g)}catch{g()}h.finally(()=>l.delete(h))},async flush(d=Np){if(l.size===0)return;let u,f=new Promise(y=>{u=setTimeout(y,d),u.unref?.()});try{await Promise.race([Promise.allSettled([...l]),f])}finally{u&&clearTimeout(u)}s&&process.stderr.write(`[telemetry] flush done (${l.size} still pending)
|
|
13
|
+
`)}}}r(Bt,"createTelemetry");var Kt={min:3100,max:3110},Kp=`${Kt.min}-${Kt.max}`,ut=`3000, or ${Kp}`;function Vt(e){return Number.isInteger(e)?e===3e3||e>=Kt.min&&e<=Kt.max:!1}r(Vt,"isAllowedCallbackPort");function Gt(e){return`Unsupported callback port ${typeof e=="string"?`"${e}"`:e} \u2014 only ${ut} are supported.`}r(Gt,"formatUnsupportedCallbackPort");import Gp from"http";import{authorizationCodeGrant as Yp}from"openid-client";function Ti(e){return e.replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t]??t)}r(Ti,"escapeHtml");function vo(e,t,n){let o=Ti(t),i=Ti(n);return`<html><body style="font-family: system-ui; padding: 40px; text-align: center;">
|
|
14
14
|
<h1>${o}</h1><p>${i}</p><p>You can close this window.</p>${e==="success"?`<style>
|
|
15
15
|
@keyframes checkmark {
|
|
16
16
|
0% { transform: scale(0); }
|
|
@@ -19,20 +19,20 @@ ${t.map(i=>` - ${i}`).join(`
|
|
|
19
19
|
}
|
|
20
20
|
h1 { animation: checkmark 0.5s ease-out; }
|
|
21
21
|
</style>`:""}
|
|
22
|
-
</body></html>`}r(
|
|
23
|
-
`),s.log(`\u{1F4E1} Fetching OpenID configuration from ${t.authority}...`);let y=await
|
|
22
|
+
</body></html>`}r(vo,"generateHtml");import Vp from"net";function Ri(e,t){return new Promise(n=>{let o=new Vp.Socket,i=r(s=>{o.removeAllListeners(),o.destroy(),n(s)},"done");o.setTimeout(500),o.once("connect",()=>i(!1)),o.once("timeout",()=>i(!0)),o.once("error",()=>i(!0)),o.connect(e,t)})}r(Ri,"isHostPortFree");function Yt(e){return`Port ${e} is already in use. Pin another callback port with --port <port> \u2014 supported ports are ${ut}.`}r(Yt,"freePortHint");async function Ii(e){if(e<0)throw new Error(`Invalid port: ${e}`);return e===0?!0:(await Promise.all([Ri(e,"127.0.0.1"),Ri(e,"::1")])).every(Boolean)}r(Ii,"isPortFree");async function zp(e,t,n,o,i,s){let{authorizationCodeGrant:a,logger:c}=s,l=new URL(e.url??"/",`http://${e.headers.host??"localhost"}`);if(l.pathname!=="/")return t.writeHead(404),t.end("Not found"),{shouldClose:!1};try{c.log("\u{1F504} Exchanging authorization code for tokens...");let p=await a(n,l,{pkceCodeVerifier:o,expectedState:i});return t.writeHead(200,{"Content-Type":"text/html",Connection:"close"}),t.end(vo("success","Login Successful!","You can close this window and return to the terminal.")),{shouldClose:!0,tokens:p}}catch(p){let d=p instanceof Error?p:new Error(String(p));return t.writeHead(400,{"Content-Type":"text/html",Connection:"close"}),t.end(vo("error","Authentication Error",d.message)),{shouldClose:!0,error:d}}}r(zp,"handleCallback");function qp(e){let t=e/6e4,n=Math.round(t*10)/10;return`${n} ${n===1?"minute":"minutes"}`}r(qp,"formatTimeoutMinutes");function Di(e,t,n,o,i={createServer:Gp.createServer,setTimeout:globalThis.setTimeout,clearTimeout:globalThis.clearTimeout,authorizationCodeGrant:Yp,logger:console}){let{createServer:s,setTimeout:a,clearTimeout:c,logger:l}=i;return new Promise((p,d)=>{let u=s(async(g,h)=>{try{let v=await zp(g,h,t,n,o,i);v.shouldClose&&(y(),v.error?d(v.error):v.tokens?p(v.tokens):d(new Error("No tokens received")))}catch(v){y(),d(v instanceof Error?v:new Error(String(v)))}}),f=a(()=>{y(),d(new Error(`Login timeout - no response received within ${qp(e.loginTimeout)}`))},e.loginTimeout);function y(){c(f),u.close(),u.closeIdleConnections?.()}r(y,"cleanup"),u.on("error",g=>{y(),g.code==="EADDRINUSE"||g.code==="EACCES"?d(new m(`Port ${e.port} is already in use \u2014 the login callback server cannot start`,{cause:g,hint:Yt(e.port)})):d(new m(`Login callback server failed: ${g.message}`,{cause:g}))}),u.listen(e.port,"127.0.0.1",()=>{l.log(`\u{1F310} Local HTTP server started on http://localhost:${e.port}`)})})}r(Di,"startCallbackServer");import{spawn as Wp}from"child_process";import Zp from"open";import{parseArgsStringToArgv as Xp}from"string-argv";function Jp(e){try{return new URL(e),!0}catch{return!1}}r(Jp,"isValidUrl");function $i(e,t="url"){if(!Jp(e))throw new Error(`${t} must be a valid URL, got: ${e}`);return e}r($i,"parseUrl");var Qp=5e3;async function Oi(e,t={}){let{open:n=Zp,spawn:o=r((p,d)=>{let u=Wp(p,d,{stdio:"ignore",detached:!0});return u.unref(),u},"spawn"),platform:i=process.platform,env:s=process.env,setTimeout:a=globalThis.setTimeout,clearTimeout:c=globalThis.clearTimeout}=t,l=s.BROWSER?.trim();if(i==="win32"&&l){let[p,...d]=Xp(l);if(!p){await n(e);return}$i(e,"openBrowser target"),await ed(o,p,[...d,e],a,c);return}await n(e)}r(Oi,"openBrowser");function ed(e,t,n,o,i){return new Promise((s,a)=>{let c=e(t,n),l=o(()=>{a(new Error(`Timed out waiting for "${t}" to spawn`))},Qp);c.once("error",p=>{i(l),a(p)}),c.once("spawn",()=>{i(l),s()})})}r(ed,"spawnBrowser");var wo="openid profile email";function Co(e){return`http://localhost:${e}/`}r(Co,"callbackRedirectUri");var ad="https://auth.cognite.com",cd="https://auth-dev.cognitedata-development.cognite.ai";function Pe(e=process.env,t){let n=e.COGNITE_IDP_BASE_URL?.trim();return n?n.replace(/\/+$/,""):t?.startsWith("cog-dev-")?cd:ad}r(Pe,"resolveIdpBaseUrl");var ld=Pe(),Mi="0404baaa-0a90-43a2-aba7-a110b53fb41c",pd="e26f94fb-bac4-4915-aa91-456668004185";function mt(e){return e?.startsWith("cog-dev-")?pd:Mi}r(mt,"resolveClientId");var Ao={authority:ld,clientId:Mi,redirectUri:Co(3e3),port:3e3,loginTimeout:300*1e3},dd={open:Oi,startCallbackServer:Di,isPortFree:Ii,discovery:od,buildAuthorizationUrl:td,randomPKCECodeVerifier:id,calculatePKCECodeChallenge:nd,randomState:sd,logger:console,telemetry:Bt()};async function zt(e,t,n){let o=t??{...Ao,authority:Pe(process.env,e),clientId:mt(e)};return n===void 0?Li(e,o,dd):Li(e,o,n)}r(zt,"login");async function ud(e,t){let{discovery:n}=e;try{return await n(new URL(t.authority),t.clientId,void 0,rd())}catch(o){throw new m(`Failed to fetch OpenID configuration from ${t.authority}`,{cause:o})}}r(ud,"fetchOpenIdConfig");async function Li(e,t,n){let{isPortFree:o,telemetry:i,logger:s,randomPKCECodeVerifier:a,calculatePKCECodeChallenge:c,randomState:l,buildAuthorizationUrl:p,open:d,startCallbackServer:u}=n;if(!await o(t.port))throw i?.track("Flows.CLI.PortInUse",{port:t.port}),new m(`Port ${t.port} is already in use \u2014 the login callback server cannot start`,{hint:Yt(t.port)});s.log(`\u{1F510} Starting CDF login flow...
|
|
23
|
+
`),s.log(`\u{1F4E1} Fetching OpenID configuration from ${t.authority}...`);let y=await ud(n,t),g=a(),h=await c(g),v=l(),S={redirect_uri:t.redirectUri,scope:t.scope??wo,code_challenge:h,code_challenge_method:"S256",state:v};e&&(S.organization_hint=e);let C=p(y,S).toString();e&&s.log(`\u{1F3E2} Organization: ${e}`),s.log(`\u{1F680} Opening browser for authentication...
|
|
24
24
|
`);try{await d(C)}catch(A){let x=A instanceof Error?A.message:String(A);s.error("\u274C Failed to open browser automatically."),s.error(` Reason: ${x}`),s.error(`Please open this URL manually:
|
|
25
|
-
`),s.error(C),s.error("")}return u(t,y,g,
|
|
26
|
-
See: ${
|
|
27
|
-
See: ${
|
|
28
|
-
${n}`),{cause:t}):null}r(fe,"enrichedHttpError");function
|
|
29
|
-
`)}r(
|
|
25
|
+
`),s.error(C),s.error("")}return u(t,y,g,v)}r(Li,"loginImpl");var Eo={...Ao,scope:`${wo} offline_access`},yd=3600,Sd=1500*60;function _i(e){return gd(new URL(e.authority),e.clientId,void 0,md())}r(_i,"discoverDefault");function Ui(e){let t=typeof e=="string"?Number(e):e;return typeof t=="number"&&Number.isFinite(t)?t:void 0}r(Ui,"asSeconds");function Ni(e,t,n=new Date,o={}){let i=t.access_token?b.from(t.access_token):null;if(!i)throw new m("Login succeeded but no access token was returned.",{hint:"The identity provider did not return an access token. Please try logging in again."});let s=t.refresh_token?b.from(t.refresh_token):o.previousRefreshToken;if(!s)throw new m("Login succeeded but no refresh token was returned.",{hint:"The identity provider may not support the `offline_access` scope, which is required for persisted sessions."});let a=n.getTime(),c=(Ui(t.expires_in)??yd)*1e3,l=(Ui(t.refresh_expires_in)??Sd)*1e3;return{version:_t,org:e.org,accessToken:i,refreshToken:s,accessTokenExpiresAt:new Date(a+c).toISOString(),refreshTokenExpiresAt:new Date(a+l).toISOString()}}r(Ni,"buildSession");async function ji(e,t={}){if(e.port!==void 0&&!Vt(e.port))throw new m(Gt(e.port));let{login:n=r((c,l)=>zt(c,l),"login"),now:o=r(()=>new Date,"now")}=t,i={...Eo,authority:Pe(process.env,e.org),clientId:mt(e.org)},s=e.port===void 0?i:{...i,port:e.port,redirectUri:Co(e.port)},a=await n(e.org,s);return Ni(e,a,o())}r(ji,"loginForSession");async function Hi(e,t={},n){let{discovery:o=_i,tokenRevocation:i=r((c,l)=>fd(c,l.expose()),"tokenRevocation")}=t,s={...Eo,authority:Pe(process.env,n),clientId:mt(n)},a=await o(s);await i(a,e)}r(Hi,"revokeRefreshToken");async function Bi(e,t={}){let n=t.discovery??_i,o=t.refreshTokenGrant??((l,p)=>hd(l,p.expose())),i=t.now??(()=>new Date),s={...Eo,authority:Pe(process.env,e.org),clientId:mt(e.org)},a=await n(s),c=await o(a,e.refreshToken);return Ni({org:e.org},c,i(),{previousRefreshToken:e.refreshToken})}r(Bi,"refreshSession");function Ki(e){if(typeof e!="object"||e===null)return!1;if("error"in e&&typeof e.error=="string"&&e.error==="invalid_grant")return!0;if(e instanceof Error)return/invalid_grant/i.test(e.message);let t="message"in e&&typeof e.message=="string"?e.message:"";return/invalid_grant/i.test(t)}r(Ki,"isInvalidGrant");var bo=class bo extends Error{constructor(n,o,i){super(o,i);this.kind=n;this.name="SessionVerificationError"}};r(bo,"SessionVerificationError");var Je=bo;function vd(e){return e instanceof Error?"cause"in e&&e.cause instanceof Error?e.cause.message:e.message:String(e)}r(vd,"describeTransportError");function wd(e){return!(typeof e!="object"||e===null||"sub"in e&&typeof e.sub!="string"||"email"in e&&typeof e.email!="string"||"name"in e&&typeof e.name!="string"||"preferred_username"in e&&typeof e.preferred_username!="string")}r(wd,"isJwtClaims");function Cd(e){try{let t=e.expose().split(".");if(t.length!==3)return{};let n=JSON.parse(Buffer.from(t[1],"base64url").toString("utf-8"));return wd(n)?n:{}}catch{return{}}}r(Cd,"decodeJwtClaims");function Ad(e){return typeof e!="object"||e===null?!1:"items"in e?Array.isArray(e.items)?e.items.every(t=>typeof t=="object"&&t!==null&&"name"in t&&typeof t.name=="string"):!1:!0}r(Ad,"isCogIdpProjectsResponse");function Ed(e){if(e)try{return new URL(e).host}catch{return}}r(Ed,"clusterFromApiUrl");async function qt(e,t={}){let n=t.fetch??globalThis.fetch,i=`${Pe(process.env,e.org)}/api/v0/orgs/${encodeURIComponent(e.org)}/projects`,s;try{s=await n(i,{headers:{Authorization:`Bearer ${e.accessToken.expose()}`}})}catch(d){throw new Je("unreachable",vd(d),{cause:d})}if(!s.ok)throw new Je("rejected",`CogIdP rejected the token: ${s.status} ${s.statusText}`);let a=await s.json(),l=((Ad(a)?a:{}).items??[]).map(d=>({name:d.name,cluster:Ed(d.apiUrl),...d.isDefault?{isDefault:!0}:{}})),p=Cd(e.accessToken);return{sub:p.sub??"unknown",email:p.email,name:p.name,preferredUsername:p.preferred_username,projects:l}}r(qt,"fetchSessionUserInfo");var kd=3e4,xo=class xo extends m{constructor(t){super("Your session has expired.",{hint:"Run `cognite auth login` to sign in again.",shouldReport:!1,...t===void 0?{}:{cause:t}}),this.name="SessionExpiredError"}};r(xo,"SessionExpiredError");var He=xo;function Jt(e){return new He(e)}r(Jt,"expiredError");async function Pd(e,t,n){let o=await e(bd.dirname(t),{stale:kd,retries:{retries:10,factor:1.5,minTimeout:100,maxTimeout:1e3}});try{return await n()}finally{await o()}}r(Pd,"withSessionLock");async function We(e={}){let t=e.readSession??(()=>pt()),n=e.now??(()=>new Date),o=e.sessionFile??D().sessionFile,i=e.lock??xd,s=await t();if(!s)return;let a=je(s,n());if(a==="EXPIRED")throw Jt();return a==="VALID"?s:Pd(i,o,async()=>{let c=await t()??s,l=je(c,n());if(l==="EXPIRED")throw Jt();return l==="VALID"?c:Td(c,e)})}r(We,"ensureFreshSession");async function Td(e,t){let n=t.readSession??(()=>pt()),o=t.writeSession??(s=>jt(s)),i=t.refreshSession??(s=>Bi(s));try{let s=await i(e);return await o(s),s}catch(s){if(!Ki(s))throw s;let a=await n();if(a&&!a.refreshToken.equals(e.refreshToken))try{let c=await i(a);return await o(c),c}catch(c){throw Jt(c)}throw Jt(s)}}r(Td,"refreshAndPersist");import{CogniteClient as uu}from"@cognite/sdk";var Vi="https://docs.cognite.com/cdf/access/";function U(e){return e!==null&&typeof e=="object"}r(U,"isRecord");function ae(e){return e instanceof Error&&"status"in e&&typeof e.status=="number"}r(ae,"isHttpError");function ko(e){return U(e.data)?e.data:void 0}r(ko,"httpErrorResponseBody");function Gi(e){let t=ko(e);if(!t)return;let n=t.error;if(U(n)&&typeof n.message=="string")return n.message;if(typeof t.message=="string")return t.message}r(Gi,"cdfApiErrorMessage");function Rd(e){switch(e){case 401:return`Your credentials are invalid or expired. Check your client ID and secret.
|
|
26
|
+
See: ${Vi}`;case 403:return`You don't have the required CDF capabilities. Please contact your CDF admin.
|
|
27
|
+
See: ${Vi}`;default:return}}r(Rd,"httpStatusHint");function fe(e){let t=e instanceof Error?e:new Error(String(e));if(!ae(t))return null;let n=Rd(t.status);return n?Object.assign(new Error(`${t.message}
|
|
28
|
+
${n}`),{cause:t}):null}r(fe,"enrichedHttpError");function Id(e){if(!U(e))return null;let t=e.missing;if(Array.isArray(t))return t;let n=e.data;if(U(n)){let o=n.error;if(U(o)&&Array.isArray(o.missing))return o.missing;if(Array.isArray(n.missing))return n.missing}return null}r(Id,"findMissingArray");function Dd(e,t){if(!ae(e)||e.status!==400)return!1;let n=Id(e);return n?n.some(o=>U(o)&&typeof o.externalId=="string"&&t.includes(o.externalId)):!1}r(Dd,"isMissingExternalIdError");function Wt(e,t){return ae(e)&&e.status===404||Dd(e,t)}r(Wt,"isNotFoundError");var zi=["DRAFT","PUBLISHED","DEPRECATED","ARCHIVED"],qi=["ACTIVE","PREVIEW"],Po=class Po extends Error{constructor(t,n){super(`Version ${n} of app ${t} not found`),this.name="AppVersionNotFoundError",this.appExternalId=t,this.version=n}};r(Po,"AppVersionNotFoundError");var te=Po,To=class To extends Error{constructor(t){super(`App ${t} not found`),this.name="AppNotFoundError",this.appExternalId=t}};r(To,"AppNotFoundError");var Ze=To;function Zt(e,t){return e.includes(t)}r(Zt,"includesValue");function $d(e){return Zt(zi,e)}r($d,"isAppVersionLifecycleState");function Od(e){return Zt(qi,e)}r(Od,"isAppVersionAlias");function Fd(e){return typeof e.version=="string"&&$d(e.lifecycleState)&&typeof e.entrypoint=="string"&&typeof e.createdTime=="number"&&typeof e.createdBy=="string"&&typeof e.appExternalId=="string"&&(e.alias===void 0||Od(e.alias))&&(e.comment===void 0||typeof e.comment=="string")}r(Fd,"isAppVersion");function Yi(e){if(!U(e)){let t=JSON.stringify(e)?.slice(0,200)??String(e);throw new Error(`Invalid version response: expected object, got ${t}`)}if(!Fd(e)){let t=JSON.stringify(e).slice(0,300);throw new Error(`Invalid version response: missing or malformed fields. Got: ${t}`)}return e}r(Yi,"parseAppVersion");function Ld(e){if(!U(e))throw new Error("Invalid app response: not an object");let{externalId:t,name:n,description:o}=e;if(typeof t!="string")throw new Error("Invalid app response: missing externalId");if(typeof n!="string")throw new Error("Invalid app response: missing name");if(o!=null&&typeof o!="string")throw new Error("Invalid app response: malformed description");return{externalId:t,name:n,description:typeof o=="string"?o:void 0}}r(Ld,"parseAppMetadata");var Ro=class Ro{constructor(t){this.client=t}get appsBasePath(){return`/api/v1/projects/${encodeURIComponent(this.client.project)}/apphosting/apps`}async createApp(t,n,o){try{await this.client.post(this.appsBasePath,{data:{items:[{externalId:t,name:n,description:o}]}})}catch(i){throw fe(i)??i}}async updateApps(t){try{await this.client.post(`${this.appsBasePath}/update`,{data:{items:t}})}catch(n){throw fe(n)??n}}async getApp(t){let n=`${this.appsBasePath}/${encodeURIComponent(t)}`;try{let o=await this.client.get(n);return Ld(o.data)}catch(o){throw Wt(o,[t])?new Ze(t):fe(o)??o}}async uploadVersion(t,n,o,i,s="index.html"){console.log(`\u{1F4E4} Uploading version ${n}...`);let a=new FormData;a.append("file",new Blob([new Uint8Array(o)]),i),a.append("version",n),a.append("entryPath",s);let c=encodeURIComponent(t),l=`${this.appsBasePath}/${c}/versions`,p=await this.client.authenticate();if(!p)throw new m("Failed to authenticate for upload",{hint:"Check your credentials and try again."});let d=b.from(p),u=`${this.client.getBaseUrl()}${l}`,f=new AbortController,y=setTimeout(()=>f.abort(),300*1e3),g;try{g=await fetch(u,{method:"POST",headers:{Authorization:`Bearer ${d.expose()}`},body:a,signal:f.signal})}catch(h){throw h instanceof Error&&h.name==="AbortError"?new m("Upload timed out after 5 minutes",{hint:"The upload took longer than 5 minutes. Try again \u2014 if it keeps timing out, check your network speed or bundle size."}):new m(`Failed to upload version to ${u}`,{cause:h,hint:"Check your network connection. Uploads can also fail behind a proxy that blocks multipart POST requests."})}finally{clearTimeout(y)}if(!g.ok){let h=await g.text(),v;try{v=JSON.parse(h)}catch{}let S=h;if(U(v)){let M=v.error;if(typeof M=="string")S=M;else if(U(M)){let K=M.message,R=M.code;S=typeof K=="string"?K:R!=null?`Unknown error (code: ${R})`:h}else{let K=v.message;S=typeof K=="string"?K:h}}let C=g.headers.get("x-request-id"),A=C?` | X-Request-ID: ${C}`:"",x=U(v)?v:h;throw new ie(`Upload failed: ${g.status} \u2014 ${S}${A}`,{httpStatusCode:g.status,requestUrl:u,responseBody:x})}console.log(`\u2705 Version ${n} uploaded`)}async getVersion(t,n){let o=encodeURIComponent(t),i=encodeURIComponent(n),s=`${this.appsBasePath}/${o}/versions/${i}`;try{let a=await this.client.get(s);return Yi(a.data)}catch(a){throw Wt(a,[t,n])?new te(t,n):fe(a)??a}}async getActiveVersion(t){let n=encodeURIComponent(t),o=`${this.appsBasePath}/${n}/versions/list`;try{let i=await this.client.post(o,{data:{filter:{aliases:["ACTIVE"]}}});if(!U(i.data)||!Array.isArray(i.data.items))throw new Error("Invalid versions/list response: expected an object with an items array");let{items:s}=i.data;if(s.length===0)return null;if(s.length>1)throw new Error(`Unexpected response: ${s.length} versions have the ACTIVE alias, expected at most 1`);return Yi(s[0])}catch(i){if(Wt(i,[t]))return null;throw fe(i)??i}}async deleteVersions(t,n){let o=encodeURIComponent(t),i=`${this.appsBasePath}/${o}/versions/delete`;try{await this.client.post(i,{data:{items:n.map(s=>({version:s}))}})}catch(s){throw fe(s)??s}}async updateVersions(t,n){let o=encodeURIComponent(t),i=`${this.appsBasePath}/${o}/versions/update`;try{await this.client.post(i,{data:{items:n}})}catch(s){throw fe(s)??s}}async submitSignatures(t,n,o){let i=encodeURIComponent(t),s=encodeURIComponent(n),a=`${this.appsBasePath}/${i}/versions/${s}/signatures`;try{await this.client.post(a,{data:{items:o}})}catch(c){throw fe(c)??c}}async listSignatures(t,n){let o=encodeURIComponent(t),i=encodeURIComponent(n),s=`${this.appsBasePath}/${o}/versions/${i}/signatures/list`;try{let a=await this.client.post(s,{data:{}});return _d(a.data)}catch(a){throw fe(a)??a}}};r(Ro,"AppHostingApi");var Xt=Ro,Md=["VALID","REVOKED","EXPIRED","SIGNED_BEFORE_KEY_ISSUED","IAT_IN_FUTURE","BUNDLE_TOO_OLD","KEY_NOT_IN_REGISTRY","SCOPE_MISMATCH","VERIFICATION_FAILED"],Ud=["developer","certifier"];function _d(e){if(!U(e))throw new Error("Invalid signatures response: expected an object with an items array");let{items:t}=e;if(!Array.isArray(t))throw new Error("Invalid signatures response: items property is missing or not an array");return t.flatMap(n=>{let o=Nd(n);return o?[o]:[]})}r(_d,"parseStoredSignatures");function Nd(e){if(!U(e))return null;let{signerKid:t,signerRole:n,signatureIat:o,receivedAt:i,createdTime:s,status:a}=e;return typeof t!="string"||t===""||!Zt(Ud,n)||typeof o!="number"||typeof i!="number"||typeof s!="number"||!Zt(Md,a)?null:{signerKid:t,signerRole:n,signatureIat:o,receivedAt:i,createdTime:s,status:a}}r(Nd,"parseStoredSignature");function Io(e,t){let n=[];e.name!==t.name&&n.push({field:"name",remote:e.name,local:t.name});let o=e.description??"";return o!==t.description&&n.push({field:"description",remote:o,local:t.description}),n}r(Io,"diffAppMetadata");function jd(e){let t=["Cannot deploy: metadata in app.json differs from what's deployed:"];for(let{field:n,remote:o,local:i}of e){let s=`${n}:`.padEnd(14);t.push(` ${s}"${o}" \u2192 "${i}"`)}return t.join(`
|
|
29
|
+
`)}r(jd,"formatMetadataDriftError");var Do=class Do{constructor(t){this.api=new Xt(t)}getVersion(t,n){return this.api.getVersion(t,n)}uploadVersion(t,n,o,i,s){return this.api.uploadVersion(t,n,o,i,s)}async ensureApp(t,n,o){console.log("\u{1F50D} Ensuring app exists...");try{await this.api.createApp(t,n,o),console.log(`\u2705 App '${t}' created`)}catch(i){if(ae(i)&&i.status===409){console.log(`\u2705 App '${t}' already exists`),await this.checkMetadataDrift(t,n,o);return}throw i}}async checkMetadataDrift(t,n,o){let i;try{i=await this.getApp(t)}catch{return}let s=Io(i,{name:n,description:o});if(s.length!==0)throw new m(jd(s),{hint:"Run npx @cognite/cli apps metadata update to sync before deploying",shouldReport:!1})}getApp(t){return this.api.getApp(t)}async updateAppMetadata(t,n,o){await this.api.updateApps([{externalId:t,update:{name:{set:n},description:o?{set:o}:{setNull:!0}}}])}async submitSignatures(t,n,o){o.length!==0&&(console.log(`\u{1F50F} Submitting ${o.length} signature${o.length===1?"":"s"} for version ${n}...`),await this.api.submitSignatures(t,n,o),console.log("\u2705 Signatures stored"))}listSignatures(t,n){return this.api.listSignatures(t,n)}async publishVersion(t,n){await this.api.updateVersions(t,[{version:n,update:{lifecycleState:{set:"PUBLISHED"}}}])}async publishAndActivate(t,n){console.log(`\u{1F680} Publishing and activating version ${n}...`),await this.api.updateVersions(t,[{version:n,update:{lifecycleState:{set:"PUBLISHED"},alias:{set:"ACTIVE"}}}]),console.log(`\u2705 Version ${n} is now PUBLISHED and ACTIVE`)}getActiveVersion(t){return this.api.getActiveVersion(t)}async deactivateVersion(t,n){await this.api.updateVersions(t,[{version:n,update:{alias:{setNull:!0}}}])}async deleteVersion(t,n){await this.api.deleteVersions(t,[n])}async deprecateVersion(t,n){await this.api.updateVersions(t,[{version:n,update:{lifecycleState:{set:"DEPRECATED"}}}])}async archiveVersion(t,n){await this.api.updateVersions(t,[{version:n,update:{lifecycleState:{set:"ARCHIVED"}}}])}async activateVersion(t,n){let o=null;try{o=await this.api.getActiveVersion(t)}catch{o=null}let i=o&&o.version!==n?o.version:void 0;return await this.api.updateVersions(t,[{version:n,update:{alias:{set:"ACTIVE"}}}]),{supersededVersion:i}}async deploy(t,n,o,i,s,a,c=!1){console.log(`
|
|
30
30
|
\u{1F680} Deploying application via App Hosting API...
|
|
31
31
|
`),await this.ensureApp(t,n,o),await this.uploadVersion(t,i,s,a),c&&await this.publishAndActivate(t,i),console.log(`
|
|
32
|
-
\u2705 Deployment successful!`)}};r(
|
|
33
|
-
Using session credentials \u2014 your token has access to all projects in the "${e.org}" organization.`),!i)throw new m("Session credentials detected but no TTY available for confirmation.",{shouldReport:!1,hint:"Pass --confirm-action-target <org/project> to skip the prompt, or configure deployClientId and deploySecretName in app.json."});let{confirmed:c}=await s(`Confirm ${n} to ${a}?`);if(!c)throw new m("Aborted.",{shouldReport:!1})},"confirmActionTarget");import Ud from"enquirer";var Nd=r(e=>Ud.prompt(e),"defaultPrompt");function _d(e){switch(e.method){case"client-credentials":return"Use client credentials from app.json";case"session":return`Reuse existing session for ${e.org}`;case"browser":return"One-off sign-in via browser (does not save a session; use `cognite auth login` for that)"}}r(_d,"choiceLabel");async function Qt(e,t=Nd){if(e.length===0)throw new m("No valid authentication method available.",{hint:"Run `cognite auth login` and authenticate to the correct organization, or set deployClientId/deploySecretName in app.json."});let n=e.map(a=>a.method);if(new Set(n).size!==n.length)throw new Error(`Cannot present a selection with duplicate method names (${n.join(", ")}).`);let o=Array.from(new Set(n)).join("|"),{choice:i}=await t({type:"select",name:"choice",message:`Multiple valid authentication methods detected (skip with --auth-method <${o}>). Authenticate with`,choices:e.map(a=>({name:a.method,message:_d(a)}))}),s=e.find(a=>a.method===i);if(!s)throw new m(`Selected authentication method "${i}" was not offered.`,{hint:"Pass --auth-method to choose one of the offered methods explicitly."});return s}r(Qt,"promptAuthMethod");async function zi(e,t,n,o={confirmActionTarget:Xt,promptAuthMethod:Qt,isTTY:process.stdin.isTTY??!1}){let{valid:i}=e;if(i.length===0)throw jd(e,t);let s;if(n.authMethod){let a=i.find(c=>c.method===n.authMethod);if(!a)throw new m(`Pass --auth-method ${i.map(c=>c.method).join(" or --auth-method ")} \u2014 "${n.authMethod}" is not currently valid for ${t.project} @ ${t.baseUrl}.`,{hint:"Run `cognite auth login` for a session, or set deployClientId/deploySecretName in app.json for client credentials."});s=a}else if(i.length===1)[s]=i;else if(o.isTTY)s=await o.promptAuthMethod(i);else throw new m(`Pass --auth-method ${i.map(a=>a.method).join("|")} to choose non-interactively \u2014 several are valid for ${t.project} @ ${t.baseUrl} and there is no TTY to prompt.`,{shouldReport:!1,hint:"Or re-run in an interactive terminal to pick from the prompt."});if(s.method==="session"&&n.action&&!n.interactive)await o.confirmActionTarget(t,{confirmActionTarget:n.confirmActionTarget},n.action);else if(n.confirmActionTarget!==void 0&&s.method!=="session")throw new m(`Remove --confirm-action-target \u2014 it only guards session credentials and is never validated against the selected deployment with ${s.method} authentication.`,{shouldReport:!1,hint:"Pass --auth-method session (or pick the session option at the prompt) if you meant to acknowledge a session target."});return s}r(zi,"chooseAuthMethod");function jd(e,t){let{invalidSession:n}=e;if(!n)return new m(`No credentials available for ${t.project} @ ${t.baseUrl}.`,{hint:"Run `cognite auth login`, or set deployClientId/deploySecretName in app.json."});let o=`Run \`cognite auth login\` for "${t.org}".`;return n.reason==="SESSION_EXPIRED"?new m(`Your session for organization "${n.org}" has expired.`,{hint:o}):new m(`Your active session is for organization "${n.org}", but this command targets "${t.org}".`,{hint:o})}r(jd,"createNoCredentialsError");function qi(e,t,n){return e?t.org&&e.org!==t.org?{reason:"DIFFERENT_ORG",org:void 0}:_e(e,n)==="EXPIRED"?{reason:"SESSION_EXPIRED",org:void 0}:{org:e.org,reason:"VALID"}:{reason:"SESSION_MISSING",org:void 0}}r(qi,"getSessionOrgIfValid");function Ji(e,t,n){let o=[];e.deployClientId&&o.push({method:"client-credentials",org:e.org});let i=n.readSessionMetadata(),s=qi(i,e,n.now());return s.reason==="VALID"&&o.push({method:"session",org:s.org}),t.interactive&&o.push({method:"browser"}),i&&(s.reason==="SESSION_EXPIRED"||s.reason==="DIFFERENT_ORG")?{valid:o,invalidSession:{reason:s.reason,org:i.org}}:{valid:o}}r(Ji,"validAuthMethods");import{CogniteClient as Wd}from"@cognite/sdk";function Hd(e){return Math.floor(Math.random()*Math.min(2**e*250,15e3))}r(Hd,"exponentialBackoffWithJitter");function Bd(e){return new Promise(t=>setTimeout(t,e))}r(Bd,"sleep");async function Wi(e,t={}){let n=t.maxAttempts??5,o=t.shouldRetry??(()=>!0),i=t.delayInMsCalculator??Hd;if(n<1)throw new Error("`maxAttempts` must be 1 or greater");if(n>100)throw new Error("`maxAttempts` must be 100 or less");let s=1;for(;;)try{return await e()}catch(a){if(s>=n||!o(a))throw a;let c=i(s);t.onAttemptFail?.(a,s,c),await Bd(c),s++}}r(Wi,"retryAsync");var Kd="https://auth.cognite.com/oauth2/token",Vd=r(e=>typeof e=="object"&&e!==null&&"access_token"in e&&typeof e.access_token=="string","hasAccessToken");async function Zi({idp:e,tokenUrl:t,init:n,missingTokenHint:o}){let i;try{i=await Wi(()=>fetch(t,n),{maxAttempts:3})}catch(c){throw new m(`Failed to fetch access token from ${t}`,{cause:c})}if(!i.ok){let c=await i.text();throw new ie(`Failed to get token from ${e}: ${i.status} ${i.statusText}`,{httpStatusCode:i.status,requestUrl:t,responseBody:c})}let s=await i.text(),a;try{a=JSON.parse(s)}catch{throw new m(`Unexpected response from ${e} authentication (invalid JSON)`,{hint:o})}if(!Vd(a))throw new m(`No access token in ${e} authentication response`,{hint:o});return b.from(a.access_token)}r(Zi,"fetchOAuthToken");var Gd=r(e=>{let t=e.DEPLOYMENT_SECRETS;if(!t)return{};try{let n=JSON.parse(t),o={};for(let[i,s]of Object.entries(n))if(typeof s=="string"){let a=i.toLowerCase().replace(/_/g,"-");o[a]=s}return o}catch(n){return console.error("Error parsing DEPLOYMENT_SECRETS:",n),{}}},"loadSecretsFromEnv"),Yd=r((e,t)=>{let n;if(t.DEPLOYMENT_SECRET&&(n=t.DEPLOYMENT_SECRET),n||(n=Gd(t)[e]),n||(n=t[e]),!n)throw new m(`Set the ${e} environment variable (named by deploySecretName in app.json) to your deploy client secret, e.g. in a .env file.`,{shouldReport:!1,hint:"Alternatively, run `cognite auth login` to use your session, or pass --interactive for a one-off browser login."});return b.from(n)},"getSecretFromEnv"),zd=r((e,t)=>{let n=t.expose();return Zi({idp:"CDF",tokenUrl:Kd,init:{method:"POST",headers:{Authorization:`Basic ${btoa(`${e}:${n}`)}`,"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"client_credentials"})},missingTokenHint:"Check the client ID in app.json and the deployment secret in your environment."})},"getTokenCdf"),Xi=r(({idp:e,tokenUrl:t,clientId:n,clientSecret:o,scopes:i,missingTokenHint:s})=>Zi({idp:e,tokenUrl:t,init:{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:n,client_secret:o,grant_type:"client_credentials",...i!==void 0?{scope:i.join(" ")}:{}})},missingTokenHint:s}),"getTokenWithClientCredentials"),qd=r((e,t)=>{if(t!==void 0)return t.join(" ");if(!e)throw new Error("Entra ID authentication requires 'baseUrl' to be set in deployment configuration");try{return`${new URL(e).origin}/.default`}catch{throw new Error(`Entra ID authentication requires 'baseUrl' to be a valid CDF URL (e.g., https://cluster.cognitedata.com), got: ${e}`)}},"resolveEntraScope"),Jd=r((e,t,n,o,i)=>Xi({idp:"Entra ID",tokenUrl:`https://login.microsoftonline.com/${n}/oauth2/v2.0/token`,clientId:e,clientSecret:t.expose(),scopes:i!==void 0?i:[qd(o)],missingTokenHint:"Check the client ID and tenant ID in app.json and the deployment secret in your environment."}),"getTokenEntra"),Do=r(async(e,t=process.env)=>{if(t.COGNITE_TOKEN)return b.from(t.COGNITE_TOKEN);let{deployClientId:n,deploySecretName:o,idpType:i="cdf",tenantId:s,baseUrl:a,scopes:c,tokenUrl:l}=e,p=Yd(o,t);if(i==="oauth"){if(!l)throw new Error("OAuth authentication requires 'tokenUrl' in deployment configuration");return Xi({idp:"OAuth",tokenUrl:l,clientId:n,clientSecret:p.expose(),scopes:c,missingTokenHint:"Check the tokenUrl, client ID, scopes, and deployment secret in app.json and your environment."})}if(i==="entra_id"){if(!s)throw new Error("Entra ID authentication requires 'tenantId' in deployment configuration");return Jd(n,p,s,a,c)}return zd(n,p)},"getToken");async function en(e,t,n=process.env,o){let i=await Do(e,n),s=n.COGNITE_BASE_URL??e.baseUrl,a=(o??(c=>new Wd(c)))({appId:t,project:e.project,baseUrl:s,oidcTokenProvider:r(async()=>i.expose(),"oidcTokenProvider")});return await a.authenticate(),a}r(en,"getSdk");async function tn(e,t,n,o){let i=o({appId:t,project:e.project,baseUrl:e.baseUrl,oidcTokenProvider:r(async()=>n.expose(),"oidcTokenProvider")});return await i.authenticate(),i}r(tn,"buildAuthenticatedClient");async function Qi(e,t,n){let{loginFn:o,createClient:i}=n,s=t.orgHint||e.org||void 0,a=await o(s);return tn(e,t.appId,b.from(a.access_token),i)}r(Qi,"resolveViaBrowser");import{HttpError as Zd}from"@cognite/sdk";import{array as es,number as Xd,object as ts,optional as Qd,safeParse as eu,string as tu}from"valibot";var nu=ts({projects:Qd(es(ts({projectUrlName:tu(),groups:es(Xd())})))});function ou(e,t){switch(e){case 401:return"Run `cognite auth login` to log in.";case 403:return"The token is valid but lacks access to this project. Ask your CDF admin to grant its service account access.";default:return e>=500?`${t} returned a server error \u2014 this is usually transient, so try again shortly.`:"Check that the deployment base URL and project in app.json are correct."}}r(ou,"hintForStatus");var ns=r(async function(e){let t=e.getBaseUrl(),n;try{({data:n}=await e.get("/api/v1/token/inspect"))}catch(i){throw i instanceof Zd?new m(`Could not verify project access against ${t} (${i.status}).`,{hint:ou(i.status,t),cause:i}):new m(`Could not connect to ${t} to verify project access.`,{hint:"Check your network connection and verify that the base URL is correct.",cause:i})}let o=eu(nu,n);if(!o.success)throw new m(`Unexpected response from ${t}/api/v1/token/inspect.`,{hint:"Retry; if it persists, your CLI may be out of date or a proxy is altering responses.",cause:new Error(JSON.stringify(o.issues))});return o.output},"inspectDeploymentToken");async function os(e,t,n,o){if(!((await(o?.inspectToken||ns)(e)).projects??[]).some(c=>c.projectUrlName===t.project&&c.groups.length>0))throw new m(`Your session for organization "${n}" doesn't have access to project "${t.project}" on ${t.baseUrl}.`,{hint:`Check you signed in to the right organization, or have access to the project "${t.project}" within "${n}" organization; \`@cognite/cli auth status\` lists the projects you can reach within your already logged in session token.`})}r(os,"assertProjectAccess");async function rs(e,t,n,o){let i=await o.ensureFreshSession();if(!i)throw new m(`No credentials available for ${e.project} @ ${e.baseUrl}.`,{hint:"Run `cognite auth login` to login."});let s=await tn(e,t,i.accessToken,o.createClient);return await os(s,e,n),s}r(rs,"resolveViaSession");async function is(e,t,n,o){switch(e.method){case"client-credentials":return o.getSdkFn(t,n.appId);case"session":return rs(t,n.appId,e.org,o);case"browser":return Qi(t,n,o)}}r(is,"buildClientForAuthMethod");async function j(e,t,n={}){let{login:o=Gt,getSdk:i=en,createClient:s=r(g=>new ru(g),"createClient"),readSessionMetadata:a=ke,ensureFreshSession:c=Je,promptAuthMethod:l=Qt,confirmActionTarget:p=Xt,isTTY:d=process.stdin?.isTTY??!1,now:u=r(()=>new Date,"now")}=n,f=Ji(e,t,{readSessionMetadata:a,now:u}),y=await zi(f,e,t,{promptAuthMethod:l,confirmActionTarget:p,isTTY:d});return is(y,e,t,{loginFn:o,getSdkFn:i,createClient:s,ensureFreshSession:c})}r(j,"buildAppHostingApiClient");async function nn(e,t,n={}){let o=await j(e,t,n);return new N(o)}r(nn,"buildAppHostingClient");import ss from"enquirer";var as="Enter custom target...";function cs(e,t){let n=t.map((o,i)=>` ${i}: ${o.org}/${o.project}`).join(`
|
|
32
|
+
\u2705 Deployment successful!`)}};r(Do,"AppHostingClient");var _=Do;import Hd from"enquirer";function Bd(e){return`${e.org}/${e.project}`}r(Bd,"targetLabel");var Qt=r(async function(e,t,n,o={isTTY:process.stdin.isTTY??!1,confirm:r(i=>Hd.prompt({type:"confirm",name:"confirmed",message:i,initial:!1}),"confirm")}){let{isTTY:i,confirm:s}=o,a=Bd(e);if(t.confirmActionTarget!==void 0){if(t.confirmActionTarget===a)return;throw new m(`--confirm-action-target "${t.confirmActionTarget}" does not match the deployment this command resolved to ("${a}").`,{shouldReport:!1,hint:`Pass --confirm-action-target ${a} to ${n}.`})}if(console.warn(`
|
|
33
|
+
Using session credentials \u2014 your token has access to all projects in the "${e.org}" organization.`),!i)throw new m("Session credentials detected but no TTY available for confirmation.",{shouldReport:!1,hint:"Pass --confirm-action-target <org/project> to skip the prompt, or configure deployClientId and deploySecretName in app.json."});let{confirmed:c}=await s(`Confirm ${n} to ${a}?`);if(!c)throw new m("Aborted.",{shouldReport:!1})},"confirmActionTarget");import Kd from"enquirer";var Vd=r(e=>Kd.prompt(e),"defaultPrompt");function Gd(e){switch(e.method){case"client-credentials":return"Use client credentials from app.json";case"session":return`Reuse existing session for ${e.org}`;case"browser":return"One-off sign-in via browser (does not save a session; use `cognite auth login` for that)"}}r(Gd,"choiceLabel");async function en(e,t=Vd){if(e.length===0)throw new m("No valid authentication method available.",{hint:"Run `cognite auth login` and authenticate to the correct organization, or set deployClientId/deploySecretName in app.json."});let n=e.map(a=>a.method);if(new Set(n).size!==n.length)throw new Error(`Cannot present a selection with duplicate method names (${n.join(", ")}).`);let o=Array.from(new Set(n)).join("|"),{choice:i}=await t({type:"select",name:"choice",message:`Multiple valid authentication methods detected (skip with --auth-method <${o}>). Authenticate with`,choices:e.map(a=>({name:a.method,message:Gd(a)}))}),s=e.find(a=>a.method===i);if(!s)throw new m(`Selected authentication method "${i}" was not offered.`,{hint:"Pass --auth-method to choose one of the offered methods explicitly."});return s}r(en,"promptAuthMethod");async function Ji(e,t,n,o={confirmActionTarget:Qt,promptAuthMethod:en,isTTY:process.stdin.isTTY??!1}){let{valid:i}=e;if(i.length===0)throw Yd(e,t);let s;if(n.authMethod){let a=i.find(c=>c.method===n.authMethod);if(!a)throw new m(`Pass --auth-method ${i.map(c=>c.method).join(" or --auth-method ")} \u2014 "${n.authMethod}" is not currently valid for ${t.project} @ ${t.baseUrl}.`,{hint:"Run `npx @cognite/cli@latest auth login` for a session, or set deployClientId/deploySecretName in app.json for client credentials."});s=a}else if(i.length===1)[s]=i;else if(o.isTTY)s=await o.promptAuthMethod(i);else throw new m(`Pass --auth-method ${i.map(a=>a.method).join("|")} to choose non-interactively \u2014 several are valid for ${t.project} @ ${t.baseUrl} and there is no TTY to prompt.`,{shouldReport:!1,hint:"Or re-run in an interactive terminal to pick from the prompt."});if(s.method==="session"&&n.action&&!n.interactive)await o.confirmActionTarget(t,{confirmActionTarget:n.confirmActionTarget},n.action);else if(n.confirmActionTarget!==void 0&&s.method!=="session")throw new m(`Remove --confirm-action-target \u2014 it only guards session credentials and is never validated against the selected deployment with ${s.method} authentication.`,{shouldReport:!1,hint:"Pass --auth-method session (or pick the session option at the prompt) if you meant to acknowledge a session target."});return s}r(Ji,"chooseAuthMethod");function Yd(e,t){let{invalidSession:n}=e;if(!n)return new m(`No credentials available for ${t.project} @ ${t.baseUrl}.`,{hint:"Run `npx @cognite/cli@latest auth login`, or set deployClientId/deploySecretName in app.json."});let o=`Run \`npx @cognite/cli@latest auth login\` for "${t.org}".`;return n.reason==="SESSION_EXPIRED"?new m(`Your session for organization "${n.org}" has expired.`,{hint:o}):new m(`Your active session is for organization "${n.org}", but this command targets "${t.org}".`,{hint:o})}r(Yd,"createNoCredentialsError");function Wi(e,t,n){return e?t.org&&e.org!==t.org?{reason:"DIFFERENT_ORG",org:void 0}:je(e,n)==="EXPIRED"?{reason:"SESSION_EXPIRED",org:void 0}:{org:e.org,reason:"VALID"}:{reason:"SESSION_MISSING",org:void 0}}r(Wi,"getSessionOrgIfValid");function Zi(e,t,n){let o=[];e.deployClientId&&o.push({method:"client-credentials",org:e.org});let i=n.readSessionMetadata(),s=Wi(i,e,n.now());return s.reason==="VALID"&&o.push({method:"session",org:s.org}),t.interactive&&o.push({method:"browser"}),i&&(s.reason==="SESSION_EXPIRED"||s.reason==="DIFFERENT_ORG")?{valid:o,invalidSession:{reason:s.reason,org:i.org}}:{valid:o}}r(Zi,"validAuthMethods");import{CogniteClient as ru}from"@cognite/sdk";function zd(e){return Math.floor(Math.random()*Math.min(2**e*250,15e3))}r(zd,"exponentialBackoffWithJitter");function qd(e){return new Promise(t=>setTimeout(t,e))}r(qd,"sleep");async function Xi(e,t={}){let n=t.maxAttempts??5,o=t.shouldRetry??(()=>!0),i=t.delayInMsCalculator??zd;if(n<1)throw new Error("`maxAttempts` must be 1 or greater");if(n>100)throw new Error("`maxAttempts` must be 100 or less");let s=1;for(;;)try{return await e()}catch(a){if(s>=n||!o(a))throw a;let c=i(s);t.onAttemptFail?.(a,s,c),await qd(c),s++}}r(Xi,"retryAsync");var Qi="https://auth.cognite.com/oauth2/token",Jd="https://auth-dev.cognitedata-development.cognite.ai/oauth2/token",Wd=/^(?:https?:\/\/)?(?:[^./]+\.plink\.)?([a-zA-Z0-9-]+)\.cognitedata\.com/;function Zd(e){return e&&e.match(Wd)?.[1]?.includes("-dev")?Jd:Qi}r(Zd,"resolveCogIdpTokenUrl");var Xd=r(e=>typeof e=="object"&&e!==null&&"access_token"in e&&typeof e.access_token=="string","hasAccessToken");async function es({idp:e,tokenUrl:t,init:n,missingTokenHint:o}){let i;try{i=await Xi(()=>fetch(t,n),{maxAttempts:3})}catch(c){throw new m(`Failed to fetch access token from ${t}`,{cause:c})}if(!i.ok){let c=await i.text();throw new ie(`Failed to get token from ${e}: ${i.status} ${i.statusText}`,{httpStatusCode:i.status,requestUrl:t,responseBody:c})}let s=await i.text(),a;try{a=JSON.parse(s)}catch{throw new m(`Unexpected response from ${e} authentication (invalid JSON)`,{hint:o})}if(!Xd(a))throw new m(`No access token in ${e} authentication response`,{hint:o});return b.from(a.access_token)}r(es,"fetchOAuthToken");var Qd=r(e=>{let t=e.DEPLOYMENT_SECRETS;if(!t)return{};try{let n=JSON.parse(t),o={};for(let[i,s]of Object.entries(n))if(typeof s=="string"){let a=i.toLowerCase().replace(/_/g,"-");o[a]=s}return o}catch(n){return console.error("Error parsing DEPLOYMENT_SECRETS:",n),{}}},"loadSecretsFromEnv"),eu=r((e,t)=>{let n;if(t.DEPLOYMENT_SECRET&&(n=t.DEPLOYMENT_SECRET),n||(n=Qd(t)[e]),n||(n=t[e]),!n)throw new m(`Set the ${e} environment variable (named by deploySecretName in app.json) to your deploy client secret, e.g. in a .env file.`,{shouldReport:!1,hint:"Alternatively, run `cognite auth login` to use your session, or pass --interactive for a one-off browser login."});return b.from(n)},"getSecretFromEnv"),tu=r((e,t,n)=>{let o=t.expose();return es({idp:"CDF",tokenUrl:n,init:{method:"POST",headers:{Authorization:`Basic ${btoa(`${e}:${o}`)}`,"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"client_credentials"})},missingTokenHint:"Check the client ID in app.json and the deployment secret in your environment."})},"getTokenCdf"),ts=r(({idp:e,tokenUrl:t,clientId:n,clientSecret:o,scopes:i,missingTokenHint:s})=>es({idp:e,tokenUrl:t,init:{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:n,client_secret:o,grant_type:"client_credentials",...i!==void 0?{scope:i.join(" ")}:{}})},missingTokenHint:s}),"getTokenWithClientCredentials"),nu=r((e,t)=>{if(t!==void 0)return t.join(" ");if(!e)throw new Error("Entra ID authentication requires 'baseUrl' to be set in deployment configuration");try{return`${new URL(e).origin}/.default`}catch{throw new Error(`Entra ID authentication requires 'baseUrl' to be a valid CDF URL (e.g., https://cluster.cognitedata.com), got: ${e}`)}},"resolveEntraScope"),ou=r((e,t,n,o,i)=>ts({idp:"Entra ID",tokenUrl:`https://login.microsoftonline.com/${n}/oauth2/v2.0/token`,clientId:e,clientSecret:t.expose(),scopes:i!==void 0?i:[nu(o)],missingTokenHint:"Check the client ID and tenant ID in app.json and the deployment secret in your environment."}),"getTokenEntra"),$o=r(async(e,t=process.env)=>{if(t.COGNITE_TOKEN)return b.from(t.COGNITE_TOKEN);let{deployClientId:n,deploySecretName:o,idpType:i="cdf",tenantId:s,baseUrl:a,scopes:c,tokenUrl:l}=e,p=eu(o,t);if(i==="oauth"){if(!l)throw new Error("OAuth authentication requires 'tokenUrl' in deployment configuration");return ts({idp:"OAuth",tokenUrl:l,clientId:n,clientSecret:p.expose(),scopes:c,missingTokenHint:"Check the tokenUrl, client ID, scopes, and deployment secret in app.json and your environment."})}if(i==="entra_id"){if(!s)throw new Error("Entra ID authentication requires 'tenantId' in deployment configuration");return ou(n,p,s,a,c)}let d=t.COGNITE_BASE_URL??a;return tu(n,p,Zd(d))},"getToken");async function tn(e,t,n=process.env,o){let i=await $o(e,n),s=n.COGNITE_BASE_URL??e.baseUrl,a=(o??(c=>new ru(c)))({appId:t,project:e.project,baseUrl:s,oidcTokenProvider:r(async()=>i.expose(),"oidcTokenProvider")});return await a.authenticate(),a}r(tn,"getSdk");async function nn(e,t,n,o){let i=o({appId:t,project:e.project,baseUrl:e.baseUrl,oidcTokenProvider:r(async()=>n.expose(),"oidcTokenProvider")});return await i.authenticate(),i}r(nn,"buildAuthenticatedClient");async function ns(e,t,n){let{loginFn:o,createClient:i}=n,s=t.orgHint||e.org||void 0,a=await o(s);return nn(e,t.appId,b.from(a.access_token),i)}r(ns,"resolveViaBrowser");import{HttpError as iu}from"@cognite/sdk";import{array as os,number as su,object as rs,optional as au,safeParse as cu,string as lu}from"valibot";var pu=rs({projects:au(os(rs({projectUrlName:lu(),groups:os(su())})))});function du(e,t){switch(e){case 401:return"Run `cognite auth login` to log in.";case 403:return"The token is valid but lacks access to this project. Ask your CDF admin to grant its service account access.";default:return e>=500?`${t} returned a server error \u2014 this is usually transient, so try again shortly.`:"Check that the deployment base URL and project in app.json are correct."}}r(du,"hintForStatus");var is=r(async function(e){let t=e.getBaseUrl(),n;try{({data:n}=await e.get("/api/v1/token/inspect"))}catch(i){throw i instanceof iu?new m(`Could not verify project access against ${t} (${i.status}).`,{hint:du(i.status,t),cause:i}):new m(`Could not connect to ${t} to verify project access.`,{hint:"Check your network connection and verify that the base URL is correct.",cause:i})}let o=cu(pu,n);if(!o.success)throw new m(`Unexpected response from ${t}/api/v1/token/inspect.`,{hint:"Retry; if it persists, your CLI may be out of date or a proxy is altering responses.",cause:new Error(JSON.stringify(o.issues))});return o.output},"inspectDeploymentToken");async function ss(e,t,n,o){if(!((await(o?.inspectToken||is)(e)).projects??[]).some(c=>c.projectUrlName===t.project&&c.groups.length>0))throw new m(`Your session for organization "${n}" doesn't have access to project "${t.project}" on ${t.baseUrl}.`,{hint:`Check you signed in to the right organization, or have access to the project "${t.project}" within "${n}" organization; \`@cognite/cli auth status\` lists the projects you can reach within your already logged in session token.`})}r(ss,"assertProjectAccess");async function as(e,t,n,o){let i=await o.ensureFreshSession();if(!i)throw new m(`No credentials available for ${e.project} @ ${e.baseUrl}.`,{hint:"Run `cognite auth login` to login."});let s=await nn(e,t,i.accessToken,o.createClient);return await ss(s,e,n),s}r(as,"resolveViaSession");async function cs(e,t,n,o){switch(e.method){case"client-credentials":return o.getSdkFn(t,n.appId);case"session":return as(t,n.appId,e.org,o);case"browser":return ns(t,n,o)}}r(cs,"buildClientForAuthMethod");async function j(e,t,n={}){let{login:o=zt,getSdk:i=tn,createClient:s=r(g=>new uu(g),"createClient"),readSessionMetadata:a=ke,ensureFreshSession:c=We,promptAuthMethod:l=en,confirmActionTarget:p=Qt,isTTY:d=process.stdin?.isTTY??!1,now:u=r(()=>new Date,"now")}=n,f=Zi(e,t,{readSessionMetadata:a,now:u}),y=await Ji(f,e,t,{promptAuthMethod:l,confirmActionTarget:p,isTTY:d});return cs(y,e,t,{loginFn:o,getSdkFn:i,createClient:s,ensureFreshSession:c})}r(j,"buildAppHostingApiClient");async function on(e,t,n={}){let o=await j(e,t,n);return new _(o)}r(on,"buildAppHostingClient");import ls from"enquirer";var ps="Enter custom target...";function ds(e,t){let n=t.map((o,i)=>` ${i}: ${o.org}/${o.project}`).join(`
|
|
34
34
|
`);throw new Error(`Deployment "${e}" not found. Available deployments:
|
|
35
|
-
${n}`)}r(
|
|
35
|
+
${n}`)}r(ds,"deploymentNotFoundError");function $(e,t){if(e.length===0)throw new Error("No deployments configured in app.json");if(t===void 0)return e[0];if(/^\d+$/.test(t)){let o=e[Number.parseInt(t)];if(o)return o;ds(t,e)}let n=e.find(o=>o.project===t||`${o.org}/${o.project}`===t);if(n)return n;ds(t,e)}r($,"findDeployment");async function L(e,t){if(t.confirmActionTarget!==void 0)throw new m("Pass -d/--deployment <target> to choose a target non-interactively \u2014 --confirm-action-target cannot be combined with --interactive.",{shouldReport:!1,hint:"--interactive already prompts for the target, so there is nothing for --confirm-action-target to acknowledge."});if(t.baseUrl&&t.project)return{org:t.org??"",project:t.project,baseUrl:t.baseUrl,deployClientId:"",deploySecretName:"",published:!1,idpType:"cdf"};if(t.deployment!==void 0)return $(e.deployments,t.deployment);let n=[...e.deployments.map(s=>`${s.org}/${s.project}`),ps],{selected:o}=await ls.prompt({type:"select",name:"selected",message:"Select deployment target",choices:n});if(o!==ps){let s=e.deployments.find(a=>`${a.org}/${a.project}`===o);if(s)return s;throw new Error(`Deployment "${o}" could not be resolved from app.json.`)}let i=await ls.prompt([{type:"input",name:"baseUrl",message:"CDF Base URL",initial:"https://api.cognitedata.com"},{type:"input",name:"project",message:"CDF Project",validate:r(s=>s?!0:"Project is required","validate")},{type:"input",name:"org",message:"Organization (for login hint)",initial:""}]);return{org:i.org||"",project:i.project,baseUrl:i.baseUrl,deployClientId:"",deploySecretName:"",published:!1,idpType:"cdf"}}r(L,"resolveDeployment");function us(e,t=process.cwd(),n={}){let o=n.readSessionMetadata??ke,i=n.loadAppConfig??k;if(e.org)return e.org;let s=o();if(s?.org)return s.org;try{let a=i(t),c=$(a.deployments,void 0);if(c.org)return c.org}catch{}throw new m("Could not determine org.",{hint:"Pass --org <org>, run `cognite auth login`, or run from an agent directory with app.json.",shouldReport:!1})}r(us,"resolveOrg");function T(e,t=1){return" ".repeat(t).concat(e)}r(T,"indent");async function z(e,t=process.cwd(),n={}){let o=n.ensureFreshSession??We,i=n.fetchUserInfo??qt,s=n.loadAppConfig??k,a=n.createClient??(l=>new mu(l));if(e.interactive&&e.baseUrl&&e.project)return await j(hu(e),{interactive:!0,appId:"cognite-cli",orgHint:e.org},n.getClient);let c=await gu(e,o,i,a);if(c)return c;try{let l=s(t),p=e.interactive?await L(l,e):$(l.deployments,void 0);return await j(p,{interactive:e.interactive,appId:"cognite-cli",orgHint:e.org},n.getClient)}catch{}throw new m("Not signed in.",{hint:"Run `cognite auth login` to start a session, or pass --interactive --base-url <url> --project <project>.",shouldReport:!1})}r(z,"getAgentClient");async function gu(e,t,n,o){let i;try{i=await t()}catch(p){if(p instanceof He)throw new m("Your session has expired.",{hint:"Run `cognite auth login` to sign in again.",shouldReport:!1,cause:p});return null}if(!i)return null;let s=await n(i),a=fu(e.project,s.projects),c=`https://${a.cluster}`,l=o({appId:"cognite-cli",project:a.name,baseUrl:c,oidcTokenProvider:r(async()=>((await t())?.accessToken??i.accessToken).expose(),"oidcTokenProvider")});return await l.authenticate(),l}r(gu,"trySessionClient");function fu(e,t){if(e){let o=t.find(i=>i.name===e);if(!o?.cluster)throw new m(`Project "${e}" not found in your session.`,{hint:t.length?`Available projects: ${t.map(i=>i.name).join(", ")}`:"Your session has no reachable projects. Check your org and permissions.",shouldReport:!1});return{...o,cluster:o.cluster}}let n=t.find(o=>o.isDefault);if(n?.cluster)return{...n,cluster:n.cluster};if(t.length===1&&t[0].cluster)return{...t[0],cluster:t[0].cluster};throw t.length===0?new m("No reachable projects found in your session.",{hint:"Check your org and permissions, or pass --project <project>.",shouldReport:!1}):new m("Multiple projects available \u2014 specify which one to use.",{hint:`Pass --project <name>. Available: ${t.map(o=>o.name).join(", ")}`,shouldReport:!1})}r(fu,"resolveSessionProject");function hu(e){return{org:e.org??"",project:e.project??"",baseUrl:e.baseUrl??"",deployClientId:"",deploySecretName:"",published:!1,idpType:"cdf"}}r(hu,"getDeployment");var Mo=class Mo extends be{constructor(){super("create");this.handle=r(async(n,o,i)=>{let s=i.optsWithGlobals(),a=s.prompt;a&&Ot();let c={externalId:s.externalId,displayName:s.displayName,description:s.description,model:s.model,instructions:s.instructions,runtimeVersion:s.runtimeVersion},l=n==="."||n==="./",p=Au(n,l),d=[];if(a&&!c.model?.trim())try{let y=await z(s);d=await ee(y).getAvailableModels()}catch{}let u=await new Ft(p,c,a,d).resolve(),f=Eu(l,u.dirName);await bu(f,l,u.dirName),await rn(he(f,$e(Fo(f))),this.buildAgentYaml(u)),await this.scaffoldEvalCases(f,u),await rn(he(f,w.readme),await this.buildReadme(u)),await this.scaffoldAgentsMd(f),await this.scaffoldSkills(f),this.printSummary(u)},"handle");this.buildAgentYaml=r(({dirName:n,...o})=>ge(o),"buildAgentYaml");this.buildReadme=r(async n=>{let o=await Oo(he(sn,"agents","create",w.readmeTemplate),"utf8");return gs(o,{displayName:n.name})},"buildReadme");this.scaffoldAgentsMd=r(async n=>{let o=await Oo(he(sn,"agents","create",w.agentsMdTemplate),"utf8");await rn(he(n,w.agentsMd),o)},"scaffoldAgentsMd");this.scaffoldSkills=r(async n=>{let o=he(sn,"agents","create","skills");for(let i of li){let s=he(n,i);await yu(o,s,{recursive:!0})}},"scaffoldSkills");this.scaffoldEvalCases=r(async(n,o)=>{let i=he(n,w.evalDir);await hs(i,{recursive:!0});let s=await Oo(he(sn,"agents","create",w.evalCasesTemplate),"utf8"),a=gs(s,{displayName:o.name});await rn(he(i,w.evalCases),a)},"scaffoldEvalCases");this.printSummary=r(n=>{let o=P(process.stdout),i=n.dirName;console.log(),console.log(o.green(`Created agent project at ${i}/`)),console.log(),console.log(T(`directory: ${i}/`)),console.log(T(`externalId: ${n.externalId}`)),console.log(T(`display name: ${n.name}`)),n.model&&console.log(T(`model: ${n.model}`)),console.log(),console.log("Next steps:"),console.log(T(`1. Edit ${i}/${$e(Fo(i))} \u2014 add tools and refine instructions`)),console.log(T(`2. cognite agents push ${i}`)),console.log(T(`3. cognite agents open ${i}`)),console.log(T(`4. Edit ${i}/${it} and run: cognite agents eval ${i}`)),console.log()},"printSummary");this.description("Scaffold a new agent project").argument("[dir]","Agent name / directory").addHelpText("after",wu);for(let n of Object.values(ys))this.addOption(n);this.action(this.handle)}};r(Mo,"CreateCommand");var an=Mo,ys=Object.freeze({externalId:new Be("--external-id <id>","Agent externalId"),displayName:new Be("--display-name <name>","Agent display name"),description:new Be("--description <text>","Agent description"),model:new Be("--model <model>","Language model (e.g. azure/gpt-4.1)"),instructions:new Be("--instructions <text>","Agent instructions"),runtimeVersion:new Be("--runtime-version <version>","Agent runtime version"),noPrompt:new Be("--no-prompt","Skip interactive prompts, use defaults")}),lE=Object.values(ys).map(e=>e.long),wu=`
|
|
36
36
|
Examples:
|
|
37
37
|
cognite agents create Interactive scaffold
|
|
38
38
|
cognite agents create my-agent Scaffold with name "my-agent"
|
|
@@ -40,40 +40,40 @@ Examples:
|
|
|
40
40
|
--description "Helps with maintenance" \\
|
|
41
41
|
--model azure/gpt-4.1 \\
|
|
42
42
|
--no-prompt Fully non-interactive
|
|
43
|
-
`,
|
|
43
|
+
`,Ss=Su(vu(import.meta.url)),ms=Lo(Ss,"..","..","_templates"),Cu=Lo(Ss,"..","..","..","_templates"),sn=fs(ms)?ms:Cu;function Au(e,t){return t?Fo(process.cwd()):e}r(Au,"normalizeDirArg");function Eu(e,t){return e?process.cwd():Lo(process.cwd(),t)}r(Eu,"resolveTargetDir");async function bu(e,t,n){if(t){let o=await at(e);if(o.length>0){let i=o.length===1?"an agent definition":"agent definitions";throw new m(`This directory already contains ${i}:
|
|
44
44
|
${o.map(s=>` - ${s}`).join(`
|
|
45
|
-
`)}`,{hint:"Scaffold into a new directory instead, or use `cognite agents pull <external-id> --force` to overwrite.",shouldReport:!1})}return}if(
|
|
46
|
-
${e}`,{hint:"Use a different agent name or remove the existing directory.",shouldReport:!1});await
|
|
45
|
+
`)}`,{hint:"Scaffold into a new directory instead, or use `cognite agents pull <external-id> --force` to overwrite.",shouldReport:!1})}return}if(fs(e))throw new m(`An agent folder named "${n}" already exists at:
|
|
46
|
+
${e}`,{hint:"Use a different agent name or remove the existing directory.",shouldReport:!1});await hs(e)}r(bu,"ensureTargetDir");function gs(e,t){return e.replace(/\{\{(\w+)\}\}/g,(n,o)=>t[o]??"")}r(gs,"renderTemplate");import{resolve as la}from"path";import{isDeepStrictEqual as Vm}from"util";import{Option as we}from"commander";function ye(e){return e.invokeError??e.scoreError?!1:e.evalCase.expectPass!==!1?e.passed:!e.passed}r(ye,"caseVerdictPassed");function Uo(e){return e.some(t=>!ye(t))}r(Uo,"hasCaseVerdictFailures");function gt(e){return e.filter(t=>!ye(t)).length}r(gt,"countCaseVerdictFailures");function ft(e){return e.filter(ye).length}r(ft,"countCaseVerdictPasses");function ht(e){return e.filter(t=>t.evalCase.expectPass===!1&&!t.invokeError&&!t.scoreError&&t.passed).length}r(ht,"countUnexpectedPasses");import{readFile as Lu,stat as Mu}from"fs/promises";import{join as ln,relative as Uu,sep as _u}from"path";import{safeParse as bs}from"valibot";import{parse as Nu}from"yaml";import{array as ve,boolean as xu,literal as cn,minLength as Xe,nonEmpty as q,object as ce,optional as Se,pipe as O,string as J,variant as ku}from"valibot";var Pu=ce({type:cn("correctness"),criteria:O(J(),q("must not be empty"))}),Tu=ce({type:cn("faithfulness"),groundTruth:O(J(),q("must not be empty"))}),Ru=ce({name:O(J(),q("must not be empty")),description:O(J(),q("must not be empty"))}),yt=Se(O(ve(Ru),Xe(1,"must contain at least one tool"))),Iu=ce({type:cn("toolSelection"),tools:yt}),Du=ce({type:cn("toolInvocation"),tools:yt}),$u=ku("type",[Pu,Tu,Iu,Du]),vs=["correctness","faithfulness","toolSelection","toolInvocation"],Ou=ce({input:O(J(),q("must not be empty")),scorers:Se(O(ve($u),Xe(1,"must contain at least one scorer")))}),Fu=ce({space:O(J(),q("must not be empty")),externalId:O(J(),q("must not be empty")),version:O(J(),q("must not be empty"))}),_o=ce({dataModels:Se(O(ve(Fu),Xe(1,"must contain at least one data model"))),instanceSpaces:Se(O(ve(O(J(),q("must not be empty"))),Xe(1,"must contain at least one instance space"))),appContext:Se(O(J(),q("must not be empty")))}),ws=ce({id:O(J(),q("must not be empty")),tags:Se(ve(O(J(),q("tag must not be empty")))),expectPass:Se(xu(),!0),turns:O(ve(Ou),Xe(1,"must contain at least one turn")),..._o.entries,tools:yt}),Cs=ce({include:Se(ve(O(J(),q("include path must not be empty")))),cases:Se(ve(ws)),..._o.entries,tools:yt}),As=ce({tags:Se(ve(O(J(),q("tag must not be empty")))),cases:O(ve(ws),Xe(1,"must contain at least one case")),..._o.entries,tools:yt});function xs(e,t){let n=e,{caseFilter:o,tagFilter:i}=t??{};if(o&&o.length>0&&(n=n.filter(s=>o.includes(s.id))),i&&i.length>0){let s=new Set(i);n=n.filter(a=>a.tags?.some(c=>s.has(c)))}if(n.length===0)throw new m("No eval cases matched the filter.",{hint:"Check the --case and --tag flag values against the loaded eval suite.",shouldReport:!1});return n}r(xs,"filterEvalCases");function ks(e,t){return Uu(e,t).split(_u).join("/")}r(ks,"displaySource");function ju(e){if(e&&typeof e=="object"&&"code"in e&&typeof e.code=="string")return e.code}r(ju,"nodeErrorCode");async function Es(e){try{return(await Mu(e)).isFile()}catch(t){if(ju(t)==="ENOENT")return!1;let n=t instanceof Error?t.message:String(t);throw new m(`Cannot access eval suite file:
|
|
47
47
|
${e}
|
|
48
|
-
${n}`,{cause:t,shouldReport:!1})}}r(
|
|
48
|
+
${n}`,{cause:t,shouldReport:!1})}}r(Es,"isRegularFile");async function Hu(e){let t=ln(e,w.evalCases),n=ln(e,w.evalDir,w.evalCases),[o,i]=await Promise.all([Es(t),Es(n)]);if(o&&i)throw new m(`Found both eval suite layouts in:
|
|
49
49
|
${e}
|
|
50
50
|
- ${t}
|
|
51
|
-
- ${n}`,{hint:`Keep one eval suite config: either ${
|
|
51
|
+
- ${n}`,{hint:`Keep one eval suite config: either ${w.evalCases} in the directory you pass, or ${it} for an agent project. Remove the other.`,shouldReport:!1});if(o)return{evalDir:e,rootPath:t};if(i)return{evalDir:ln(e,w.evalDir),rootPath:n};throw new m(`No eval suite config found in:
|
|
52
52
|
${e}
|
|
53
53
|
Attempted:
|
|
54
54
|
- ${t}
|
|
55
|
-
- ${n}`,{hint:`Add ${
|
|
56
|
-
${e}`,{shouldReport:!1})}try{return
|
|
55
|
+
- ${n}`,{hint:`Add ${w.evalCases} to the directory you pass, or ${it} for an agent project.`,shouldReport:!1})}r(Hu,"resolveEvalSuite");async function Ps(e){let{evalDir:t,rootPath:n}=await Hu(e),o=ks(e,n),{cases:i,include:s,rootContext:a,rootTools:c}=await Bu(n,o),l=await Ku(s,t,e,a,c),p=[...i,...l];if(p.length===0)throw new m("No eval cases found.",{hint:`Add a cases list or an include field to ${o}.`,shouldReport:!1});return Yu(p),zu(p),p}r(Ps,"loadEvalCases");async function Bu(e,t){let n=await Ts(e),o=bs(Cs,n);if(!o.success)throw new m(`Invalid ${e}: ${Rs(o.issues)}`,{shouldReport:!1});let{include:i,cases:s,tools:a,...c}=o.output;return{cases:(s??[]).map(p=>Is(p,t,c,a)),include:i,rootContext:c,rootTools:a}}r(Bu,"loadRootCasesFile");async function Ku(e,t,n,o,i){return!e||e.length===0?[]:(await Promise.all(e.map(async a=>{let c=ln(t,a),l=ks(n,c),p=await Ts(c),d=bs(As,p);if(!d.success)throw new m(`Invalid ${c}: ${Rs(d.issues)}`,{shouldReport:!1});let{tags:u,cases:f,tools:y,...g}=d.output;return f.map(h=>Is(h,l,o,i,{fileContext:g,fileTags:u,fileTools:y}))}))).flat()}r(Ku,"loadIncludedFiles");async function Ts(e){let t;try{t=await Lu(e,"utf8")}catch{throw new m(`Eval file not found:
|
|
56
|
+
${e}`,{shouldReport:!1})}try{return Nu(t)}catch(n){throw new m(`Failed to parse ${e}: ${n instanceof Error?n.message:String(n)}`,{hint:"Check the YAML syntax of the file.",shouldReport:!1})}}r(Ts,"readAndParseYaml");function Rs(e){return e.map(t=>{let n=t.path?.map(o=>String(o.key)).join(".")??"";return n?`${n}: ${t.message}`:t.message}).join("; ")}r(Rs,"formatValidationIssues");function Vu(e,t,n){let o=n?.dataModels??t?.dataModels??e.dataModels,i=n?.instanceSpaces??t?.instanceSpaces??e.instanceSpaces,s=n?.appContext??t?.appContext??e.appContext;if(!o&&!i&&!s)return;let a={};return o&&(a.dataModels=o),i&&(a.instanceSpaces=i),s&&(a.appContext=s),a}r(Vu,"mergeSessionContext");function Gu(e,t){if(t){if(t.dataModels&&!t.instanceSpaces)throw new m(`Case "${e}" declares dataModels without instanceSpaces`,{hint:"Add instanceSpaces alongside dataModels in your session context.",shouldReport:!1});if(t.instanceSpaces&&!t.dataModels)throw new m(`Case "${e}" declares instanceSpaces without dataModels`,{hint:"Add dataModels alongside instanceSpaces in your session context.",shouldReport:!1})}}r(Gu,"assertDataModelScopePairing");function Is(e,t,n,o,i){let{id:s,turns:a,tags:c,expectPass:l,dataModels:p,instanceSpaces:d,appContext:u,tools:f}=e,y=i?.fileTags&&i.fileTags.length>0?[...new Set([...i.fileTags,...c??[]])]:c,g=Vu(n,i?.fileContext,{dataModels:p,instanceSpaces:d,appContext:u});Gu(s,g);let h=f??i?.fileTools??o;return{id:s,turns:a,expectPass:l,...y?{tags:y}:{},source:t,contextInformation:g,...h?{tools:h}:{}}}r(Is,"buildEvalCase");function Yu(e){let t=new Map;for(let{id:n,source:o}of e){let i=t.get(n)??[];i.push(o),t.set(n,i)}for(let[n,o]of t){if(o.length<=1)continue;let s=[...new Set(o)].map(a=>` - ${a}`).join(`
|
|
57
57
|
`);throw new m(`Duplicate case id "${n}"
|
|
58
58
|
Defined in:
|
|
59
|
-
${s}`,{hint:"Each case must have a unique id.",shouldReport:!1})}}r(
|
|
60
|
-
`)}r(
|
|
61
|
-
`).trim()}r(
|
|
59
|
+
${s}`,{hint:"Each case must have a unique id.",shouldReport:!1})}}r(Yu,"assertUniqueCaseIds");function zu(e){for(let t of e)if(!t.turns.some(o=>o.scorers&&o.scorers.length>0))throw new m(`Case "${t.id}" (${t.source}) has no scored turns`,{hint:"Add scorers to at least one turn in each case.",shouldReport:!1})}r(zu,"assertCaseHasScoredTurn");function Fe(e){if(e===null||typeof e!="object")return JSON.stringify(e);let t=e.toJSON;if(typeof t=="function")return Fe(t.call(e));if(Array.isArray(e))return`[${e.map(Fe).join(",")}]`;let n=e;return`{${Object.keys(n).filter(i=>n[i]!==void 0).sort().map(i=>`${JSON.stringify(i)}:${Fe(n[i])}`).join(",")}}`}r(Fe,"stableStringify");function No(e){try{return Fe(e)}catch{return String(e)}}r(No,"safeStableStringify");var qu=["name","description","instructions","model","runtimeVersion"],Ju=["labels","tools","skills","subagents","exampleQuestions"];function Fs(e,t){let n=Ue(e),o=Ue(t),i=[];for(let s of qu){let a=n[s],c=o[s];Wu(a,c)||i.push({field:s,local:Ds(a),remote:Ds(c)})}for(let s of Ju){let a=n[s],c=o[s];Zu(s,a,c)||i.push({field:s,local:$s(s,a),remote:$s(s,c)})}return i}r(Fs,"detectDrift");function Ls(e,t){let n=e.map(i=>i.field).join(", "),o=[`Warning: local ${w.configGlob} differs from deployed config.`,` Fields: ${n}`];if(t?.verbose)for(let{field:i,remote:s,local:a}of e){let c=`${i}:`.padEnd(18);o.push(` ${c}"${s}" \u2192 "${a}"`)}return o.push(" Run with --upsert to push local changes before evaluating."),o.join(`
|
|
60
|
+
`)}r(Ls,"formatAgentDriftWarning");function Wu(e,t){return jo(e)===jo(t)}r(Wu,"scalarValuesEqual");function Zu(e,t,n){return Bo(Ho(t),e)===Bo(Ho(n),e)}r(Zu,"arrayValuesEqual");function jo(e){return e??""}r(jo,"normalizeOptionalString");function Ds(e){return jo(e)}r(Ds,"formatScalarValue");function $s(e,t){return Bo(Ho(t),e)}r($s,"formatArrayValue");function Ho(e){return e??[]}r(Ho,"normalizeArray");function Bo(e,t){let n=[...e].sort((o,i)=>Os(t,o).localeCompare(Os(t,i)));return Fe(n)}r(Bo,"stableArrayStringify");function Os(e,t){if(typeof t!="object"||t===null)return Fe(t);let n=t;switch(e){case"tools":return String(n.name??"");case"subagents":return String(n.agentExternalId??"");case"exampleQuestions":return String(n.question??"");default:return Fe(t)}}r(Os,"arrayItemSortKey");async function Ms(e,t){if(e)try{e.track("Flows.CLI.Agents.Eval",{...t}),await e.flush(qe)}catch{}}r(Ms,"trackAgentsEval");function Xu(e){return typeof e=="object"&&e!==null&&e.type==="result"&&Array.isArray(e.messages)}r(Xu,"isSessionResult");function Ko(e){let t=e.content?.text;if(typeof t=="string"&&t.length>0)return t;let n=[];for(let o of e.reasoning??[])for(let i of o.content??[])typeof i.text=="string"&&i.text.length>0&&n.push(i.text);return n.join(`
|
|
61
|
+
`).trim()}r(Ko,"messageText");function pn(e){return e.map(t=>t.name).join(", ")}r(pn,"formatToolNameList");var Qe=500;function Us(e,t){return e.length<=t?e:`${e.slice(0,t)}\u2026 (${e.length-t} more chars)`}r(Us,"truncate");function Vo(e){try{return JSON.stringify(e)??String(e)}catch{return String(e)}}r(Vo,"safeJsonEncode");function et(e,t=1/0){if(e.input===void 0||e.input===null)return`${e.name}()`;let n;if(typeof e.input=="object"&&!Array.isArray(e.input)){let o=Object.entries(e.input);if(o.length===0)return`${e.name}()`;n=o.map(([i,s])=>`${i}=${Vo(s)}`).join(", ")}else n=Vo(e.input);return`${e.name}(${Us(n,t)})`}r(et,"formatToolInvocation");function dn(e,t=Qe){let n=typeof e=="string"?e:Vo(e);return n=n.replace(/\s+/g," ").trim(),Us(n,t)}r(dn,"formatToolResultPreview");function Qu(e){let t=[];for(let n of e)for(let o of n.reasoning??[])for(let i of o.data??[]){let s=i.toolCall;typeof s?.name=="string"&&s.name.length>0&&t.push({name:s.name,input:s.input,result:s.result})}return t}r(Qu,"extractToolCalls");function em(e){let t=[];for(let n of e){let o=!1;for(let i of n.reasoning??[]){for(let s of i.data??[]){let a=s.toolCall;if(typeof a?.name=="string"&&a.name.length>0){o=!0;break}}if(o)break}if(!o)for(let i of n.actions??[]){let s=i.toolConfirmation;typeof s?.toolName=="string"&&s.toolName.length>0&&t.push({name:s.toolName,input:s.toolArguments,synthesized:!0})}}return t}r(em,"synthesizeToolConfirmationCalls");function _s(e,t){for(let n of t){if(n.synthesized){e.push(n);continue}let o=e.findIndex(i=>i.synthesized===!0&&i.name===n.name&&No(i.input)===No(n.input));o!==-1?e[o]=n:e.push(n)}}r(_s,"mergeToolCalls");function Ns(e){let t=e.response;if(!Xu(t))throw new Error("Unexpected agent chat response shape");let n=t.messages,o=n[n.length-1];if(!o)throw new Error("Agent returned no messages");let i=[...Qu(n),...em(n)],s=o.actions?.find(c=>c.type==="toolConfirmation");if(s){let c=s.actionId??s.id;if(!c)throw new Error("Tool confirmation action missing actionId (both actionId and id are absent)");return{output:Ko(o),toolCalls:i,cursor:t.cursor,pendingToolConfirmation:{actionId:c,toolName:s.toolConfirmation?.toolName}}}let a=o.actions?.find(c=>c.type==="userSession");if(a){let c=a.actionId??a.id;if(!c)throw new Error("User session action missing actionId (both actionId and id are absent)");return{output:Ko(o),toolCalls:i,cursor:t.cursor,pendingUserSession:{actionId:c}}}return{output:Ko(o),toolCalls:i,cursor:t.cursor}}r(Ns,"extractAgentTurn");function Hs(e){let{modelId:t,service:n,verbose:o}=e;return{specificationVersion:"v2",provider:"cdf",modelId:t,supportedUrls:{},async doGenerate(i){return tm(i,{modelId:t,service:n,verbose:o})},async doStream(i){throw new Error("CDF chat completions judge does not support streaming")}}}r(Hs,"createCdfChatCompletionsModel");async function tm(e,t){let{modelId:n,service:o,verbose:i}=t,s=nm(e.responseFormat),a=om(e.prompt,s),c={model:n,messages:a,stream:!1,temperature:e.temperature,maxTokens:e.maxOutputTokens};i?.logJson("chat/completions request",c),i?.log("judge POST /ai/chat/completions");let l=performance.now(),p=await o.postChatCompletions(c);i?.log(`judge chat/completions HTTP 200 in ${((performance.now()-l)/1e3).toFixed(1)}s`),i?.logJson("chat/completions response",p);let d=p.choices[0]?.message?.content??"",u=p.choices[0]?.finishReason??"stop";return{content:[{type:"text",text:d}],finishReason:rm(u),usage:{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},warnings:[],request:{body:c},response:{modelId:p.model??n,body:p}}}r(tm,"generateWithCdf");function nm(e){if(!e||e.type==="text")return;let t=e.schema?JSON.stringify(e.schema):'{"label":"string","explanation":"string"}',n=e.name?` (${e.name})`:"";return`Respond with a single valid JSON object only. No markdown code fences or extra text.${e.description?`
|
|
62
62
|
${e.description}`:""}
|
|
63
|
-
The JSON must conform to this schema${n}: ${t}`}r(
|
|
64
|
-
`)}r(
|
|
63
|
+
The JSON must conform to this schema${n}: ${t}`}r(nm,"jsonResponseInstruction");function om(e,t){let n=[];t&&n.push({role:"system",content:t});for(let o of e){if(o.role==="system"){n.push({role:"system",content:o.content});continue}if(o.role==="user"){let i=js(o.content);i&&n.push({role:"user",content:i});continue}if(o.role==="assistant"){let i=js(o.content);i&&n.push({role:"assistant",content:i})}}return n}r(om,"toCdfMessages");function js(e){return e.filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join(`
|
|
64
|
+
`)}r(js,"extractTextParts");function rm(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":case"content-filter":return"content-filter";case"tool_calls":case"tool-calls":return"tool-calls";default:return"other"}}r(rm,"mapFinishReason");var im="azure/gpt-5";function Go(e={}){return e.cliModelId?.trim()||process.env.EVAL_JUDGE_MODEL?.trim()||e.agentModelFallback?.trim()||im}r(Go,"resolveJudgeModelId");function Bs(e){let t=e.modelId??Go({cliModelId:e.cliModelId,agentModelFallback:e.agentModelFallback});return Hs({modelId:t,service:e.service,verbose:e.verbose})}r(Bs,"createJudgeModel");import{mkdir as fm,writeFile as hm}from"fs/promises";import{join as zs}from"path";var Ke="report.json",Yo="report.md";var un="eval-report";function mn(e){let t={name:e.name,message:e.message};ue(e)&&(e.hint&&(t.hint=e.hint),e.helpUrl&&(t.helpUrl=e.helpUrl)),Tt(e)&&(t.http={status:e.httpStatusCode,...e.requestUrl!==void 0&&{url:e.requestUrl},...e.responseBody!==void 0&&{responseBody:e.responseBody}});let n=e.cause;return n instanceof Error&&(t.cause=mn(n)),t}r(mn,"serializeError");function zo(e,t,n){return{version:1,meta:n,summary:{totalCases:e.totalCases,passedCases:e.passedCases,failedCases:e.failedCases,skippedCases:e.skippedCases,metExpectations:ft(e.results),verdictFailures:gt(e.results),unexpectedPassCount:ht(e.results)},cases:e.results.map(Vs),traces:t}}r(zo,"buildEvalReportDocument");function Vs(e){let t=e.evalCase;return{id:t.id,source:t.source,...t.tags!==void 0&&t.tags.length>0&&{tags:t.tags},expectPass:t.expectPass!==!1,scorersPassed:e.passed,verdictPassed:ye(e),...t.contextInformation!==void 0&&{contextInformation:t.contextInformation},...e.run&&{turns:e.run.turns.map(n=>({input:n.input,output:n.output,toolCalls:n.toolCalls.map(o=>({name:o.name,...o.input!==void 0&&{input:o.input},...o.result!==void 0&&{result:o.result}})),apiRoundTrips:n.apiRoundTrips}))},scores:e.scores.map(n=>({turnIndex:n.turnIndex,scorerType:n.scorerType,score:n.score,...n.label!==void 0&&{label:n.label},...n.explanation!==void 0&&{explanation:n.explanation},passed:n.passed})),...e.invokeError&&{invokeError:mn(e.invokeError)},...e.scoreError&&{scoreError:mn(e.scoreError)}}}r(Vs,"serializeCaseResult");function Jo(e){let t=e.summary.skippedCases>0?` (${e.summary.skippedCases} skipped)`:"";return mm(`
|
|
65
65
|
# Agent eval report
|
|
66
66
|
|
|
67
67
|
- Agent: \`${e.meta.agentExternalId}\`
|
|
68
68
|
- Judge model: \`${e.meta.judgeModelId}\`
|
|
69
69
|
- Chat route: \`${e.meta.route}\`
|
|
70
70
|
- Summary: **${e.summary.metExpectations}/${e.cases.length}** cases met expectations${t}
|
|
71
|
-
- Full verbose-equivalent traces: \`${
|
|
71
|
+
- Full verbose-equivalent traces: \`${Ke}\` (${e.traces.length} event(s))
|
|
72
72
|
|
|
73
|
-
${e.cases.map(
|
|
73
|
+
${e.cases.map(sm).join(`
|
|
74
74
|
`)}
|
|
75
|
-
${
|
|
76
|
-
`)}r(
|
|
75
|
+
${pm(e.traces)}
|
|
76
|
+
`)}r(Jo,"formatEvalReportMarkdown");function sm(e){let t=e.verdictPassed?"PASS":"FAIL",n=e.expectPass===!1?" (expected fail)":"",o=e.tags&&e.tags.length>0?`- Tags: ${e.tags.map(i=>`\`${i}\``).join(", ")}
|
|
77
77
|
`:"";return`
|
|
78
78
|
## ${t}: \`${e.id}\`${n}
|
|
79
79
|
|
|
@@ -81,112 +81,112 @@ ${nm(e.traces)}
|
|
|
81
81
|
- Verdict: ${e.verdictPassed?"met expectations":"did not meet expectations"}
|
|
82
82
|
- Scorers: ${e.scorersPassed?"all passed":"failed or missing"}
|
|
83
83
|
${o}
|
|
84
|
-
${e.invokeError?
|
|
85
|
-
`}r(
|
|
86
|
-
`):e.scores.length>0?
|
|
84
|
+
${e.invokeError?Gs("Invoke error",e.invokeError):""}${e.scoreError?Gs("Score error",e.scoreError):""}${am(e)}
|
|
85
|
+
`}r(sm,"formatCaseMarkdown");function am(e){return e.turns?e.turns.map((t,n)=>cm(t,n,e)).join(`
|
|
86
|
+
`):e.scores.length>0?Ys(e.scores,{showTurnIndex:!0}):""}r(am,"formatCaseBodyMarkdown");function cm(e,t,n){let i=(n.turns?.length??0)>1?`### Turn ${t+1}`:"### Turn",s=n.scores.filter(a=>a.turnIndex===t);return`
|
|
87
87
|
${i}
|
|
88
88
|
|
|
89
89
|
**Prompt**
|
|
90
90
|
|
|
91
|
-
${
|
|
91
|
+
${qo(e.input)}
|
|
92
92
|
|
|
93
93
|
**Response**
|
|
94
94
|
|
|
95
|
-
${
|
|
95
|
+
${qo(e.output||"(empty)")}
|
|
96
96
|
|
|
97
|
-
${
|
|
98
|
-
`}r(
|
|
97
|
+
${lm(e.toolCalls)}${s.length>0?Ys(s):""}
|
|
98
|
+
`}r(cm,"formatTurnMarkdown");function lm(e){return e.length===0?"":`
|
|
99
99
|
**Tool calls**
|
|
100
100
|
|
|
101
|
-
${e.map(n=>{let o=
|
|
101
|
+
${e.map(n=>{let o=et(n,Qe),i=n.result!==void 0?` \u2192 ${dn(n.result,Qe)}`:"";return`- ${gm(`${o}${i}`)}`}).join(`
|
|
102
102
|
`)}
|
|
103
|
-
`}r(
|
|
103
|
+
`}r(lm,"formatToolCallsMarkdown");function Ys(e,t={}){return`
|
|
104
104
|
**Scorers**
|
|
105
105
|
|
|
106
106
|
${e.map(o=>{let i=t.showTurnIndex===!0?` (turn ${o.turnIndex+1})`:"",s=[o.label?`label=${o.label}`:void 0,`score=${o.score}`].filter(Boolean).join(", "),a=o.explanation?`
|
|
107
107
|
- ${o.explanation}`:"";return`- \`${o.scorerType}\`${i}: **${o.passed?"pass":"fail"}** (${s})${a}`}).join(`
|
|
108
108
|
`)}
|
|
109
|
-
`}r(
|
|
109
|
+
`}r(Ys,"formatScoresMarkdown");function pm(e){if(e.length===0)return"";let t=e.slice(0,40),n=t.map(i=>i.type==="log"?`- ${i.message}`:`- JSON: ${i.label}`).join(`
|
|
110
110
|
`),o=e.length>t.length?`
|
|
111
|
-
- \u2026 ${e.length-t.length} more event(s) in \`${
|
|
111
|
+
- \u2026 ${e.length-t.length} more event(s) in \`${Ke}\``:"";return`
|
|
112
112
|
## Debug traces (summary)
|
|
113
113
|
|
|
114
|
-
Captured ${e.length} verbose-equivalent event(s). See \`${
|
|
114
|
+
Captured ${e.length} verbose-equivalent event(s). See \`${Ke}\` for full payloads (agent chat request/response, judge inputs, chat/completions I/O).
|
|
115
115
|
|
|
116
116
|
${n}${o}
|
|
117
|
-
`}r(
|
|
117
|
+
`}r(pm,"formatTracesMarkdown");function Gs(e,t){return`
|
|
118
118
|
### ${e}
|
|
119
119
|
|
|
120
|
-
${
|
|
121
|
-
`}r(
|
|
120
|
+
${Wo(`- Message: ${t.message}`,t.hint&&`- Hint: ${t.hint}`,t.helpUrl&&`- Help: ${t.helpUrl}`,t.http&&dm(t.http),t.cause&&um(t.cause))}
|
|
121
|
+
`}r(Gs,"formatErrorMarkdown");function dm(e){let t=e.responseBody===void 0?void 0:`- Response body:
|
|
122
122
|
|
|
123
|
-
${
|
|
124
|
-
`)}r(
|
|
123
|
+
${qo(typeof e.responseBody=="string"?e.responseBody:JSON.stringify(e.responseBody,null,2))}`;return Wo(`- HTTP status: \`${e.status}\``,e.url&&`- URL: \`${e.url}\``,t)}r(dm,"formatHttpErrorMarkdown");function um(e){return Wo(`- Cause: ${e.name}: ${e.message}`,e.http&&` - HTTP status: \`${e.http.status}\``,e.http?.url&&` - URL: \`${e.http.url}\``)}r(um,"formatCauseMarkdown");function Wo(...e){return e.filter(t=>!!t).join(`
|
|
124
|
+
`)}r(Wo,"lines");function mm(e){return`${e.replace(/^\n+/,"").replace(/\n{3,}/g,`
|
|
125
125
|
|
|
126
126
|
`).trimEnd()}
|
|
127
|
-
`}r(
|
|
127
|
+
`}r(mm,"trimBlankLines");function qo(e){return`\`\`\`
|
|
128
128
|
${e.replace(/```/g,"``\\`")}
|
|
129
|
-
\`\`\``}r(
|
|
130
|
-
`,"utf8"),await n(a,
|
|
131
|
-
${
|
|
132
|
-
\u2026 (${n.length-t} more chars)`}r(
|
|
133
|
-
`)}r(
|
|
134
|
-
`):"No tools called"}r(
|
|
129
|
+
\`\`\``}r(qo,"fence");function gm(e){let t=Math.max(0,...(e.match(/`+/g)??[]).map(i=>i.length)),n="`".repeat(t+1),o=e.startsWith("`")||e.endsWith("`")||e.startsWith(" ")||e.endsWith(" ")?" ":"";return`${n}${o}${e}${o}${n}`}r(gm,"inlineCode");async function qs(e){let t=e.mkdir??fm,n=e.writeFile??hm,o=e.reportDir;await t(o,{recursive:!0});let i=zo(e.summary,e.traces,{...e.meta,reportDir:o}),s=zs(o,Ke),a=zs(o,Yo);return await n(s,`${JSON.stringify(i,null,2)}
|
|
130
|
+
`,"utf8"),await n(a,Jo(i),"utf8"),{jsonPath:s,mdPath:a}}r(qs,"writeEvalReport");async function Js(e,t,n){let o=(e.externalId!==void 0?e.externalId.trim():void 0)??(e.systemAgent?pi:void 0);if(e.externalId!==void 0&&o==="")throw new m("--external-id cannot be empty.",{hint:`Provide a valid agent external ID, or omit the flag to read from ${w.configGlob}.`,shouldReport:!1});if(o!==void 0)return{externalId:o,agentYaml:void 0};let i=await n(t);if(!i.externalId)throw new m("No agent specified.",{hint:`Provide --external-id, --system-agent, or run from a directory with ${w.configGlob}.`,shouldReport:!1});return{externalId:i.externalId,agentYaml:i}}r(Js,"resolveAgentIdentity");var ym=new Set(["localhost","127.0.0.1"]),Sm="Pass an origin only, e.g. http://127.0.0.1:5000. Do not set COGNITE_BASE_URL to localhost \u2014 use AGENT_CHAT_BASE_URL instead.",vm="Use a loopback origin for local cog-ai. Override chat POSTs include the CLI CDF access token; they are only sent to loopback origins.";function wm(){let e=process.env.AGENT_CHAT_ROUTE?.trim().toLowerCase();return e==="public"||e==="agents"?"public":e==="internal"||e==="fusion"?"internal":"public"}r(wm,"resolveAgentChatRoute");function Ws(){let e=process.env.AGENT_CHAT_BASE_URL?.trim();if(!e)return;let t;try{t=new URL(e)}catch{throw St(e,"must be a valid URL")}if(t.protocol!=="http:"&&t.protocol!=="https:")throw St(e,"must use http or https");if(t.pathname!=="/"&&t.pathname!=="")throw St(e,"must be an origin only (e.g. http://127.0.0.1:5000), not a full API path");if(t.search||t.hash)throw St(e,"must not include query or fragment");if(!ym.has(t.hostname))throw St(e,"must target a loopback host (localhost or 127.0.0.1)",vm);return t.origin}r(Ws,"resolveAgentChatBaseUrl");function Zs(e){return e?"internal":wm()}r(Zs,"resolveEffectiveAgentChatRoute");function Xs(e,t){let n=t==="internal"?"internal/agents/chat":"agents/chat";return`/api/v1/projects/${encodeURIComponent(e)}/ai/${n}`}r(Xs,"formatAgentChatPath");function Qs(e){return`/api/v1/projects/${encodeURIComponent(e)}/ai/chat/completions`}r(Qs,"formatChatCompletionsPath");function gn(e,t){return`${e.replace(/\/+$/,"")}${t.startsWith("/")?t:`/${t}`}`}r(gn,"joinClientUrl");function St(e,t,n=Sm){return new m(`Invalid agent chat base URL "${e}": ${t}.`,{hint:n,shouldReport:!1})}r(St,"invalidChatBaseUrl");function Cm(e){return{...e,messages:e.messages.map(t=>t.role==="action"&&t.type==="userSession"?{...t,nonce:"<redacted>"}:t)}}r(Cm,"redactNonces");async function ea(e){let t=e.allowToolConfirmation!==!1,n=e.maxTurns??8,o=e.verbose;o?.log(`agentExternalId=${e.agentExternalId} | auto-allow tools=${t}`);let i=e.cursor,s,a,c,l,p=[],d="",u=0;for(let f=0;f<n;f+=1){u+=1;let y=`turn ${u}/${n}`,g;a&&c&&i?(g={agentExternalId:e.agentExternalId,cursor:i,messages:[{role:"action",type:"userSession",actionId:a,nonce:c}]},a=void 0,c=void 0):s&&i?(g={agentExternalId:e.agentExternalId,cursor:i,messages:[{role:"action",type:"toolConfirmation",actionId:s,status:"ALLOW"}]},s=void 0):g={agentExternalId:e.agentExternalId,...e.contextInformation?{contextInformation:e.contextInformation}:{},...i?{cursor:i}:{},messages:[{role:"user",content:{type:"text",text:e.input}}]},o?.log(`${y}: sending chat request\u2026`),o?.logJson(`${y} request body`,Cm(g)),l=await e.service.postAgentChat(g),o?.logJson(`${y} response`,l);let h;try{h=Ns(l)}catch(v){throw new m(`Failed to parse agent response on turn ${u}/${n}`,{hint:"The CDF agent API returned an unexpected response shape. Run with --verbose to see the raw response.",cause:v})}if(_s(p,h.toolCalls),o?.log(`${y}: extracted output length=${h.output.length}, tools=[${pn(h.toolCalls)}]`),h.output&&(d=h.output),h.pendingToolConfirmation){if(o?.log(`${y}: tool confirmation requested \u2014 tool=${h.pendingToolConfirmation.toolName??"?"} actionId=${h.pendingToolConfirmation.actionId}`),!t)throw new m(`Agent requested tool confirmation (${h.pendingToolConfirmation.toolName??"unknown"}) but allowToolConfirmation is false`,{hint:"Re-run with tool confirmation enabled, or adjust the agent to avoid confirmation prompts."});if(!h.cursor||!h.pendingToolConfirmation.actionId)throw new m("Tool confirmation missing cursor or actionId",{hint:"The agent API returned an incomplete tool-confirmation action. This may be an API bug \u2014 retry or report to CDF support."});i=h.cursor,s=h.pendingToolConfirmation.actionId,o?.log(`${y}: auto-ALLOW, continuing with cursor\u2026`);continue}if(h.pendingUserSession){if(o?.log(`${y}: userSession requested \u2014 actionId=${h.pendingUserSession.actionId}, creating nonce\u2026`),!h.cursor||!h.pendingUserSession.actionId)throw new m("User session missing cursor or actionId",{hint:"The agent API returned an incomplete user-session action. This may be an API bug \u2014 retry or report to CDF support."});let v=await e.service.createSessionNonce();i=h.cursor,a=h.pendingUserSession.actionId,c=v,o?.log(`${y}: created nonce, continuing with cursor\u2026`);continue}return o?.log(`${y}: conversation complete`),{output:d,toolCalls:p,turns:u,cursor:h.cursor??i,lastResponse:l}}throw new m(`Agent chat exceeded ${n} turns (action loop?)`,{hint:"The agent may be stuck in a tool-confirmation or user-session loop. Increase maxTurns or inspect the agent configuration."})}r(ea,"invokeAgentCase");import{createCorrectnessEvaluator as Pm}from"@arizeai/phoenix-evals/llm/createCorrectnessEvaluator";import{createFaithfulnessEvaluator as Tm}from"@arizeai/phoenix-evals/llm/createFaithfulnessEvaluator";import{createToolInvocationEvaluator as Rm}from"@arizeai/phoenix-evals/llm/createToolInvocationEvaluator";import{createToolSelectionEvaluator as Im}from"@arizeai/phoenix-evals/llm/createToolSelectionEvaluator";function ta(e){return{log(t){e(t)},logJson(t,n,o=6e3){e(`${t}:
|
|
131
|
+
${Am(n,o)}`)}}}r(ta,"createEvalLogger");function na(){let e=[];return{events:e,logger:{log(t){e.push({type:"log",message:t})},logJson(t,n){e.push({type:"json",label:t,value:Em(n)})}}}}r(na,"createTraceCapture");function oa(e,t){return{log(n){e.log(n),t.log(n)},logJson(n,o,i){e.logJson(n,o,i),t.logJson(n,o,i)}}}r(oa,"teeEvalLogger");function Am(e,t=6e3){let n;try{n=JSON.stringify(e,null,2)??String(e)}catch{n=String(e)}return n.length<=t?n:`${n.slice(0,t)}
|
|
132
|
+
\u2026 (${n.length-t} more chars)`}r(Am,"formatJson");function ra(e){return e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(1)}s`}r(ra,"formatDurationMs");function Em(e){try{return JSON.parse(JSON.stringify(e)??"null")}catch{return String(e)}}r(Em,"cloneForTrace");var bm=.5,xm={correctness:{pass:"correct",fail:"incorrect"},faithfulness:{pass:"faithful",fail:"unfaithful"},toolSelection:{pass:"correct",fail:"incorrect"},toolInvocation:{pass:"correct",fail:"incorrect"}};function km(e,t){let n=xm[e];if(n){if(t.label===n.pass)return!0;if(t.label===n.fail)return!1}return(t.score??0)>=bm}r(km,"scorerPassed");async function vt(e,t,n,o,i,s){s?.log(`scoring ${n.type} (Phoenix + CDF /ai/chat/completions)\u2026`),s?.logJson(`${n.type} judge input`,i);let a=performance.now(),c;try{c=await o.evaluate(i)}catch(d){if(ue(d))throw d;let u=d instanceof Error?d.message:String(d);throw new m(`Phoenix ${n.type} judge failed (${u}). Judge uses CDF POST .../ai/chat/completions.`,{cause:d})}s?.log(`${n.type} judge finished in ${ra(performance.now()-a)}`),s?.logJson(`${n.type} judge result`,c);let l=km(n.type,c),p=typeof c.score=="number"?c.score:l?1:0;return{caseId:e,turnIndex:t,scorerType:n.type,score:p,label:c.label,explanation:c.explanation,passed:l}}r(vt,"runPhoenixLlmScorer");function ia(e=[]){return e.map(t=>`${t.name}: ${t.description}`).join(`
|
|
133
|
+
`)}r(ia,"formatAvailableTools");function Dm(e){return e.length>0?pn(e):"No tools called"}r(Dm,"formatToolSelection");function $m(e){return e.length>0?e.map(t=>et(t)).join(`
|
|
134
|
+
`):"No tools called"}r($m,"formatToolInvocations");function Om(e){let t=e.map(n=>`"${n}"`);return t.length<=1?t.join(""):`${t.slice(0,-1).join(", ")}, and ${t[t.length-1]}`}r(Om,"formatScorerTypeList");function Fm(e,t){let n=e.turns.slice(0,t);return n.length===0?"":`Conversation so far:
|
|
135
135
|
`+n.map(o=>`User: ${o.input}
|
|
136
136
|
Assistant: ${o.output}`).join(`
|
|
137
137
|
`)+`
|
|
138
138
|
|
|
139
|
-
`}r(
|
|
139
|
+
`}r(Fm,"conversationContext");async function Lm(e,t,n,o,i,s){let a=o.turns[t];if(!a)throw new m(`No agent response recorded for turn ${t+1} of case "${e.id}" (${e.source}).`,{hint:"This is an internal mismatch between scored turns and executed turns."});let c=Fm(o,t),l=s?.verbose;if(n.type==="correctness"){let d=Pm({model:i});return vt(e.id,t,n,d,{input:`${c}User question:
|
|
140
140
|
${a.input}
|
|
141
141
|
|
|
142
142
|
Criteria:
|
|
143
|
-
${n.criteria}`,output:a.output},l)}if(n.type==="faithfulness"){let d=
|
|
144
|
-
${a.input}`:a.input,output:a.output,context:n.groundTruth},l)}if(n.type==="toolSelection"||n.type==="toolInvocation"){let d=n.tools??e.tools??s?.tools??[];if(d.length===0){let f=s?.tools===void 0?`Add a tools field to the scorer, case, or eval.yaml root (${
|
|
145
|
-
${a.input}`:a.input,availableTools:
|
|
146
|
-
${a.input}`:a.input,availableTools:na(d),toolSelection:bm(a.toolCalls)},l)}let p=n;throw new m(`Scorer type "${p.type}" is not supported yet.`,{hint:`The CLI eval schema currently supports only ${xm(hs)} scorers.`,shouldReport:!1})}r(Pm,"evaluateScorer");async function Tm(e,t,n,o,i){let s=e.turns[t]?.scorers??[];return(await Promise.all(s.map(c=>Pm(e,t,c,n,o,i)))).filter(c=>c!==null)}r(Tm,"scoreTurn");async function oa(e,t,n,o){return(await Promise.all(e.turns.map((s,a)=>Tm(e,a,t,n,o)))).flat()}r(oa,"scoreCase");function Rm(e){return e.length>0&&e.every(t=>t.passed)}r(Rm,"casePassed");function Im(e,t,n){if(n<=1)return e;let o=e instanceof Error?e.message:String(e);return new m(`turn ${t+1}/${n}: ${o}`,{hint:ue(e)?e.hint:void 0,helpUrl:ue(e)?e.helpUrl:void 0,shouldReport:ue(e)?e.shouldReport:void 0,cause:e})}r(Im,"annotateTurnFailure");async function Dm(e,t){let{service:n,agentExternalId:o,judgeModel:i,verbose:s}=t;s?.log(`--- case "${e.id}" (${e.source}) invoke ---`);let a;try{let c=[],l;for(let[p,d]of e.turns.entries()){s?.log(` turn ${p+1}/${e.turns.length}: "${d.input}"`);let u;try{u=await Zs({service:n,agentExternalId:o,input:d.input,cursor:l,contextInformation:e.contextInformation,allowToolConfirmation:t.allowToolConfirmation,verbose:s})}catch(f){throw Im(f,p,e.turns.length)}l=u.cursor,c.push({input:d.input,output:u.output,toolCalls:u.toolCalls,apiRoundTrips:u.turns})}a={caseId:e.id,turns:c}}catch(c){return{evalCase:e,scores:[],passed:!1,invokeError:c instanceof Error?c:new Error(String(c))}}s?.log(`--- case "${e.id}" (${e.source}) score (Phoenix) ---`);try{let c=await oa(e,a,i,{verbose:s,tools:t.tools,warn:t.warn});return{evalCase:e,run:a,scores:c,passed:Rm(c)}}catch(c){return{evalCase:e,run:a,scores:[],passed:!1,scoreError:c instanceof Error?c:new Error(String(c))}}}r(Dm,"runCase");async function ra(e){let{cases:t,verbose:n}=e,o=[];for(let s of t){let a=await Dm(s,e);if(o.push(a),e.failFast&&!ye(a)){n?.log(`--- fail-fast: stopping after failed case "${s.id}" (${s.source}) ---`);break}}let i=o.filter(s=>s.passed).length;return{totalCases:t.length,passedCases:i,failedCases:o.length-i,skippedCases:t.length-o.length,results:o}}r(ra,"runEval");var Wo={"cdf-version":"20230101-alpha"};function ia(e,t,n={}){let{chatBaseUrl:o}=n,i=Js(e.project,t),s=Ws(e.project),a=o?mn(o,i):i,c=o?a:mn(e.getBaseUrl(),i),l=mn(e.getBaseUrl(),s);async function p(g){if(o)return d(g);try{return(await e.post(a,{data:g,headers:Wo})).data}catch(h){if(!ae(h))throw h;let w=t==="internal"&&h.status===404?" Try the public route: set AGENT_CHAT_ROUTE=public.":"";throw gn(h,"Agent chat",c,w||void 0)}}r(p,"postAgentChat");async function d(g){let h=await e.authenticate();if(!h)throw new m("Agent chat requires a CDF access token for local cog-ai.",{hint:"Run `cognite auth login` or pass --interactive with --base-url and --project.",shouldReport:!1});let w={...Wo,Authorization:`Bearer ${h}`};try{let S=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json",...w},body:JSON.stringify(g)});if(!S.ok)throw gn($m(S.status,await S.text()),"Agent chat",c);return await S.json()}catch(S){throw S instanceof ie||S instanceof m?S:Om(S,o)}}r(d,"postLoopbackAgentChat");async function u(g){try{return(await e.post(s,{data:g,headers:Wo})).data}catch(h){throw gn(h,"Chat completions",l)}}r(u,"postChatCompletions");async function f(){let g=`/api/v1/projects/${encodeURIComponent(e.project)}/sessions`;try{return await y({oneshotTokenExchange:!0},g)}catch(h){if(Lm(h))return await y({tokenExchange:!0},g);throw h}}r(f,"createSessionNonce");async function y(g,h){try{let w=await e.sessions.create([g]),S=w?.[0]?.nonce;if(!S)throw new m("Session creation returned no nonce",{hint:"The Sessions API returned an empty items list. Retry, or check IdP configuration for this project.",cause:new Error(`Response items: ${JSON.stringify(w)}`)});return S}catch(w){throw w instanceof m?w:gn(w,"Session creation",h)}}return r(y,"requestSessionNonce"),{postAgentChat:p,postChatCompletions:u,createSessionNonce:f,agentChatUrl:c,chatCompletionsUrl:l}}r(ia,"getEvalService");function $m(e,t){let n;try{n=JSON.parse(t)}catch{n={error:{message:t}}}return Object.assign(new Error(t),{status:e,data:U(n)?n:void 0})}r($m,"httpErrorFromFetchBody");function Om(e,t){return e instanceof Error?!t||!Fm(e)?e:new m(`Agent chat failed: could not connect to ${t}`,{hint:`Is cog-ai running? Try GET ${t}/health`,cause:e,shouldReport:!1}):new Error(String(e))}r(Om,"wrapConnectError");function Fm(e){let t=e,n=new Set;for(;t!=null&&!n.has(t)&&(n.add(t),typeof t=="object");){let o=t.code;if(o==="ECONNREFUSED"||o==="ENOTFOUND"||o==="ECONNRESET")return!0;t=t.cause}return!1}r(Fm,"isConnectError");function Lm(e){let t=e instanceof ie?e.httpStatusCode:ae(e)?e.status:void 0;return t===400||t===401||t===403}r(Lm,"isSessionTypeRejected");function gn(e,t,n,o){if(!ae(e))return e instanceof Error?e:new Error(String(e));let i=Ki(e),s=i?`: ${i}`:"",a=o??"";return new ie(`${t} failed (${e.status})${s}${a}`,{httpStatusCode:e.status,requestUrl:n,responseBody:xo(e),cause:e})}r(gn,"wrapCdfApiError");function ca(e){if(!e)return"(none)";let t=[],n=e.dataModels?.length??0,o=e.instanceSpaces?.length??0;return(n>0||o>0)&&t.push(`${n} data model(s), ${o} space(s)`),e.appContext&&t.push("app context"),t.length>0?t.join(", "):"(none)"}r(ca,"formatSessionContextSummary");function Um(e){let t=e.filter(s=>s.contextInformation!==void 0);if(t.length===0)return;let n=t.map(s=>s.contextInformation),o=n[0];return t.length===e.length&&n.every(s=>Mm(s,o))?ca(o):`varies by case (${t.length}/${e.length})`}r(Um,"summarizeSessionContextForStdout");function aa(e,t){return t?[...t,e]:[e]}r(aa,"collectRepeatableValues");var Zo=Object.freeze({case:new ve("--case <id>","Run only cases with this id (repeatable)").argParser(aa),tag:new ve("--tag <tag>","Run only cases with this tag (repeatable)").argParser(aa),judgeModel:new ve("--judge-model <model>","LLM model for scoring eval cases (e.g. azure/gpt-5)"),externalId:new ve("--external-id <id>",`Agent external ID (alternative to reading from ${v.configGlob})`).conflicts("systemAgent"),systemAgent:new ve("--system-agent","Evaluate the Cognite system agent (currently cdf_industrial_v4)").conflicts("externalId"),upsert:new ve("--upsert",`Push the local ${v.configGlob} to CDF before running evals`).conflicts("externalId").conflicts("systemAgent"),failFast:new ve("--fail-fast","Stop after the first failing case; skip the rest"),verbose:new ve("-v, --verbose","Log request/response traces to stderr"),failOnToolConfirmation:new ve("--fail-on-tool-confirmation","Fail a case instead of auto-approving when the agent requests tool confirmation"),reportDir:new ve("--report-dir [path]",`Write structured eval reports (report.json + report.md); defaults to ${dn} when the path is omitted`).preset(dn)}),px=Object.values(Zo).map(e=>e.long).filter(e=>e!=null);function Nm(e,t){return e.expectPass===!1?t.dim(" (expected fail)"):""}r(Nm,"formatExpectedFailSuffix");function _m(e,t,n,o,i){if(e.length!==0){t(T(n.dim("toolsCalled:"),o));for(let s of e){let a=Qe(s,Xe);!i||s.result===void 0||s.result===null?t(T(a,o+1)):t(T(`${a} ${n.dim(`\u2192 ${pn(s.result)}`)}`,o+1))}}}r(_m,"formatToolCalls");function jm(e,t,n,o,i){let a=ye(e)?n.green("\u2713"):n.red("\u2717"),c=Nm(e.evalCase,n),l=o&&e.evalCase.source?`${e.evalCase.id} (${e.evalCase.source})`:e.evalCase.id;if(t(`${a} ${l}${c}`),e.invokeError){t(T(n.red("invoke: fail"))),t(T(e.invokeError.message,2)),e.invokeError instanceof m&&e.invokeError.hint&&t(T(n.yellow(`\u{1F4A1} ${e.invokeError.hint}`),2));return}e.scoreError&&(t(T(n.red("score: fail"))),t(T(e.scoreError.message,2)),e.scoreError instanceof m&&e.scoreError.hint&&t(T(n.yellow(`\u{1F4A1} ${e.scoreError.hint}`),2)));let p=e.run?.turns.length??0,d=[...new Set([...Array.from({length:p},(f,y)=>y),...e.scores.map(f=>f.turnIndex)])].sort((f,y)=>f-y),u=d.length>1;for(let f of d){let y=u?2:1;u&&t(T(n.dim(`turn ${f+1}`)));let g=e.run?.turns[f];g&&_m(g.toolCalls,t,n,y,i);for(let h of e.scores.filter(w=>w.turnIndex===f)){let w=h.passed?n.green("pass"):n.red("fail");t(T(`${h.scorerType}: ${w}`,y)),h.explanation&&t(T(n.dim(h.explanation),y+1))}}}r(jm,"formatCaseResult");async function Hm(e,t,n,o){if(n.upsert){await t.upsert(Me(e)),o.writeStdout(o.c.green(`Pushed agent "${e.externalId}" to project "${o.project}"`));return}try{let i=await t.getByExternalId(e.externalId),s=Ds(e,i);s.length>0&&o.writeStderr(o.c.yellow($s(s,{verbose:n.verbose})))}catch(i){if(i instanceof m&&i.message.includes("not found"))o.writeStderr(o.c.yellow(`Warning: agent "${e.externalId}" is not deployed in CDF. Run with --upsert to push local config before evaluating.`));else{let s=i instanceof Error?i.message:String(i);o.writeStderr(o.c.yellow(`Warning: failed to fetch deployed agent "${e.externalId}": ${s}`))}}}r(Hm,"ensureAgentConfigBeforeEval");async function la(e,t,n={}){let o=n.readAgentYaml??$e,i=n.loadEvalCases??bs,s=n.writeStdout??(E=>console.log(E)),a=n.writeStderr??(E=>console.error(E)),c=n.chalk??P(process.stdout),l=n.getAgentClient??z,p=n.getAgentsService??ee,d=n.getEvalService??ia,u=n.runEval??ra,f=n.writeEvalReport??Gs,y=sa(e??"."),{externalId:g,agentYaml:h}=await Ys(t,y,o);if(t.upsert&&h===void 0)throw new m(`--upsert requires a local ${v.configGlob} to push.`,{hint:`Remove --upsert, or add an agent definition (${v.configGlob}) to this directory.`,shouldReport:!1});let w=await i(y),S=As(w,{caseFilter:t.case,tagFilter:t.tag}),C=[...new Set(w.map(E=>E.source))],A=C.length>1,x=await l(t,y),M=p(x);h!==void 0&&await Hm(h,M,t,{project:x.project,writeStdout:s,writeStderr:a,c});let K=zs(),R=qs(K),Y=d(x,R,K?{chatBaseUrl:K}:{}),le=t.reportDir!==void 0&&t.reportDir.length>0?sa(t.reportDir):void 0,I=le!==void 0?Qs():void 0,oe=t.verbose?Xs(E=>a(E)):void 0,F=I&&oe?ea(oe,I.logger):I?.logger??oe,re=Vo({cliModelId:t.judgeModel,agentModelFallback:h?.model});A&&s(`Matched ${S.length} of ${w.length} case(s) across ${C.length} file(s)`);let V=Um(S);V!==void 0&&s(`Session context: ${V}`),s(`Judge model: ${c.cyan(re)}`),F?.log(`Agent: ${g}`);for(let E of S)F?.log(` ${E.id}: ${ca(E.contextInformation)}`);for(let E of C){let de=w.filter(zn=>zn.source===E).length;F?.log(` ${E} (${de} case(s))`)}F?.log(`Loaded ${S.length} case(s): ${S.map(E=>E.id).join(", ")}`),F?.log(`judge model: ${re} (source: ${t.judgeModel?"--judge-model flag":process.env.EVAL_JUDGE_MODEL?"EVAL_JUDGE_MODEL env":h?.model?`${v.configGlob} model fallback`:"default"})`),F?.log(`agent chat route: ${R}`),F?.log(`agent chat URL: ${Y.agentChatUrl}`),F?.log(`chat completions URL: ${Y.chatCompletionsUrl}`);let Gn=_s({cliModelId:t.judgeModel,agentModelFallback:h?.model,service:Y,verbose:F}),pe=await u({cases:S,service:Y,agentExternalId:g,judgeModel:Gn,verbose:F,tools:h?.tools,warn:r((E,de)=>{a(c.yellow(de?`${E}
|
|
147
|
-
hint: ${de}`:E))},"warn"),allowToolConfirmation:!t.failOnToolConfirmation,failFast:t.failFast});for(let E of pe.results)
|
|
148
|
-
${
|
|
143
|
+
${n.criteria}`,output:a.output},l)}if(n.type==="faithfulness"){let d=Tm({model:i});return vt(e.id,t,n,d,{input:c?`${c}Current question:
|
|
144
|
+
${a.input}`:a.input,output:a.output,context:n.groundTruth},l)}if(n.type==="toolSelection"||n.type==="toolInvocation"){let d=n.tools??e.tools??s?.tools??[];if(d.length===0){let f=s?.tools===void 0?`Add a tools field to the scorer, case, or eval.yaml root (${w.configGlob} is not used with --external-id/--system-agent).`:`Add a tools field to the scorer, case, or eval.yaml root, or declare tools in ${w.configGlob}.`,y=`Warning: Skipping ${n.type} scorer on case "${e.id}": no tools available.`;return l?.log(y),s?.warn?.(y,f),null}if(n.type==="toolSelection"){let f=Im({model:i});return vt(e.id,t,n,f,{input:c?`${c}Current question:
|
|
145
|
+
${a.input}`:a.input,availableTools:ia(d),toolSelection:Dm(a.toolCalls)},l)}let u=Rm({model:i});return vt(e.id,t,n,u,{input:c?`${c}Current question:
|
|
146
|
+
${a.input}`:a.input,availableTools:ia(d),toolSelection:$m(a.toolCalls)},l)}let p=n;throw new m(`Scorer type "${p.type}" is not supported yet.`,{hint:`The CLI eval schema currently supports only ${Om(vs)} scorers.`,shouldReport:!1})}r(Lm,"evaluateScorer");async function Mm(e,t,n,o,i){let s=e.turns[t]?.scorers??[];return(await Promise.all(s.map(c=>Lm(e,t,c,n,o,i)))).filter(c=>c!==null)}r(Mm,"scoreTurn");async function sa(e,t,n,o){return(await Promise.all(e.turns.map((s,a)=>Mm(e,a,t,n,o)))).flat()}r(sa,"scoreCase");function Um(e){return e.length>0&&e.every(t=>t.passed)}r(Um,"casePassed");function _m(e,t,n){if(n<=1)return e;let o=e instanceof Error?e.message:String(e);return new m(`turn ${t+1}/${n}: ${o}`,{hint:ue(e)?e.hint:void 0,helpUrl:ue(e)?e.helpUrl:void 0,shouldReport:ue(e)?e.shouldReport:void 0,cause:e})}r(_m,"annotateTurnFailure");async function Nm(e,t){let{service:n,agentExternalId:o,judgeModel:i,verbose:s}=t;s?.log(`--- case "${e.id}" (${e.source}) invoke ---`);let a;try{let c=[],l;for(let[p,d]of e.turns.entries()){s?.log(` turn ${p+1}/${e.turns.length}: "${d.input}"`);let u;try{u=await ea({service:n,agentExternalId:o,input:d.input,cursor:l,contextInformation:e.contextInformation,allowToolConfirmation:t.allowToolConfirmation,verbose:s})}catch(f){throw _m(f,p,e.turns.length)}l=u.cursor,c.push({input:d.input,output:u.output,toolCalls:u.toolCalls,apiRoundTrips:u.turns})}a={caseId:e.id,turns:c}}catch(c){return{evalCase:e,scores:[],passed:!1,invokeError:c instanceof Error?c:new Error(String(c))}}s?.log(`--- case "${e.id}" (${e.source}) score (Phoenix) ---`);try{let c=await sa(e,a,i,{verbose:s,tools:t.tools,warn:t.warn});return{evalCase:e,run:a,scores:c,passed:Um(c)}}catch(c){return{evalCase:e,run:a,scores:[],passed:!1,scoreError:c instanceof Error?c:new Error(String(c))}}}r(Nm,"runCase");async function aa(e){let{cases:t,verbose:n}=e,o=[];for(let s of t){let a=await Nm(s,e);if(o.push(a),e.failFast&&!ye(a)){n?.log(`--- fail-fast: stopping after failed case "${s.id}" (${s.source}) ---`);break}}let i=o.filter(s=>s.passed).length;return{totalCases:t.length,passedCases:i,failedCases:o.length-i,skippedCases:t.length-o.length,results:o}}r(aa,"runEval");var Zo={"cdf-version":"20230101-alpha"};function ca(e,t,n={}){let{chatBaseUrl:o}=n,i=Xs(e.project,t),s=Qs(e.project),a=o?gn(o,i):i,c=o?a:gn(e.getBaseUrl(),i),l=gn(e.getBaseUrl(),s);async function p(g){if(o)return d(g);try{return(await e.post(a,{data:g,headers:Zo})).data}catch(h){if(!ae(h))throw h;let v=t==="internal"&&h.status===404?" Try the public route: set AGENT_CHAT_ROUTE=public.":"";throw fn(h,"Agent chat",c,v||void 0)}}r(p,"postAgentChat");async function d(g){let h=await e.authenticate();if(!h)throw new m("Agent chat requires a CDF access token for local cog-ai.",{hint:"Run `cognite auth login` or pass --interactive with --base-url and --project.",shouldReport:!1});let v={...Zo,Authorization:`Bearer ${h}`};try{let S=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json",...v},body:JSON.stringify(g)});if(!S.ok)throw fn(jm(S.status,await S.text()),"Agent chat",c);return await S.json()}catch(S){throw S instanceof ie||S instanceof m?S:Hm(S,o)}}r(d,"postLoopbackAgentChat");async function u(g){try{return(await e.post(s,{data:g,headers:Zo})).data}catch(h){throw fn(h,"Chat completions",l)}}r(u,"postChatCompletions");async function f(){let g=`/api/v1/projects/${encodeURIComponent(e.project)}/sessions`;try{return await y({oneshotTokenExchange:!0},g)}catch(h){if(Km(h))return await y({tokenExchange:!0},g);throw h}}r(f,"createSessionNonce");async function y(g,h){try{let v=await e.sessions.create([g]),S=v?.[0]?.nonce;if(!S)throw new m("Session creation returned no nonce",{hint:"The Sessions API returned an empty items list. Retry, or check IdP configuration for this project.",cause:new Error(`Response items: ${JSON.stringify(v)}`)});return S}catch(v){throw v instanceof m?v:fn(v,"Session creation",h)}}return r(y,"requestSessionNonce"),{postAgentChat:p,postChatCompletions:u,createSessionNonce:f,agentChatUrl:c,chatCompletionsUrl:l}}r(ca,"getEvalService");function jm(e,t){let n;try{n=JSON.parse(t)}catch{n={error:{message:t}}}return Object.assign(new Error(t),{status:e,data:U(n)?n:void 0})}r(jm,"httpErrorFromFetchBody");function Hm(e,t){return e instanceof Error?!t||!Bm(e)?e:new m(`Agent chat failed: could not connect to ${t}`,{hint:`Is cog-ai running? Try GET ${t}/health`,cause:e,shouldReport:!1}):new Error(String(e))}r(Hm,"wrapConnectError");function Bm(e){let t=e,n=new Set;for(;t!=null&&!n.has(t)&&(n.add(t),typeof t=="object");){let o=t.code;if(o==="ECONNREFUSED"||o==="ENOTFOUND"||o==="ECONNRESET")return!0;t=t.cause}return!1}r(Bm,"isConnectError");function Km(e){let t=e instanceof ie?e.httpStatusCode:ae(e)?e.status:void 0;return t===400||t===401||t===403}r(Km,"isSessionTypeRejected");function fn(e,t,n,o){if(!ae(e))return e instanceof Error?e:new Error(String(e));let i=Gi(e),s=i?`: ${i}`:"",a=o??"";return new ie(`${t} failed (${e.status})${s}${a}`,{httpStatusCode:e.status,requestUrl:n,responseBody:ko(e),cause:e})}r(fn,"wrapCdfApiError");function da(e){if(!e)return"(none)";let t=[],n=e.dataModels?.length??0,o=e.instanceSpaces?.length??0;return(n>0||o>0)&&t.push(`${n} data model(s), ${o} space(s)`),e.appContext&&t.push("app context"),t.length>0?t.join(", "):"(none)"}r(da,"formatSessionContextSummary");function Gm(e){let t=e.filter(s=>s.contextInformation!==void 0);if(t.length===0)return;let n=t.map(s=>s.contextInformation),o=n[0];return t.length===e.length&&n.every(s=>Vm(s,o))?da(o):`varies by case (${t.length}/${e.length})`}r(Gm,"summarizeSessionContextForStdout");function pa(e,t){return t?[...t,e]:[e]}r(pa,"collectRepeatableValues");var Xo=Object.freeze({case:new we("--case <id>","Run only cases with this id (repeatable)").argParser(pa),tag:new we("--tag <tag>","Run only cases with this tag (repeatable)").argParser(pa),judgeModel:new we("--judge-model <model>","LLM model for scoring eval cases (e.g. azure/gpt-5)"),externalId:new we("--external-id <id>",`Agent external ID (alternative to reading from ${w.configGlob})`).conflicts("systemAgent"),systemAgent:new we("--system-agent","Evaluate the Cognite system agent (currently cdf_industrial_v4)").conflicts("externalId"),upsert:new we("--upsert",`Push the local ${w.configGlob} to CDF before running evals`).conflicts("externalId").conflicts("systemAgent"),failFast:new we("--fail-fast","Stop after the first failing case; skip the rest"),verbose:new we("-v, --verbose","Log request/response traces to stderr"),failOnToolConfirmation:new we("--fail-on-tool-confirmation","Fail a case instead of auto-approving when the agent requests tool confirmation"),reportDir:new we("--report-dir [path]",`Write structured eval reports (report.json + report.md); defaults to ${un} when the path is omitted`).preset(un)}),yx=Object.values(Xo).map(e=>e.long).filter(e=>e!=null);function Ym(e,t){return e.expectPass===!1?t.dim(" (expected fail)"):""}r(Ym,"formatExpectedFailSuffix");function zm(e,t,n,o,i){if(e.length!==0){t(T(n.dim("toolsCalled:"),o));for(let s of e){let a=et(s,Qe);!i||s.result===void 0||s.result===null?t(T(a,o+1)):t(T(`${a} ${n.dim(`\u2192 ${dn(s.result)}`)}`,o+1))}}}r(zm,"formatToolCalls");function qm(e,t,n,o,i){let a=ye(e)?n.green("\u2713"):n.red("\u2717"),c=Ym(e.evalCase,n),l=o&&e.evalCase.source?`${e.evalCase.id} (${e.evalCase.source})`:e.evalCase.id;if(t(`${a} ${l}${c}`),e.invokeError){t(T(n.red("invoke: fail"))),t(T(e.invokeError.message,2)),e.invokeError instanceof m&&e.invokeError.hint&&t(T(n.yellow(`\u{1F4A1} ${e.invokeError.hint}`),2));return}e.scoreError&&(t(T(n.red("score: fail"))),t(T(e.scoreError.message,2)),e.scoreError instanceof m&&e.scoreError.hint&&t(T(n.yellow(`\u{1F4A1} ${e.scoreError.hint}`),2)));let p=e.run?.turns.length??0,d=[...new Set([...Array.from({length:p},(f,y)=>y),...e.scores.map(f=>f.turnIndex)])].sort((f,y)=>f-y),u=d.length>1;for(let f of d){let y=u?2:1;u&&t(T(n.dim(`turn ${f+1}`)));let g=e.run?.turns[f];g&&zm(g.toolCalls,t,n,y,i);for(let h of e.scores.filter(v=>v.turnIndex===f)){let v=h.passed?n.green("pass"):n.red("fail");t(T(`${h.scorerType}: ${v}`,y)),h.explanation&&t(T(n.dim(h.explanation),y+1))}}}r(qm,"formatCaseResult");async function Jm(e,t,n,o){if(n.upsert){await t.upsert(Ue(e)),o.writeStdout(o.c.green(`Pushed agent "${e.externalId}" to project "${o.project}"`));return}try{let i=await t.getByExternalId(e.externalId),s=Fs(e,i);s.length>0&&o.writeStderr(o.c.yellow(Ls(s,{verbose:n.verbose})))}catch(i){if(i instanceof m&&i.message.includes("not found"))o.writeStderr(o.c.yellow(`Warning: agent "${e.externalId}" is not deployed in CDF. Run with --upsert to push local config before evaluating.`));else{let s=i instanceof Error?i.message:String(i);o.writeStderr(o.c.yellow(`Warning: failed to fetch deployed agent "${e.externalId}": ${s}`))}}}r(Jm,"ensureAgentConfigBeforeEval");async function ua(e,t,n={}){let o=n.readAgentYaml??Oe,i=n.loadEvalCases??Ps,s=n.writeStdout??(E=>console.log(E)),a=n.writeStderr??(E=>console.error(E)),c=n.chalk??P(process.stdout),l=n.getAgentClient??z,p=n.getAgentsService??ee,d=n.getEvalService??ca,u=n.runEval??aa,f=n.writeEvalReport??qs,y=la(e??"."),{externalId:g,agentYaml:h}=await Js(t,y,o);if(t.upsert&&h===void 0)throw new m(`--upsert requires a local ${w.configGlob} to push.`,{hint:`Remove --upsert, or add an agent definition (${w.configGlob}) to this directory.`,shouldReport:!1});let v=await i(y),S=xs(v,{caseFilter:t.case,tagFilter:t.tag}),C=[...new Set(v.map(E=>E.source))],A=C.length>1,x=await l(t,y),M=p(x);h!==void 0&&await Jm(h,M,t,{project:x.project,writeStdout:s,writeStderr:a,c});let K=Ws(),R=Zs(K),Y=d(x,R,K?{chatBaseUrl:K}:{}),le=t.reportDir!==void 0&&t.reportDir.length>0?la(t.reportDir):void 0,I=le!==void 0?na():void 0,oe=t.verbose?ta(E=>a(E)):void 0,F=I&&oe?oa(oe,I.logger):I?.logger??oe,re=Go({cliModelId:t.judgeModel,agentModelFallback:h?.model});A&&s(`Matched ${S.length} of ${v.length} case(s) across ${C.length} file(s)`);let V=Gm(S);V!==void 0&&s(`Session context: ${V}`),s(`Judge model: ${c.cyan(re)}`),F?.log(`Agent: ${g}`);for(let E of S)F?.log(` ${E.id}: ${da(E.contextInformation)}`);for(let E of C){let de=v.filter(qn=>qn.source===E).length;F?.log(` ${E} (${de} case(s))`)}F?.log(`Loaded ${S.length} case(s): ${S.map(E=>E.id).join(", ")}`),F?.log(`judge model: ${re} (source: ${t.judgeModel?"--judge-model flag":process.env.EVAL_JUDGE_MODEL?"EVAL_JUDGE_MODEL env":h?.model?`${w.configGlob} model fallback`:"default"})`),F?.log(`agent chat route: ${R}`),F?.log(`agent chat URL: ${Y.agentChatUrl}`),F?.log(`chat completions URL: ${Y.chatCompletionsUrl}`);let Yn=Bs({cliModelId:t.judgeModel,agentModelFallback:h?.model,service:Y,verbose:F}),pe=await u({cases:S,service:Y,agentExternalId:g,judgeModel:Yn,verbose:F,tools:h?.tools,warn:r((E,de)=>{a(c.yellow(de?`${E}
|
|
147
|
+
hint: ${de}`:E))},"warn"),allowToolConfirmation:!t.failOnToolConfirmation,failFast:t.failFast});for(let E of pe.results)qm(E,s,c,A,t.verbose??!1),E.evalCase.expectPass===!1&&!E.invokeError&&!E.scoreError&&E.passed&&a(c.yellow(`Warning: case "${E.evalCase.id}" expected scorers to fail but they passed.`));let zn=Uo(pe.results),Br=ft(pe.results),Kr=`${Br}/${pe.results.length} cases met expectations`,Il=zn?c.bold(c.red(Kr)):c.bold(c.green(Kr));if(s(`
|
|
148
|
+
${Il}`),pe.skippedCases>0&&s(c.yellow(`Stopped early (--fail-fast): ${pe.skippedCases} case(s) not run.`)),le!==void 0&&I!==void 0)try{let{jsonPath:E,mdPath:de}=await f({reportDir:le,summary:pe,traces:I.events,meta:{agentExternalId:g,judgeModelId:re,route:R}});s(`Wrote eval report: ${E}`),s(`Wrote eval report: ${de}`)}catch(E){let de=E instanceof Error?E.message:String(E);a(c.yellow(`Warning: failed to write eval report: ${de}`))}zn&&(process.exitCode=1);let Dl=Array.from(new Set(S.flatMap(E=>E.turns.flatMap(de=>de.scorers?.map(qn=>qn.type)??[])))),Vr=ro();await Ms(n.telemetry,{caseCount:pe.totalCases,passCount:Br,failCount:gt(pe.results),unexpectedPassCount:ht(pe.results),scorersUsed:Dl,success:!zn,...Vr!==void 0&&{actionDurationMs:Vr}})}r(ua,"handleAgentsEval");import{Option as Qm}from"commander";function hn(e,t){return e.map((n,o)=>Math.max(n.length,...t.map(i=>i[o].length)))}r(hn,"computeColumnWidths");function wt(e,t,n=e){return e.map((o,i)=>n[i]+" ".repeat(Math.max(0,t[i]-o.length))).join(" ").trimEnd()}r(wt,"formatTableRow");import{writeFile as ma}from"fs/promises";import{resolve as Zm}from"path";import{resolve as Wm}from"path";async function Ce(e,t,n={}){let o=n.readAgentYaml??Oe,i=n.getAgentClient??z,s=n.getAgentsService??ee,a=Wm(e??"."),c=await o(a),l=await i(t,a);await s(l).upsert(Ue(c));let d=P(process.stdout);return console.log(d.green(`Pushed agent "${c.externalId}" to project "${l.project}"`)),{client:l,agentYaml:c}}r(Ce,"handleAgentsPush");var Te="published",Qo=class Qo extends be{constructor(){super("publish");this.handle=r(async(n,o,i)=>{let s=i.optsWithGlobals(),a=Zm(n??"."),{path:c,agent:l}=await ct(a),p=l.labels??[];if(p.includes(Te))await Ce(n,s);else{let u={...l,labels:[...p,Te]};await ma(c,ge(u));try{await Ce(n,s)}catch(f){throw await ma(c,ge(l)),f}}let d=P(process.stdout);console.log(d.green(`Published agent "${l.externalId}"`))},"handle");this.description("Promote a draft agent to production").argument("[dir]","Agent project directory").addHelpText("after",Xm),this.action(this.handle)}};r(Qo,"PublishCommand");var yn=Qo,Xm=`
|
|
149
149
|
Examples:
|
|
150
150
|
cognite agents publish Publish agent in current directory
|
|
151
151
|
cognite agents publish ./my-agent Publish agent in my-agent directory
|
|
152
|
-
`;var
|
|
153
|
-
${e}`),!1}}r(
|
|
154
|
-
${e}`)}}r(
|
|
155
|
-
${p}`,{hint:"Use --force to overwrite the existing file.",shouldReport:!1});await
|
|
152
|
+
`;var ga=Object.freeze({json:new Qm("--json","Output as JSON")});async function fa(e,t={}){let n=t.getAgentClient??z,o=t.getAgentsService??ee,i=await n(e,process.cwd()),c=(await o(i).list()).items;if(e.json){console.log(JSON.stringify(c,null,2));return}if(c.length===0){console.log(`No agents found in project "${i.project}".`);return}let l=P(process.stdout),p=c.map(S=>({externalId:S.externalId,name:S.name,status:S.labels?.includes(Te)?"published":"draft",model:S.model,updated:er(S.lastUpdatedTime)})),d=["externalId","name","status","model","updated"],u=["External ID","Name","Status","Model","Updated"],f=p.map(S=>d.map(C=>S[C])),y=hn(u,f);console.log(),console.log(l.bold(wt(u,y))),console.log(l.dim(y.map(S=>"\u2500".repeat(S)).join(" ")));for(let S of p){let C=S.status==="published"?l.green(S.status):l.yellow(S.status),A=d.map(M=>S[M]),x=d.map(M=>M==="status"?C:S[M]);console.log(wt(A,y,x))}console.log();let g=p.filter(S=>S.status==="published").length,h=p.length-g,v=[`${p.length} agent${p.length===1?"":"s"}`];g>0&&v.push(`${g} published`),h>0&&v.push(`${h} draft`),console.log(v.join(", "))}r(fa,"handleAgentsList");function er(e,t=Date.now()){let n=t-e;if(n<0)return"just now";let o=Math.floor(n/1e3);if(o<60)return"just now";let i=Math.floor(o/60);if(i<60)return`${i}m ago`;let s=Math.floor(i/60);return s<24?`${s}h ago`:`${Math.floor(s/24)}d ago`}r(er,"formatRelativeTime");import{resolve as ng}from"path";import{Option as og}from"commander";function ha(e,t){let{org:n,project:o,baseUrl:i}=e,s;try{s=new URL(i).hostname}catch{return null}let{externalId:a,versionTag:c}=t,l=new URLSearchParams({cluster:s,customAppVersion:c,workspace:"industrial-tools"});return`https://${n}.fusion.cognite.com/${o}/flows-apps/app/${encodeURIComponent(a)}?${l}`}r(ha,"generateFusionUrl");function ya(e){let{org:t,project:n,cluster:o,agentExternalId:i}=e,s=new URLSearchParams({cluster:o,atlasOverride:i});return`https://${t}.fusion.cognite.com/${n}?${s}`}r(ya,"generateAtlasAgentUrl");import{execFileSync as Sa}from"child_process";import{platform as eg}from"os";import tg from"path";function X(e,t={}){let{platform:n=eg}=t;switch(n()){case"darwin":return e==="macos";case"win32":return e==="windows";default:return e==="other"}}r(X,"isOS");function Sn(e,t={}){let{exec:n=Sa,log:o=console.log}=t,[i,s]=X("macos",t)?["open",[e]]:X("windows",t)?["rundll32",["url.dll,FileProtocolHandler",e]]:["xdg-open",[e]];try{return n(i,s),!0}catch{return o(`Could not open browser \u2014 open manually:
|
|
153
|
+
${e}`),!1}}r(Sn,"openInBrowser");function va(e,t={}){let{exec:n=Sa,log:o=console.log}=t,[i,s]=X("macos",t)?["open",["-R",e]]:X("windows",t)?["explorer",[`/select,${e}`]]:["xdg-open",[tg.dirname(e)]];try{n(i,s)}catch{o(`Could not open file manager \u2014 files are at:
|
|
154
|
+
${e}`)}}r(va,"revealInFileManager");var tr=Object.freeze({upsert:new og("--upsert","Push the agent to CDF before opening (upsert draft)").default(!1)}),ck=Object.values(tr).map(e=>e.long).filter(e=>e!=null);function rg(e){try{return new URL(e.getBaseUrl()).hostname}catch{throw new m("Could not determine cluster from client base URL.",{hint:"Check your --base-url or session project configuration.",shouldReport:!1})}}r(rg,"clusterFromBaseUrl");async function wa(e,t,n={}){let o=n.handleAgentsPush??Ce,i=n.readAgentYaml??Oe,s=n.getAgentClient??z,a=n.resolveOrg??us,c=n.openInBrowser??Sn,l=ng(e??"."),{client:p,agentYaml:d}=t.upsert?await o(e,t):{agentYaml:await i(l),client:await s(t,l)},u=a(t,l),f=p.project,y=rg(p),g=ya({org:u,project:f,cluster:y,agentExternalId:d.externalId}),h=P(process.stdout);console.log(h.cyan(`Opening ${g}`)),c(g)}r(wa,"handleAgentsOpen");import{mkdir as ig,writeFile as sg}from"fs/promises";import{basename as ag,join as cg,resolve as lg}from"path";import{Option as pg}from"commander";async function Ca(e,t,n,o={getAgentClient:{}}){let i=await z(n,process.cwd(),o.getAgentClient),s=await ee(i).getByExternalId(e),a=lg(t??"."),c=$e(ag(a)),l=(await at(a)).find(u=>u.toLowerCase()===c.toLowerCase()),p=cg(a,l??c);if(l!==void 0&&!n.force)throw new m(`${l} already exists at:
|
|
155
|
+
${p}`,{hint:"Use --force to overwrite the existing file.",shouldReport:!1});await ig(a,{recursive:!0}),await sg(p,ge(s));let d=P(process.stdout);console.log(d.green(`Pulled agent "${s.name}" (${e}) to ${p}`))}r(Ca,"handleAgentsPull");var Ct=Object.freeze({externalId:{name:"external-id",description:"externalId of the agent to pull"},dir:{name:"dir",description:"Agent project directory"}}),nr=Object.freeze({force:new pg("--force","Overwrite the existing agent definition without prompting")}),wk=Object.values(nr).map(e=>e.long).filter(e=>e!=null);import{resolve as dg}from"path";import{Option as Aa}from"commander";var Ea=Object.freeze({externalId:new Aa("--external-id <id>",`Agent external ID (alternative to reading from ${w.configGlob})`),json:new Aa("--json","Output as JSON")});function ug(e){return e.labels?.includes(Te)?"published":"draft"}r(ug,"describeAgentStatus");function mg(e,t=Date.now()){return e==null||isNaN(e)?"unknown":`${new Date(e).toISOString()} (${er(e,t)})`}r(mg,"formatUpdatedAt");function gg(e){let t=e.tools??[];if(t.length===0)return["Tools: none"];let n=[`Tools (${t.length}):`];for(let o of t)n.push(T(`- ${o.type}: ${o.description}`));return n}r(gg,"formatTools");function fg(e){let t=e.skills??[];if(t.length===0)return["Skills: none"];let n=[`Skills (${t.length}):`];for(let o of t)n.push(T(`- ${o}`));return n}r(fg,"formatSkills");function hg(e){let t=e.subagents??[];if(t.length===0)return["Sub-agents: none"];let n=[`Sub-agents (${t.length}):`];for(let o of t)n.push(T(`- ${o.agentExternalId}`));return n}r(hg,"formatSubagents");function yg(e,t,n=Date.now()){let o=ug(e);return["",`Agent: ${t.bold(e.name)} (${t.dim(e.externalId)})`,`Status: ${o==="published"?t.green(o):t.yellow(o)}`,`Model: ${e.model}`,`Updated: ${t.dim(mg(e.lastUpdatedTime,n))}`,"",...gg(e),"",...fg(e),"",...hg(e),...o==="draft"?["","Run `npx @cognite/cli agents publish .` to publish this agent."]:[]]}r(yg,"renderAgentStatus");async function ba(e,t,n={}){let o=n.readAgentYaml??Oe,i=n.getAgentClient??z,s=n.getAgentsService??ee,a=dg(e??"."),c;if(t.externalId!==void 0){let f=t.externalId.trim();if(!f)throw new m("--external-id cannot be empty.",{hint:`Provide a valid agent external ID, or omit the flag to read from ${w.configGlob}.`,shouldReport:!1});c=f}else c=(await o(a)).externalId;let l=await i(t,a),d=await s(l).getByExternalId(c);if(t.json){console.log(JSON.stringify(d,null,2));return}let u=yg(d,P(process.stdout));for(let f of u)console.log(f)}r(ba,"handleAgentsStatus");import{writeFile as xa}from"fs/promises";import{resolve as Sg}from"path";var or=class or extends be{constructor(){super("unpublish");this.handle=r(async(n,o,i)=>{let s=i.optsWithGlobals(),a=Sg(n??"."),{path:c,agent:l}=await ct(a),p=l.labels??[];if(p.includes(Te)){let u={...l,labels:p.filter(f=>f!==Te)};await xa(c,ge(u));try{await Ce(n,s)}catch(f){throw await xa(c,ge(l)),f}}else await Ce(n,s);let d=P(process.stdout);console.log(d.green(`Unpublished agent "${l.externalId}"`))},"handle");this.description("Retract a published agent back to draft").argument("[dir]","Agent project directory").addHelpText("after",vg),this.action(this.handle)}};r(or,"UnpublishCommand");var vn=or,vg=`
|
|
156
156
|
Examples:
|
|
157
157
|
cognite agents unpublish Unpublish agent in current directory
|
|
158
158
|
cognite agents unpublish ./my-agent Unpublish agent in my-agent directory
|
|
159
|
-
`;var
|
|
160
|
-
`,"passphraseMismatchMsg"),Oa=`Passphrase confirmation failed after ${An} attempts`,Fa=r(e=>`A signing key with kid "${e}" already exists. Overwrite it?`,"confirmOverwriteMsg"),La="How would you like to submit your key registration?",Ma="Open in browser",Ua="Copy link to clipboard";async function sr(e){return ir.prompt(e)}r(sr,"defaultPrompt");function Na(e){return t=>{try{return e(t),!0}catch(n){return n instanceof Error?n.message:"Invalid"}}}r(Na,"parserAsValidator");var Sg=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/;function Ve(e){let t=e.trim();if(!t)throw new Error("--kid must not be empty");if(t.length>64)throw new Error("--kid must be 64 characters or fewer");if(!Sg.test(t))throw new Error("--kid must contain only lowercase letters, digits, and hyphens, and must not start or end with a hyphen (e.g. jsmith-dev-001)");return t}r(Ve,"parseKid");async function _a(e={}){let{prompt:t=sr}=e,{kid:n}=await t({type:"input",name:"kid",message:Pa,validate:Na(Ve)});return Ve(n)}r(_a,"promptKid");async function ja(e={}){let{prompt:t=r(o=>ir.prompt(o),"prompt")}=e,{action:n}=await t({type:"select",name:"action",message:La,choices:[{name:"browser",message:Ma},{name:"clipboard",message:Ua}]});if(n!=="browser"&&n!=="clipboard")throw new Error(`Unexpected Zendesk action: ${n}`);return n}r(ja,"promptZendeskAction");async function Ha(e={}){let{prompt:t=sr,gitUserEmail:n=ka}=e,{email:o}=await t({type:"input",name:"email",message:Ta,initial:n(),validate:Na(i=>et(i,"email"))});return et(o,"email")}r(Ha,"promptEmail");async function Ba(e={}){let{prompt:t=sr,stderr:n=process.stderr}=e;for(let o=1;o<=An;o+=1){let{passphrase:i}=await t({type:"password",name:"passphrase",message:Ra,validate:r(a=>a.length>=15?!0:Da(),"validate")}),{confirm:s}=await t({type:"password",name:"confirm",message:Ia});if(i===s)return b.from(i);n.write($a(o))}throw new Error(Oa)}r(Ba,"promptPassphrase");async function Ka(e,t={}){let{prompt:n=r(i=>ir.prompt(i),"prompt")}=t,{confirmed:o}=await n({type:"confirm",name:"confirmed",message:Fa(e),initial:!1});return o}r(Ka,"promptConfirmOverwrite");import{existsSync as Tg,readdirSync as Rg,readFileSync as Ig}from"fs";import{join as cr}from"path";import{execFile as wg}from"child_process";import{promisify as vg}from"util";var Va="cognite-flows",Cg=vg(wg),Ga=r((e,t)=>Cg(e,t),"defaultExecFile"),Ag=-25300,Eg=Ag&255;function bg(e){if(!(e instanceof Error)||!("code"in e)||e.code!==Eg)return!1;let t="stderr"in e?String(e.stderr):"";return/could not be found/i.test(t)||t===""}r(bg,"isKeychainNotFoundError");async function Ya(e,t,n={}){let o=t.expose();if(!X("macos",n))throw new Error("Keychain storage is only supported on macOS");let{execFile:i=Ga}=n;await i("security",["add-generic-password","-a",e,"-s",Va,"-w",Buffer.from(o,"utf-8").toString("base64"),"-U"])}r(Ya,"storeKeyInKeychain");async function En(e,t={}){if(!X("macos",t))return null;let{execFile:n=Ga}=t;try{let{stdout:o}=await n("security",["find-generic-password","-a",e,"-s",Va,"-w"]);return b.from(Buffer.from(o.trim(),"base64").toString("utf-8"))}catch(o){if(bg(o))return null;throw o}}r(En,"readKeyFromKeychain");var qa="cognite-cli-signing",xg="The native @napi-rs/keyring binary failed to load for this platform. Reinstall the CLI, or regenerate the key with `--output <path>` to use passphrase-encrypted file storage instead.",kg="Multiple Windows Credential Manager entries match this kid. Open Credential Manager (Control Panel \u2192 User Accounts \u2192 Credential Manager \u2192 Windows Credentials) and remove the duplicates.",za="Windows Credential Manager failed unexpectedly. Regenerate the key with `--output <path>` to fall back to passphrase-encrypted file storage.";function Pg(e){if(!(e instanceof Error))return za;let t=e.message.toLowerCase();return t.includes("cannot find module")||t.includes("module_not_found")||t.includes("failed to load native binding")?xg:t.includes("ambiguous")?kg:za}r(Pg,"hintFor");function Ja(e,t,n){return new m(`Failed to ${e} signing key for kid "${t}" in Windows Credential Manager`,{cause:n,hint:Pg(n),shouldReport:!1})}r(Ja,"wrapKeyringError");async function Wa(e,t){let{Entry:n}=await import("@napi-rs/keyring"),o=new n(e,t);return{setPassword:r(i=>o.setPassword(i),"setPassword"),getPassword:r(()=>o.getPassword(),"getPassword"),deleteCredential:r(()=>o.deleteCredential(),"deleteCredential")}}r(Wa,"defaultCreateEntry");async function Za(e,t,n={}){let{createEntry:o=Wa}=n,i=Buffer.from(t.expose(),"utf-8").toString("base64");try{(await o(qa,e)).setPassword(i)}catch(s){throw Ja("store",e,s)}}r(Za,"storeSigningKey");async function bn(e,t={}){let{createEntry:n=Wa}=t;try{let i=(await n(qa,e)).getPassword();return i===null?null:b.from(Buffer.from(i,"base64").toString("utf-8"))}catch(o){throw Ja("read",e,o)}}r(bn,"readSigningKey");var Fe=".pub.pem",lr=".key.jwe",pr=".meta.json";function xn(e){switch(e.kind){case"keychain":return"OS credential store";case"encrypted-file":return e.path;case"public-only":return"public-only (private key missing)"}}r(xn,"formatLocalKeySource");function Dg(e){return{existsSync:e.existsSync??Tg,readdirSync:e.readdirSync??Rg,readFileSync:e.readFileSync??((t,n)=>Ig(t,n)),isOS:e.isOS??(t=>X(t)),readKeyFromKeychain:e.readKeyFromKeychain??(t=>En(t)),readSigningKey:e.readSigningKey??(t=>bn(t))}}r(Dg,"resolveDeps");function $g(e){try{let t=JSON.parse(e);if(typeof t=="object"&&t!==null&&!Array.isArray(t)&&"email"in t&&typeof t.email=="string")return t.email}catch{}}r($g,"readEmailFromMeta");function Og(e,t){return t.existsSync(e)?t.readdirSync(e).filter(n=>n.endsWith(Fe)):[]}r(Og,"publicKeyEntries");function Fg(e){return e.slice(0,-Fe.length)}r(Fg,"kidFromPublicKeyFilename");async function Lg(e,t,n){if(n.isOS("macos")&&await n.readKeyFromKeychain(e).catch(()=>null)!==null)return{kind:"keychain"};if(n.isOS("windows")&&await n.readSigningKey(e).catch(()=>null)!==null)return{kind:"keychain"};let o=cr(t,`${e}${lr}`);return n.existsSync(o)?{kind:"encrypted-file",path:o}:{kind:"public-only"}}r(Lg,"resolveSource");async function kn(e=D().keysDir,t={}){let n=Dg(t),o=new Set,i=Og(e,n).flatMap(s=>{let a=Fg(s);return!a||o.has(a)?[]:(o.add(a),[{kid:a,entry:s}])});return Promise.all(i.map(async({kid:s,entry:a})=>{let c=await Lg(s,e,n),l=cr(e,`${s}${pr}`),p;try{p=$g(n.readFileSync(l,"utf8"))}catch{}return{kid:s,source:c,publicKeyPath:cr(e,a),email:p}}))}r(kn,"discoverLocalKeys");import{createReadStream as Mg}from"fs";function Pn(e){let t=Mg(e);return new ReadableStream({start(n){t.on("data",o=>{let i=typeof o=="string"?Buffer.from(o):o;n.enqueue(new Uint8Array(i))}),t.on("end",()=>n.close()),t.on("error",o=>n.error(o))},cancel(){t.destroy()}})}r(Pn,"createWebStreamFromFile");import Ug from"path";var Tn=".cognite-bundles";function Xa(e,t){return`${e}-${t}.zip`}r(Xa,"bundleFileName");function ne(e,t,n){return Ug.join(e,Tn,Xa(t,n))}r(ne,"bundlePath");var Qa=[".dev.sig",".cert.sig",".sig"];function Kg(e){return{existsSync:e.existsSync??Ng,readFileSync:e.readFileSync??((t,n)=>_g(t,n)),createBundleStream:e.createBundleStream??Pn,verifyBundle:e.verifyBundle??Hg,loadAppConfig:e.loadAppConfig??k,defaultKeyDir:e.defaultKeyDir??(()=>D().keysDir)}}r(Kg,"resolveDeps");function Vg(e,t){return Qa.map(n=>`${e}${n}`).find(n=>t(n))}r(Vg,"findSiblingSignature");function Gg(e){let t=e.split(".");return t.length===3&&t.every(n=>n.length>0)}r(Gg,"isCompactJws");function Yg(e){try{let t=Bg(e);return typeof t.kid=="string"?t.kid:void 0}catch{return}}r(Yg,"readKidFromToken");function zg(e,t,n){let{existsSync:o,readFileSync:i}=n;try{Ve(e)}catch(a){throw new m(a instanceof Error?a.message:String(a),{shouldReport:!1})}if(!o(t))throw new m(`Key directory not found: ${t}`,{shouldReport:!1});let s=jg(t,`${e}${Fe}`);if(!o(s))throw new m(`No public key found for kid "${e}" in ${t}`,{shouldReport:!1});try{return i(s,"utf-8")}catch(a){throw new m(`Failed to read public key file: ${s}`,{cause:a,shouldReport:!1})}}r(zg,"resolvePublicKeyForKid");function qg(e,t){let{payload:n,kid:o}=e;if(console.log(`Verified ${n.appId}@${n.version}`),console.log(` kid: ${o}`),console.log(` hash: ${n.bundleSha256}`),n.scopes&&n.scopes.length>0){let i=n.scopes.map(s=>`${s.org}/${s.project}`).join(", ");console.log(` scopes: ${i}`)}t&&console.log(JSON.stringify(n,null,2))}r(qg,"printResult");async function ec(e,t,n={},o=process.cwd()){let{existsSync:i,readFileSync:s,loadAppConfig:a,createBundleStream:c,verifyBundle:l,defaultKeyDir:p}=Kg(n),d;if(e)d=Rn(o,e);else{let g;try{g=a(o)}catch(h){let w=h instanceof Error?h.message:String(h);throw new m(w,{cause:h,hint:"Run this command from a Cognite app directory (one with app.json), or pass [bundle] explicitly.",shouldReport:!1})}d=ne(o,g.externalId,g.versionTag)}if(!i(d)){let g=e?void 0:"Default derived from app.json \u2014 pass [bundle] explicitly to override.";throw new m(`Bundle not found: ${d}`,{hint:g,shouldReport:!1})}let u=t.sig?Rn(o,t.sig):Vg(d,i);if(!u)throw new m("No signature file found.",{hint:`Pass --sig <path> or place one of ${Qa.map(g=>`${d}${g}`).join(", ")} next to the bundle.`,shouldReport:!1});if(!i(u))throw new m(`Signature file not found: ${u}`,{shouldReport:!1});let f;try{f=s(u,"utf-8").trim()}catch(g){throw new m(`Failed to read signature file: ${u}`,{cause:g,shouldReport:!1})}if(!Gg(f))throw new m(`Malformed JWS in ${u}`,{hint:"Expected a compact JWS (header.payload.signature \u2014 three base64url segments).",shouldReport:!1});let y;if(t.key){let g=Rn(o,t.key);if(!i(g))throw new m(`Public key not found: ${g}`,{shouldReport:!1});try{y=s(g,"utf-8")}catch(h){throw new m(`Failed to read public key file: ${g}`,{cause:h,shouldReport:!1})}}else{let g=t.keyDir?Rn(o,t.keyDir):p(),h=Yg(f);if(!h)throw new m("Token header has no kid.",{hint:"Pass --key <path> to a public key PEM.",shouldReport:!1});y=zg(h,g,{existsSync:i,readFileSync:s})}try{let g=await l({token:f,publicKeyPem:y,bundleStream:c(d)});qg(g,t.verbose??!1)}catch(g){let h=g instanceof Error?g.message:String(g);throw new m(`Bundle rejected: ${h}`,{shouldReport:!1})}}r(ec,"handleVerify");function tc(e,t={}){return e.command("verify [bundle]").description("Verify a signed app bundle locally (default: derived from app.json)").option("-s, --sig <path>","Path to the signature file (default: sibling .dev.sig / .cert.sig / .sig)").option("--key <path>","Path to a public key PEM file").option("--key-dir <path>","Directory of <kid>.pub.pem files \u2014 kid is read from the token header (default: $COGNITE_CLI_HOME/keys)").option("-v, --verbose","Print the full decoded payload after verification").addHelpText("after",`
|
|
159
|
+
`;var ir=class ir extends It{constructor(t,n){super(t),this.telemetry=n}configure(){this.description("Manage Atlas agents \u2014 create, iterate, and publish agents to Cognite Data Fusion"),this.hook("postAction",(t,n)=>ii(this.telemetry,n)),this.create(),this.push(),this.open(),this.publish(),this.unpublish(),this.pull(),this.list(),this.status(),this.eval()}create(){let t=new an;return this.addCommand(t),t}push(){return this.command("push").description("Push a draft agent to CDF for interactive testing").argument("[dir]","Agent project directory").action(async(t,n,o)=>{await Ce(t,o.optsWithGlobals())})}open(){let t=this.command("open").description("Open the agent in Fusion for interactive testing").argument("[dir]","Agent project directory");for(let n of Object.values(tr))t.addOption(n);return t.action((n,o,i)=>wa(n,i.optsWithGlobals()))}publish(){let t=new yn;return this.addCommand(t),t}unpublish(){let t=new vn;return this.addCommand(t),t}pull(){let t=this.command("pull").description("Pull an existing agent from CDF into the local project").argument(`<${Ct.externalId.name}>`,Ct.externalId.description).argument(`[${Ct.dir.name}]`,Ct.dir.description);for(let n of Object.values(nr))t.addOption(n);return t.action((n,o,i,s)=>Ca(n,o,s.optsWithGlobals()))}list(){let t=this.command("list").description("List agents in the CDF project");for(let n of Object.values(ga))t.addOption(n);return t.action((n,o)=>fa(o.optsWithGlobals()))}status(){let t=this.command("status").description("Show the current status of the agent in CDF").argument("[dir]","Agent project directory");for(let n of Object.values(Ea))t.addOption(n);return t.action(async(n,o,i)=>ba(n,i.optsWithGlobals()))}eval(){let t=this.command("eval").description("Run eval cases for an agent").argument("[dir]","Agent directory");for(let n of Object.values(Xo))t.addOption(n);return t.action((n,o,i)=>ua(n,i.optsWithGlobals(),{telemetry:this.telemetry}))}};r(ir,"AgentsCommand");var rr=ir;function ka(e,t={}){let n=new rr("agents",t.telemetry);return e.addCommand(n),n}r(ka,"registerAgentsCommand");import{existsSync as Yg,readFileSync as zg}from"fs";import{join as qg,resolve as In}from"path";import{verifyBundle as Jg}from"@cognite/app-sdk/codesigning";import{decodeProtectedHeader as Wg}from"jose";import sr from"enquirer";import{email as wg,pipe as Cg,safeParse as Ag,string as Eg}from"valibot";var bg=Cg(Eg(),wg());function tt(e,t="email"){let n=e.trim();if(!n)throw new Error(`${t} is required`);if(!Ag(bg,n).success)throw new Error(`${t} must look like an email (user@example.com); got "${e}"`);return n}r(tt,"parseEmail");import{execFileSync as Cn}from"child_process";import{execFileSync as xg}from"child_process";function wn(e={}){let{execFileSync:t=xg}=e;try{return t("git",["--version"],{stdio:"ignore"}),!0}catch{return!1}}r(wn,"isGitInstalled");function Ae(e={}){if(!wn(e))throw new m("Git is not installed or not found on PATH.",{hint:"Install Git (https://git-scm.com) and ensure it is on your PATH, then try again.",shouldReport:!1})}r(Ae,"throwIfGitMissing");function An(e,t={}){let{execFileSync:n=Cn}=t;try{return n("git",["-C",e,"status"],{stdio:"ignore"}),!0}catch{return!1}}r(An,"isInsideGitRepo");function Pa(e,t={}){let{execFileSync:n=Cn}=t;n("git",["-C",e,"init"],{stdio:"pipe"}),n("git",["-C",e,"add","."],{stdio:"pipe"}),n("git",["-C",e,"commit","-m","Initial commit","--no-gpg-sign","--no-verify"],{stdio:"pipe"})}r(Pa,"gitInitAndCommit");function Ta(e={}){let{execFileSync:t=Cn}=e;try{return String(t("git",["config","--get","user.name"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]})).trim()||void 0}catch{return}}r(Ta,"gitUserName");function Ra(e={}){let{execFileSync:t=Cn}=e;try{return String(t("git",["config","--get","user.email"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]})).trim()||void 0}catch{return}}r(Ra,"gitUserEmail");var En=3,Ia="Signing identity (kid) \u2014 e.g. jsmith-dev-001 (lowercase letters, digits, hyphens)",Da="Email address for the registry entry",$a=`Passphrase for the encrypted private key (min ${15} chars)`,Oa="Confirm passphrase",Fa=r(()=>`Passphrase must be at least ${15} characters`,"passphraseTooShortMsg"),La=r(e=>`Passphrases do not match (attempt ${e}/${En}).
|
|
160
|
+
`,"passphraseMismatchMsg"),Ma=`Passphrase confirmation failed after ${En} attempts`,Ua=r(e=>`A signing key with kid "${e}" already exists. Overwrite it?`,"confirmOverwriteMsg"),_a="How would you like to submit your key registration?",Na="Open in browser",ja="Copy link to clipboard";async function ar(e){return sr.prompt(e)}r(ar,"defaultPrompt");function Ha(e){return t=>{try{return e(t),!0}catch(n){return n instanceof Error?n.message:"Invalid"}}}r(Ha,"parserAsValidator");var kg=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/;function Ge(e){let t=e.trim();if(!t)throw new Error("--kid must not be empty");if(t.length>64)throw new Error("--kid must be 64 characters or fewer");if(!kg.test(t))throw new Error("--kid must contain only lowercase letters, digits, and hyphens, and must not start or end with a hyphen (e.g. jsmith-dev-001)");return t}r(Ge,"parseKid");async function Ba(e={}){let{prompt:t=ar}=e,{kid:n}=await t({type:"input",name:"kid",message:Ia,validate:Ha(Ge)});return Ge(n)}r(Ba,"promptKid");async function Ka(e={}){let{prompt:t=r(o=>sr.prompt(o),"prompt")}=e,{action:n}=await t({type:"select",name:"action",message:_a,choices:[{name:"browser",message:Na},{name:"clipboard",message:ja}]});if(n!=="browser"&&n!=="clipboard")throw new Error(`Unexpected Zendesk action: ${n}`);return n}r(Ka,"promptZendeskAction");async function Va(e={}){let{prompt:t=ar,gitUserEmail:n=Ra}=e,{email:o}=await t({type:"input",name:"email",message:Da,initial:n(),validate:Ha(i=>tt(i,"email"))});return tt(o,"email")}r(Va,"promptEmail");async function Ga(e={}){let{prompt:t=ar,stderr:n=process.stderr}=e;for(let o=1;o<=En;o+=1){let{passphrase:i}=await t({type:"password",name:"passphrase",message:$a,validate:r(a=>a.length>=15?!0:Fa(),"validate")}),{confirm:s}=await t({type:"password",name:"confirm",message:Oa});if(i===s)return b.from(i);n.write(La(o))}throw new Error(Ma)}r(Ga,"promptPassphrase");async function Ya(e,t={}){let{prompt:n=r(i=>sr.prompt(i),"prompt")}=t,{confirmed:o}=await n({type:"confirm",name:"confirmed",message:Ua(e),initial:!1});return o}r(Ya,"promptConfirmOverwrite");import{existsSync as Mg,readdirSync as Ug,readFileSync as _g}from"fs";import{join as lr}from"path";import{execFile as Pg}from"child_process";import{promisify as Tg}from"util";var za="cognite-flows",Rg=Tg(Pg),qa=r((e,t)=>Rg(e,t),"defaultExecFile"),Ig=-25300,Dg=Ig&255;function $g(e){if(!(e instanceof Error)||!("code"in e)||e.code!==Dg)return!1;let t="stderr"in e?String(e.stderr):"";return/could not be found/i.test(t)||t===""}r($g,"isKeychainNotFoundError");async function Ja(e,t,n={}){let o=t.expose();if(!X("macos",n))throw new Error("Keychain storage is only supported on macOS");let{execFile:i=qa}=n;await i("security",["add-generic-password","-a",e,"-s",za,"-w",Buffer.from(o,"utf-8").toString("base64"),"-U"])}r(Ja,"storeKeyInKeychain");async function bn(e,t={}){if(!X("macos",t))return null;let{execFile:n=qa}=t;try{let{stdout:o}=await n("security",["find-generic-password","-a",e,"-s",za,"-w"]);return b.from(Buffer.from(o.trim(),"base64").toString("utf-8"))}catch(o){if($g(o))return null;throw o}}r(bn,"readKeyFromKeychain");var Za="cognite-cli-signing",Og="The native @napi-rs/keyring binary failed to load for this platform. Reinstall the CLI, or regenerate the key with `--output <path>` to use passphrase-encrypted file storage instead.",Fg="Multiple Windows Credential Manager entries match this kid. Open Credential Manager (Control Panel \u2192 User Accounts \u2192 Credential Manager \u2192 Windows Credentials) and remove the duplicates.",Wa="Windows Credential Manager failed unexpectedly. Regenerate the key with `--output <path>` to fall back to passphrase-encrypted file storage.";function Lg(e){if(!(e instanceof Error))return Wa;let t=e.message.toLowerCase();return t.includes("cannot find module")||t.includes("module_not_found")||t.includes("failed to load native binding")?Og:t.includes("ambiguous")?Fg:Wa}r(Lg,"hintFor");function Xa(e,t,n){return new m(`Failed to ${e} signing key for kid "${t}" in Windows Credential Manager`,{cause:n,hint:Lg(n),shouldReport:!1})}r(Xa,"wrapKeyringError");async function Qa(e,t){let{Entry:n}=await import("@napi-rs/keyring"),o=new n(e,t);return{setPassword:r(i=>o.setPassword(i),"setPassword"),getPassword:r(()=>o.getPassword(),"getPassword"),deleteCredential:r(()=>o.deleteCredential(),"deleteCredential")}}r(Qa,"defaultCreateEntry");async function ec(e,t,n={}){let{createEntry:o=Qa}=n,i=Buffer.from(t.expose(),"utf-8").toString("base64");try{(await o(Za,e)).setPassword(i)}catch(s){throw Xa("store",e,s)}}r(ec,"storeSigningKey");async function xn(e,t={}){let{createEntry:n=Qa}=t;try{let i=(await n(Za,e)).getPassword();return i===null?null:b.from(Buffer.from(i,"base64").toString("utf-8"))}catch(o){throw Xa("read",e,o)}}r(xn,"readSigningKey");var Le=".pub.pem",pr=".key.jwe",dr=".meta.json";function kn(e){switch(e.kind){case"keychain":return"OS credential store";case"encrypted-file":return e.path;case"public-only":return"public-only (private key missing)"}}r(kn,"formatLocalKeySource");function Ng(e){return{existsSync:e.existsSync??Mg,readdirSync:e.readdirSync??Ug,readFileSync:e.readFileSync??((t,n)=>_g(t,n)),isOS:e.isOS??(t=>X(t)),readKeyFromKeychain:e.readKeyFromKeychain??(t=>bn(t)),readSigningKey:e.readSigningKey??(t=>xn(t))}}r(Ng,"resolveDeps");function jg(e){try{let t=JSON.parse(e);if(typeof t=="object"&&t!==null&&!Array.isArray(t)&&"email"in t&&typeof t.email=="string")return t.email}catch{}}r(jg,"readEmailFromMeta");function Hg(e,t){return t.existsSync(e)?t.readdirSync(e).filter(n=>n.endsWith(Le)):[]}r(Hg,"publicKeyEntries");function Bg(e){return e.slice(0,-Le.length)}r(Bg,"kidFromPublicKeyFilename");async function Kg(e,t,n){if(n.isOS("macos")&&await n.readKeyFromKeychain(e).catch(()=>null)!==null)return{kind:"keychain"};if(n.isOS("windows")&&await n.readSigningKey(e).catch(()=>null)!==null)return{kind:"keychain"};let o=lr(t,`${e}${pr}`);return n.existsSync(o)?{kind:"encrypted-file",path:o}:{kind:"public-only"}}r(Kg,"resolveSource");async function Pn(e=D().keysDir,t={}){let n=Ng(t),o=new Set,i=Hg(e,n).flatMap(s=>{let a=Bg(s);return!a||o.has(a)?[]:(o.add(a),[{kid:a,entry:s}])});return Promise.all(i.map(async({kid:s,entry:a})=>{let c=await Kg(s,e,n),l=lr(e,`${s}${dr}`),p;try{p=jg(n.readFileSync(l,"utf8"))}catch{}return{kid:s,source:c,publicKeyPath:lr(e,a),email:p}}))}r(Pn,"discoverLocalKeys");import{createReadStream as Vg}from"fs";function Tn(e){let t=Vg(e);return new ReadableStream({start(n){t.on("data",o=>{let i=typeof o=="string"?Buffer.from(o):o;n.enqueue(new Uint8Array(i))}),t.on("end",()=>n.close()),t.on("error",o=>n.error(o))},cancel(){t.destroy()}})}r(Tn,"createWebStreamFromFile");import Gg from"path";var Rn=".cognite-bundles";function tc(e,t){return`${e}-${t}.zip`}r(tc,"bundleFileName");function ne(e,t,n){return Gg.join(e,Rn,tc(t,n))}r(ne,"bundlePath");var nc=[".dev.sig",".cert.sig",".sig"];function Zg(e){return{existsSync:e.existsSync??Yg,readFileSync:e.readFileSync??((t,n)=>zg(t,n)),createBundleStream:e.createBundleStream??Tn,verifyBundle:e.verifyBundle??Jg,loadAppConfig:e.loadAppConfig??k,defaultKeyDir:e.defaultKeyDir??(()=>D().keysDir)}}r(Zg,"resolveDeps");function Xg(e,t){return nc.map(n=>`${e}${n}`).find(n=>t(n))}r(Xg,"findSiblingSignature");function Qg(e){let t=e.split(".");return t.length===3&&t.every(n=>n.length>0)}r(Qg,"isCompactJws");function ef(e){try{let t=Wg(e);return typeof t.kid=="string"?t.kid:void 0}catch{return}}r(ef,"readKidFromToken");function tf(e,t,n){let{existsSync:o,readFileSync:i}=n;try{Ge(e)}catch(a){throw new m(a instanceof Error?a.message:String(a),{shouldReport:!1})}if(!o(t))throw new m(`Key directory not found: ${t}`,{shouldReport:!1});let s=qg(t,`${e}${Le}`);if(!o(s))throw new m(`No public key found for kid "${e}" in ${t}`,{shouldReport:!1});try{return i(s,"utf-8")}catch(a){throw new m(`Failed to read public key file: ${s}`,{cause:a,shouldReport:!1})}}r(tf,"resolvePublicKeyForKid");function nf(e,t){let{payload:n,kid:o}=e;if(console.log(`Verified ${n.appId}@${n.version}`),console.log(` kid: ${o}`),console.log(` hash: ${n.bundleSha256}`),n.scopes&&n.scopes.length>0){let i=n.scopes.map(s=>`${s.org}/${s.project}`).join(", ");console.log(` scopes: ${i}`)}t&&console.log(JSON.stringify(n,null,2))}r(nf,"printResult");async function oc(e,t,n={},o=process.cwd()){let{existsSync:i,readFileSync:s,loadAppConfig:a,createBundleStream:c,verifyBundle:l,defaultKeyDir:p}=Zg(n),d;if(e)d=In(o,e);else{let g;try{g=a(o)}catch(h){let v=h instanceof Error?h.message:String(h);throw new m(v,{cause:h,hint:"Run this command from a Cognite app directory (one with app.json), or pass [bundle] explicitly.",shouldReport:!1})}d=ne(o,g.externalId,g.versionTag)}if(!i(d)){let g=e?void 0:"Default derived from app.json \u2014 pass [bundle] explicitly to override.";throw new m(`Bundle not found: ${d}`,{hint:g,shouldReport:!1})}let u=t.sig?In(o,t.sig):Xg(d,i);if(!u)throw new m("No signature file found.",{hint:`Pass --sig <path> or place one of ${nc.map(g=>`${d}${g}`).join(", ")} next to the bundle.`,shouldReport:!1});if(!i(u))throw new m(`Signature file not found: ${u}`,{shouldReport:!1});let f;try{f=s(u,"utf-8").trim()}catch(g){throw new m(`Failed to read signature file: ${u}`,{cause:g,shouldReport:!1})}if(!Qg(f))throw new m(`Malformed JWS in ${u}`,{hint:"Expected a compact JWS (header.payload.signature \u2014 three base64url segments).",shouldReport:!1});let y;if(t.key){let g=In(o,t.key);if(!i(g))throw new m(`Public key not found: ${g}`,{shouldReport:!1});try{y=s(g,"utf-8")}catch(h){throw new m(`Failed to read public key file: ${g}`,{cause:h,shouldReport:!1})}}else{let g=t.keyDir?In(o,t.keyDir):p(),h=ef(f);if(!h)throw new m("Token header has no kid.",{hint:"Pass --key <path> to a public key PEM.",shouldReport:!1});y=tf(h,g,{existsSync:i,readFileSync:s})}try{let g=await l({token:f,publicKeyPem:y,bundleStream:c(d)});nf(g,t.verbose??!1)}catch(g){let h=g instanceof Error?g.message:String(g);throw new m(`Bundle rejected: ${h}`,{shouldReport:!1})}}r(oc,"handleVerify");function rc(e,t={}){return e.command("verify [bundle]").description("Verify a signed app bundle locally (default: derived from app.json)").option("-s, --sig <path>","Path to the signature file (default: sibling .dev.sig / .cert.sig / .sig)").option("--key <path>","Path to a public key PEM file").option("--key-dir <path>","Directory of <kid>.pub.pem files \u2014 kid is read from the token header (default: $COGNITE_CLI_HOME/keys)").option("-v, --verbose","Print the full decoded payload after verification").addHelpText("after",`
|
|
161
161
|
Bundles are stored in .cognite-bundles/<externalId>-<versionTag>.zip by default.
|
|
162
162
|
|
|
163
163
|
Examples:
|
|
164
164
|
cognite apps verify Verify default bundle (path from app.json)
|
|
165
165
|
cognite apps verify .cognite-bundles/my-app-1.0.0.zip Verify a specific bundle
|
|
166
166
|
cognite apps verify .cognite-bundles/my-app-1.0.0.zip --sig my-app-1.0.0.zip.dev.sig Verify with explicit signature
|
|
167
|
-
cognite apps verify .cognite-bundles/my-app-1.0.0.zip --key /path/to/pub.pem Verify with explicit public key`).action((n,o)=>
|
|
167
|
+
cognite apps verify .cognite-bundles/my-app-1.0.0.zip --key /path/to/pub.pem Verify with explicit public key`).action((n,o)=>oc(n,o,t))}r(rc,"registerVerifyCommand");import{existsSync as of}from"fs";import{resolve as rf}from"path";import{config as sf}from"dotenv";function H(e,t={existsSync:of,config:sf}){let n=rf(e,".env");t.existsSync(n)&&(console.log(`Loading environment variables from ${n}`),t.config({path:n}))}r(H,"loadEnvFile");function B(e){e.infra!=="appsApi"&&(console.error(`
|
|
168
168
|
\u26A0\uFE0F Legacy infrastructure is no longer supported.
|
|
169
169
|
|
|
170
170
|
Your app.json is missing \`"infra": "appsApi"\`, which means it was created for
|
|
171
171
|
the old CDF Application Registry. This deploy path has been removed.
|
|
172
172
|
|
|
173
173
|
To migrate: add \`"infra": "appsApi"\` to your app.json, wire up the correct authentication and re-deploy.
|
|
174
|
-
`),process.exit(1))}r(B,"assertAppHostingInfra");import{Option as
|
|
174
|
+
`),process.exit(1))}r(B,"assertAppHostingInfra");import{Option as ic}from"commander";var af={"client-credentials":!0,session:!0,browser:!0};function ur(){return new ic("--auth-method <method>","Authentication method to use when several are valid, skipping the selection prompt").choices(Object.keys(af))}r(ur,"authMethodOption");function cf(){return new ic("--confirm-action-target <target>","Acknowledge the org/project this command will act on, skipping the interactive prompt (value must match the resolved target)")}r(cf,"confirmActionTargetOption");function W(){return[cf(),ur()]}r(W,"sessionAuthOptions");async function lf(e,t,n){let o=await j(e,{interactive:t.interactive,appId:n,orgHint:t.org,authMethod:t.authMethod,confirmActionTarget:t.confirmActionTarget,action:"activate"});return new _(o)}r(lf,"defaultBuildApiClient");async function pf(e,t={}){let{loadEnvFile:n=H,loadAppConfig:o=k,getApiClient:i=lf}=t,s=process.cwd();n(s);let a=o(s);B(a);let c=e.interactive?await L(a,e):$(a.deployments,e.deployment),l=await i(c,e,a.externalId),{externalId:p,versionTag:d}=a,u;try{u=await l.getVersion(p,d)}catch(y){throw y instanceof te?new Error(`Version ${d} of ${p} has not been deployed yet. Run \`npx @cognite/cli apps deploy\` first.`):y}if(u.alias==="ACTIVE"){console.log(` ${p} @ ${d} is already ACTIVE \u2014 nothing to do.`);return}if(u.lifecycleState==="DEPRECATED"||u.lifecycleState==="ARCHIVED")throw new Error(`Cannot activate ${p} @ ${d}: version is ${u.lifecycleState} (terminal).`);u.lifecycleState==="DRAFT"&&(await l.publishVersion(p,d),console.log(`\u2713 Published ${p} @ ${d} is now PUBLISHED`));let{supersededVersion:f}=await l.activateVersion(p,d);console.log(`\u2713 Activated ${p} @ ${d} is now ACTIVE`),f&&console.log(` Superseded ${f} \u2192 PUBLISHED`)}r(pf,"handleActivate");function sc(e){let t=e.command("activate").description("Activate the current app version (publish if needed, then set ACTIVE alias)").argument("[path]","Path to the app folder (only `.` is currently supported)",".").option("-d, --deployment <target>","Deployment target from app.json (index or name)").option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)");return W().forEach(n=>t.addOption(n)),t.addHelpText("after",`
|
|
175
175
|
Examples:
|
|
176
176
|
npx @cognite/cli apps activate . Activate using env-var auth
|
|
177
|
-
npx @cognite/cli apps activate . --interactive Activate using browser auth (no secrets needed)`).action((n,o)=>
|
|
178
|
-
`),initial:!1};async function
|
|
177
|
+
npx @cognite/cli apps activate . --interactive Activate using browser auth (no secrets needed)`).action((n,o)=>pf(o))}r(sc,"registerActivateCommand");import{basename as Ac,dirname as Gf,normalize as Yf,resolve as Ln}from"path";import{fileURLToPath as zf,pathToFileURL as qf}from"url";import{Logger as Jf,runner as Wf}from"hygen";import{safeParse as df}from"valibot";function At(e,t){return n=>{let o=df(t,n);return o.success?!0:`${e} ${o.issues[0].message}`}}r(At,"toPromptValidator");var ac={name:At("App name",Qn),displayName:At("Display name",Xn),baseUrl:At("Base URL",eo),org:At("Org",to),project:At("Project",no)};function uf(e,t){return e?async n=>{let o=t(n);return o===!0?e(n):o}:t}r(uf,"composeValidators");function Dn(e){return e.map(t=>{if(!(t.name in ac))return t;let n=ac[t.name];return{...t,validate:uf(t.validate,n)}})}r(Dn,"applySchemaValidators");import{basename as cc}from"path";import lc from"enquirer";function mr(e){return e.replace(/[A-Z]/g,(t,n)=>n===0?t.toLowerCase():`-${t.toLowerCase()}`)}r(mr,"kebabCase");var mf={type:"confirm",name:"useSpecKit",message:["Enable spec-driven development?"," Adds the github/spec-kit slash commands (/speckit.specify, .clarify, .plan, .tasks, .implement)"," to your app for use in Claude Code, Cursor, or GitHub Copilot. They walk you through writing SPEC.md and"," generating a plan, tasks, and implementation."].join(`
|
|
178
|
+
`),initial:!1};async function gf(e,t,n){return e!==void 0?e:t?!!(await n([mf])).useSpecKit:!1}r(gf,"resolveSpecKit");function ff(e){return typeof e=="function"}r(ff,"isFunctionInitial");function pc(e){return(e??"").trim().replace(/\/+$/,"")||"api"}r(pc,"normalizeCluster");function dc({isCurrentDir:e,dirName:t,onAppName:n,onUseSpecKit:o,presets:i={},specKit:s,prompt:a=lc.prompt.bind(lc)}){return()=>({prompt:r(async c=>{if(!Array.isArray(c))return a([c]);let l=Object.fromEntries(Object.entries(i).filter(R=>R[1]!==void 0)),p=Object.keys(l).length>0,d=e?cc(process.cwd()):t?cc(t):null,u=p&&d!==null,f=!u&&d?c.map(R=>R.name==="name"?{...R,initial:d}:R):c,y=Dn(f),g=u&&d?{...l,name:d}:l,h=new Set(Object.keys(g)),v=y.filter(R=>!h.has(R.name)),S=v.findIndex(R=>R.name==="baseUrl"),C;if(u){let R=pc(g.cluster),Y=r(I=>ff(I.initial)?I.initial():I.initial,"resolveInitial"),le=r(I=>{if(I.name==="baseUrl")return`https://${R}.cognitedata.com`;let oe=Y(I);if(oe===void 0)throw new Error(`Non-interactive mode: --${mr(I.name)} has no default. Pass it as a flag.`);return oe},"deriveValue");C=Object.fromEntries(v.map(I=>[I.name,le(I)]))}else if(S!==-1){let R=v.filter(V=>V.name!=="baseUrl"),Y=R.length>0?await a(R):{},le=typeof Y.cluster=="string"?Y.cluster:"",oe=`https://${pc(le||g.cluster)}.cognitedata.com`,F=v[S],re=await a([{...F,initial:oe}]);C={...Y,...re}}else C=v.length>0?await a(v):{};let A={...g,...C},x=typeof A.name=="string"?A.name:"";x&&n(x);let K=await gf(s,!u&&v.length>0,a);return o?.(K),{...A,name:x,useCurrentDir:e,directoryName:e?void 0:t??void 0,useSpecKit:K}},"prompt")})}r(dc,"createAppPrompter");async function uc(e,t,n){let o=[];Object.values(t).some(s=>s!==void 0)&&n!==null&&o.push({key:"name",value:n,label:"directory"});for(let[s,a]of Object.entries(t))a!==void 0&&o.push({key:s,value:a,label:`--${mr(s)}`});for(let{key:s,value:a,label:c}of o){let l=e.find(d=>d.name===s)?.validate;if(!l)continue;let p=await l(a);if(p!==!0)throw new Error(`Invalid ${c}: ${p}`)}}r(uc,"validatePresets");import{cpSync as gc,existsSync as fc,mkdirSync as On,readdirSync as Cf,readFileSync as Af,writeFileSync as gr}from"fs";import{basename as Ef,dirname as fr,posix as bf,resolve as N}from"path";import{fileURLToPath as hc}from"url";import{copyFileSync as hf,symlinkSync as yf}from"fs";import{dirname as Sf,join as vf}from"path";function wf(e){if(e&&typeof e=="object"&&"code"in e&&typeof e.code=="string")return e.code}r(wf,"errno");function mc(e){return e instanceof Error?e.message:String(e)}r(mc,"messageOf");function $n({target:e,linkPath:t,label:n,symlink:o=yf,copyFile:i=hf}){try{return o(e,t),!0}catch(s){let a=wf(s);if(a==="EEXIST")return!0;let c=mc(s);if(a==="EPERM"||a==="EACCES")try{let l=vf(Sf(t),e);return i(l,t),console.log(`\u2139\uFE0F Wrote ${n} as a copy of ${e} (symlinks need Developer Mode or an elevated shell on Windows).`),!0}catch(l){return console.warn(`\u26A0\uFE0F Could not create ${n} symlink: ${c} (copy fallback also failed: ${mc(l)})`),!1}return console.warn(`\u26A0\uFE0F Could not create ${n} symlink:`,c),!1}}r($n,"linkOrCopyOrWarn");var xf=N(fr(hc(import.meta.url)),"..","..","_vendor","spec-kit"),kf=N(fr(hc(import.meta.url)),"..","..","_cognite-spec-extensions"),Pf=["claude-code","cursor","github-copilot"],Tf={branch_numbering:"sequential"};function yc({appDir:e,vendorDir:t=xf,cogniteExtensionsDir:n=kf,agents:o=Pf}){let i=N(e,".specify"),s=N(i,"memory"),a=new Set(o),c=`prepare spec-kit install for appDir=${e}`,p=[{srcRoot:t,from:"templates",to:".specify/templates"},{srcRoot:t,from:"scripts/bash",to:".specify/scripts/bash"},{srcRoot:t,from:"commands",to:".claude/commands",agent:"claude-code"},{srcRoot:t,from:"commands",to:".cursor/commands",agent:"cursor"},{srcRoot:n,from:"commands",to:".claude/commands",agent:"claude-code"},{srcRoot:n,from:"commands",to:".cursor/commands",agent:"cursor"},{srcRoot:n,from:"templates",to:".specify/templates"}].filter(({agent:d})=>!d||a.has(d));try{for(let{srcRoot:u,from:f,to:y}of p){let g=N(e,y);c=`copy ${Ef(u)}/${f} to ${y}`,On(fr(g),{recursive:!0}),gc(N(u,f),g,{recursive:!0})}if(a.has("github-copilot")){let u=N(e,".github","agents"),f=N(e,".github","prompts");c="create .github/agents and .github/prompts dirs",On(u,{recursive:!0}),On(f,{recursive:!0});for(let y of[N(t,"commands"),N(n,"commands")])if(fc(y))for(let g of Cf(y)){if(!g.endsWith(".md"))continue;let h=g.slice(0,-3);c=`copy ${g} to .github/agents/${h}.agent.md`,gr(N(u,`${h}.agent.md`),Af(N(y,g))),c=`write .github/prompts/${h}.prompt.md`,gr(N(f,`${h}.prompt.md`),`---
|
|
179
179
|
agent: ${h}
|
|
180
180
|
---
|
|
181
|
-
`)}}let d=
|
|
182
|
-
`),c=`link .specify/memory/constitution.md in specifyDir=${i}
|
|
181
|
+
`)}}let d=N(i,"extensions.yml");fc(d)||(c="write .specify/extensions.yml",gc(N(n,"extensions.yml"),d)),c=`write init-options.json under specifyDir=${i}`,gr(N(i,"init-options.json"),`${JSON.stringify(Tf,null,2)}
|
|
182
|
+
`),c=`link .specify/memory/constitution.md in specifyDir=${i}`,On(s,{recursive:!0}),$n({target:bf.join("..","..","AGENTS.md"),linkPath:N(s,"constitution.md"),label:".specify/memory/constitution.md"})}catch(d){let u=d instanceof Error?d.message:String(d);throw new Error(`installSpecKit failed while ${c} (appDir=${e}, vendorDir=${t}): ${u}`,{cause:d})}}r(yc,"installSpecKit");import{execFileSync as Fn}from"child_process";import{mkdtempSync as Rf,readdirSync as If,rmSync as Df}from"fs";import{createRequire as $f}from"module";import{tmpdir as Of}from"os";import{join as Ff,resolve as Sc}from"path";import{InvalidArgumentError as Lf}from"commander";import Mf from"enquirer";var vc="cognitedata/builder-skills",hr=["claude-code","cursor","github-copilot","opencode","codex"],Uf=$f(import.meta.url).resolve("skills/bin/cli.mjs");function yr(e,t={}){try{Fn(process.execPath,[Uf,...e],{stdio:"inherit",cwd:process.cwd(),...t,env:{...process.env,...t.env,DISABLE_TELEMETRY:"1"}})}catch(n){throw Ae(),new m(`Skills CLI failed (${e.join(" ")})`,{cause:n,hint:"Check your internet connection and try again."})}}r(yr,"execSkillsCli");function _f(){return hr.map(e=>["add",vc,"-a",e,"--skill","*","-y"])}r(_f,"pullAllArgsPerAgent");var Nf=1e4;async function wc(e,t={}){let n=t.exec??yr;Ae();let o=t.timeout??Nf,i=t.readdir??(c=>If(c));for(let c of _f())try{n(c,{cwd:e,timeout:o,stdio:["pipe","pipe","inherit"]})}catch(l){let p=l instanceof Error?l.message:String(l);console.warn("\u26A0\uFE0F Could not pull skills for args ["+c.join(" ")+"]:",p)}let s=new Set;for(let c of[Sc(e,".claude","skills"),Sc(e,".agents","skills")])try{i(c).forEach(l=>s.add(l))}catch{}let a=s.size;a>0?console.log(`Installed ${a} skills successfully.`):console.log("No skills were installed.")}r(wc,"pullAllSkillsInto");function jf(e){if(!/^[\w.-]+\/[\w.-]+$/.test(e))throw new Lf("Expected owner/repo format (e.g., cognitedata/builder-skills)");return e}r(jf,"validateSource");function Hf(e){let t=Rf(Ff(Of(),"skills-"));try{try{Fn("git",["clone","--depth","1","--filter=blob:none","--no-checkout","-q",`https://github.com/${e}.git`,t],{stdio:"ignore"})}catch(o){throw Ae(),new m(`Failed to clone skills repository "${e}".`,{hint:"Check your internet connection and try again.",shouldReport:!1,cause:o})}let n;try{n=Fn("git",["ls-tree","-d","--name-only","HEAD:skills"],{cwd:t})}catch{n=Fn("git",["ls-tree","-d","--name-only","HEAD"],{cwd:t})}return n.toString().trim().split(/\r?\n/).filter(o=>!!o&&!o.startsWith("."))}finally{Df(t,{recursive:!0,force:!0})}}r(Hf,"listRemoteSkills");async function Bf(e,t={}){let n=r(c=>Mf.prompt(c),"defaultPrompt"),{listSkills:o=Hf,prompt:i=n}=t,s=o(e),{selected:a}=await i({type:"multiselect",name:"selected",message:"Select skills to install (space to toggle, a to toggle all, enter to confirm)",choices:s});return a}r(Bf,"pickSkillsInteractive");function Kf(e,t,n){let o=["add",e.source,"-a",t];return e.skill?o.push("--skill",e.skill):n&&n.length>0?o.push("--skill",...n,"-y"):o.push("--skill","*","-y"),e.global&&o.push("--global"),o}r(Kf,"buildPullArgs");async function Vf(e){Ae(),console.log(`Pulling skills from ${e.source}...`);let t;if(e.interactive&&!e.skill){try{t=await Bf(e.source)}catch(o){if(o instanceof m)throw o;let i=o instanceof Error?o.message:String(o);console.error(`Failed to resolve skills interactively: ${i}`),process.exitCode=1;return}if(t.length===0){console.log("No skills selected.");return}}let n=!1;for(let o of hr)try{yr(Kf(e,o,t))}catch(i){let s=i instanceof Error?i.message:String(i);console.warn(`\u26A0\uFE0F Could not pull skills for ${o}: ${s}`),n=!0}n?(console.log(`
|
|
183
183
|
Skills pulled with some errors (see warnings above)`),process.exitCode=1):console.log(`
|
|
184
|
-
Skills pulled successfully`)}r(
|
|
185
|
-
Supports: ${
|
|
184
|
+
Skills pulled successfully`)}r(Vf,"handlePull");function Cc(e){let t=e.command("skills").summary("Manage AI agent skills for your app").description(`Manage AI agent skills for your app.
|
|
185
|
+
Supports: ${hr.join(", ")}`).addHelpText("after",`
|
|
186
186
|
Examples:
|
|
187
187
|
npx @cognite/cli apps skills pull Pull all skills
|
|
188
188
|
npx @cognite/cli apps skills pull --skill create-client-tool Pull a specific skill
|
|
189
|
-
npx @cognite/cli apps skills list List installed skills`);return t.command("pull").description("Pull all skills into your project").option("--source <owner/repo>","Skills repository"
|
|
189
|
+
npx @cognite/cli apps skills list List installed skills`);return t.command("pull").description("Pull all skills into your project").option("--source <owner/repo>","Skills repository",jf,vc).option("--skill <name>","Pull a specific skill by name").option("-i, --interactive","Interactively select which skills to install",!1).option("--global","Install skills globally",!1).action(Vf),t.command("list").description("List installed skills").action(()=>{yr(["list"])}),t}r(Cc,"registerSkillsCommand");var Ec=Ln(Gf(zf(import.meta.url)),"..","..","_templates");async function Zf(){let e=Ln(Ec,"app","new","prompt.js");return(await import(qf(e).href)).default}r(Zf,"loadPromptDefs");function Xf(e,t){return!e||t?null:Yf(e)}r(Xf,"resolveDirName");function Qf(e,t,n){if(e)return{cwd:process.cwd(),display:"."};let o=t??n;if(!o)throw new Error("App creation completed without a target directory or name.");return{cwd:Ln(process.cwd(),o),display:o}}r(Qf,"resolveAppLocation");function eh(e,t,n){let o=` npm install
|
|
190
190
|
npm run dev`,i="To deploy your app:",s="npx @cognite/cli apps deploy --interactive",a=n?`
|
|
191
191
|
To start spec-driven development:
|
|
192
192
|
Run /speckit.specify in Claude Code, Cursor, or GitHub Copilot and describe your app.
|
|
@@ -213,7 +213,7 @@ ${i}
|
|
|
213
213
|
cd "${t}"
|
|
214
214
|
${s}
|
|
215
215
|
${c}
|
|
216
|
-
`)}r(
|
|
216
|
+
`)}r(eh,"printSuccessMessage");async function th(e){try{console.log("\u{1F9E0} Pulling skills into your app..."),await wc(e)}catch(t){let n=t instanceof Error?t.message:String(t);console.warn("\u26A0\uFE0F Could not pull skills:",n)}}r(th,"pullSkillsInto");function nh(e,t={}){let{isGitInstalled:n=wn,isInsideGitRepo:o=An,gitInitAndCommit:i=Pa}=t;if(!n()){console.warn("git not found \u2014 skipping git repository initialisation");return}if(!o(e)){console.log("Initialising git repository...");try{i(e)}catch(s){let c=(s&&typeof s=="object"&&"stderr"in s&&s.stderr?String(s.stderr).trim():"")||(s instanceof Error?s.message:String(s));console.warn("Could not initialise git repository:",c)}}}r(nh,"maybeInitGit");async function oh(e,t){let n=e==="."||e==="./",o=Xf(e,n),i=null,s=!1,a={displayName:t.displayName,description:t.description,org:t.org,project:t.project,cluster:t.cluster,baseUrl:t.baseUrl},c=await Zf(),l=Dn(c),p=n?Ac(process.cwd()):o?Ac(o):null;await uc(l,a,p);let d=dc({isCurrentDir:n,dirName:o,onAppName:r(f=>{i=f},"onAppName"),onUseSpecKit:r(f=>{s=f},"onUseSpecKit"),presets:a,specKit:t.specKit});await Wf(["app","new"],{templates:Ec,cwd:process.cwd(),logger:new Jf(console.log.bind(console)),createPrompter:d,debug:!!process.env.DEBUG});let u=Qf(n,o,i);$n({target:"AGENTS.md",linkPath:Ln(u.cwd,"CLAUDE.md"),label:"CLAUDE.md"}),s&&yc({appDir:u.cwd}),await th(u.cwd),nh(u.cwd),eh(n,u.display,s)}r(oh,"handleCreate");function bc(e){return e.command("create").description("Create a new application.").argument("[directory]","Target directory (. for current, or subdirectory name)").option("--display-name <name>","App display name (skips the prompt)").option("--description <description>","App description (skips the prompt)").option("--org <org>","Deployment org (skips the prompt)").option("--project <project>","Deployment project (skips the prompt)").option("--cluster <cluster>","CDF cluster, e.g. greenfield (skips the prompt)").option("--base-url <url>","CDF base URL, e.g. https://greenfield.cognitedata.com (skips the prompt; defaults to cluster-derived URL when omitted)").option("--spec-kit","Install spec-kit slash commands (skips the prompt)").option("--no-spec-kit","Skip spec-kit installation (skips the prompt)").addHelpText("after",`
|
|
217
217
|
Non-interactive use (CI, scripts, AI agents):
|
|
218
218
|
Pass [directory] plus --display-name, --description, --org, --project, --cluster, --base-url
|
|
219
219
|
to skip every prompt. Missing flags fall back to the interactive prompt.
|
|
@@ -226,30 +226,30 @@ Examples:
|
|
|
226
226
|
--display-name "My App" --description "My app" \\
|
|
227
227
|
--org cog-atlas --project atlas-greenfield --cluster greenfield \\
|
|
228
228
|
--base-url https://greenfield.cognitedata.com
|
|
229
|
-
Fully non-interactive`).action(
|
|
229
|
+
Fully non-interactive`).action(oh)}r(bc,"registerCreateCommand");import rh from"path";async function ih(e,t,n){return on(e,{interactive:t.interactive,appId:n,orgHint:t.org,authMethod:t.authMethod,confirmActionTarget:t.confirmActionTarget,action:"deactivate"})}r(ih,"defaultBuildApiClient");async function sh(e,t,n={}){let{loadEnvFile:o=H,loadAppConfig:i=k,getApiClient:s=ih}=n,a=rh.resolve(process.cwd(),e);o(a);let c=i(a);B(c);let l=t.interactive?await L(c,t):$(c.deployments,t.deployment),{externalId:p}=c,d=await s(l,t,p),u=await d.getActiveVersion(p);if(!u){console.log(` ${p} has no active version \u2014 nothing to deactivate.`);return}await d.deactivateVersion(p,u.version),console.log(`\u2713 Deactivated ${p} @ ${u.version} \u2014 active alias removed`)}r(sh,"handleDeactivate");function xc(e){let t=e.command("deactivate").description("Deactivate the app by removing its active version from service").argument("[path]","Path to the app folder (only `.` is currently supported)",".").option("-d, --deployment <target>","Deployment target from app.json (index or name)").option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)");return W().forEach(n=>t.addOption(n)),t.addHelpText("after",`
|
|
230
230
|
Examples:
|
|
231
231
|
npx @cognite/cli apps deactivate . Deactivate using env-var auth
|
|
232
|
-
npx @cognite/cli apps deactivate . --interactive Deactivate using browser auth (no secrets needed)`).action((n,o)=>
|
|
233
|
-
`);return}if(y.lifecycleState==="DRAFT"){await d.deleteVersion(u,f),console.log(`\u2713 Deleted ${u} @ ${f} (DRAFT removed)`);return}y.lifecycleState==="PUBLISHED"&&(await d.deprecateVersion(u,f),console.log(`\u2713 Deprecated ${u} @ ${f} is now DEPRECATED`)),await d.archiveVersion(u,f),console.log(`\u2713 Archived ${u} @ ${f} is now ARCHIVED`)}r(
|
|
232
|
+
npx @cognite/cli apps deactivate . --interactive Deactivate using browser auth (no secrets needed)`).action((n,o)=>sh(n,o))}r(xc,"registerDeactivateCommand");import ah from"path";import ch from"enquirer";async function lh(e,t,n){return on(e,{interactive:t.interactive,appId:n,orgHint:t.org,authMethod:t.authMethod,confirmActionTarget:t.confirmActionTarget,action:"delete"})}r(lh,"defaultBuildApiClient");async function ph(e){let{confirmed:t}=await ch.prompt({type:"confirm",name:"confirmed",message:e,initial:!1});return t}r(ph,"defaultConfirm");async function dh(e,t,n={}){let{loadEnvFile:o=H,loadAppConfig:i=k,getApiClient:s=lh,confirm:a=ph}=n,c=ah.resolve(process.cwd(),e);o(c);let l=i(c);B(l);let p=t.interactive?await L(l,t):$(l.deployments,t.deployment),d=await s(p,t,l.externalId),{externalId:u,versionTag:f}=l,y;try{y=await d.getVersion(u,f)}catch(g){throw g instanceof te?new m(`Version ${f} of ${u} has not been deployed yet.`,{hint:"Run `npx @cognite/cli apps deploy` first."}):g}if(y.alias==="ACTIVE")throw new m(`Cannot archive ${u} @ ${f}: version is currently ACTIVE.`,{hint:"Run `npx @cognite/cli apps deactivate` first."});if(y.lifecycleState==="ARCHIVED"){console.log(` ${u} @ ${f} is already ARCHIVED \u2014 nothing to do.`);return}if(!t.force&&!await a(`Delete ${u} @ ${f}?`)){process.stderr.write(`Aborted.
|
|
233
|
+
`);return}if(y.lifecycleState==="DRAFT"){await d.deleteVersion(u,f),console.log(`\u2713 Deleted ${u} @ ${f} (DRAFT removed)`);return}y.lifecycleState==="PUBLISHED"&&(await d.deprecateVersion(u,f),console.log(`\u2713 Deprecated ${u} @ ${f} is now DEPRECATED`)),await d.archiveVersion(u,f),console.log(`\u2713 Archived ${u} @ ${f} is now ARCHIVED`)}r(dh,"handleDelete");function kc(e){let t=e.command("delete").description("Archive the current app version").argument("[path]","Path to the app folder (only `.` is currently supported)",".").option("-d, --deployment <target>","Deployment target from app.json (index or name)").option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)").option("-f, --force","Skip confirmation prompt",!1);return W().forEach(n=>t.addOption(n)),t.addHelpText("after",`
|
|
234
234
|
Examples:
|
|
235
235
|
npx @cognite/cli apps delete . Archive using env-var auth
|
|
236
236
|
npx @cognite/cli apps delete . --interactive Archive using browser auth (no secrets needed)
|
|
237
|
-
npx @cognite/cli apps delete . --force Skip confirmation prompt`).action((n,o)=>
|
|
238
|
-
`).filter(Boolean),i=r(a=>{let c=a.replace(/\\/g,"/");return!
|
|
237
|
+
npx @cognite/cli apps delete . --force Skip confirmation prompt`).action((n,o)=>dh(n,o))}r(kc,"registerDeleteCommand");import{existsSync as kh}from"fs";import{rm as Ph}from"fs/promises";import Tc from"enquirer";import{existsSync as wh}from"fs";import{mkdir as Ch,readFile as Ah}from"fs/promises";import{basename as Eh,dirname as bh}from"path";import{execFileSync as Mn}from"child_process";import Re from"fs";import Z from"path";import{parseAndValidateManifestConfig as gh}from"@cognite/app-sdk/vite";import{BlobReader as fh,Uint8ArrayWriter as hh,ZipWriter as yh}from"@zip.js/zip.js";import{existsSync as uh,readFileSync as mh}from"fs";var Ee=[".dev.sig",".cert.sig"];function Et(e,t={}){let n=t.existsSync??uh,o=t.readFileSync??((s,a)=>mh(s,a)),i=[];for(let s of Ee){let a=`${e}${s}`;if(!n(a))continue;let c=o(a,"utf8").trim();c.length>0&&i.push(c)}return i}r(Et,"discoverSignatures");var Sr="package.json",vr="package-lock.json",Pc="manifest.json",wr=".cognite",Sh=[/^\.env(\..+)?$/i,/^\.secrets?$/i,/^\.token/i,/^\.cognite/i,/\.(key|pem|p12|pfx|jks|crt)$/i];function vh(e){let[t,n,...o]=e.split("/");return t!==Rn||n===void 0||o.length>0?!1:n.endsWith(".zip")||Ee.some(i=>n.endsWith(`.zip${i}`))}r(vh,"isBundleArtifact");var Cr=class Cr{constructor(t="dist"){this.distPath=Z.isAbsolute(t)?t:Z.join(process.cwd(),t),this.appRoot=Z.dirname(this.distPath)}validateBuildDirectory(){if(!Re.existsSync(this.distPath))throw new Error(`Build directory "${this.distPath}" not found. Run build first.`);let t=Z.join(this.appRoot,Sr);if(!Re.existsSync(t))throw new Error(`"${t}" not found. It is required for deployment.`);let n=Z.join(this.appRoot,vr);if(!Re.existsSync(n))throw new Error(`"${n}" not found. It is required for deployment.`)}async createZip(t="app.zip",n=!1){this.validateBuildDirectory(),console.log("\u{1F4E6} Packaging application...");let o=new yh(new hh,{level:9}),i=r(async(l,p)=>{await o.add(p,new fh(await Re.openAsBlob(l))),n&&console.log(` \u{1F4C4} ${p}`)},"addFile"),s=r(async l=>{let p=await Re.promises.readdir(l,{withFileTypes:!0});for(let d of p){let u=Z.join(l,d.name);d.isDirectory()?await s(u):await i(u,Z.relative(this.distPath,u).replace(/\\/g,"/"))}},"addDir"),a;try{await s(this.distPath);let l=Z.join(this.appRoot,Sr);await i(l,Z.posix.join(wr,Sr));let p=Z.join(this.appRoot,Pc);if(Re.existsSync(p)){let u=Re.readFileSync(p,"utf-8");gh(u,p),await i(p,Z.posix.join(wr,Pc))}let d=Z.join(this.appRoot,vr);await i(d,Z.posix.join(wr,vr)),a=await o.close()}catch(l){let p=l instanceof Error?l.message:String(l);throw new Error(`Failed to create zip: ${p}`)}try{await Re.promises.writeFile(t,a)}catch(l){throw new m(`Failed to write bundle to ${t}`,{cause:l})}let c=(a.byteLength/1024/1024).toFixed(2);return console.log(`\u2705 App packaged: ${t} (${c} MB)`),t}async createSourceArchive(t){console.log("\u{1F4E6} Packaging source for review...");let n;try{n=Mn("git",["-C",this.appRoot,"rev-parse","--show-toplevel"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}catch(l){throw Ae(),new m("Source packaging requires a git repository.",{hint:"Run `git init` first.",shouldReport:!1,cause:l})}let o=Mn("git",["-C",this.appRoot,"rev-parse","--show-prefix"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),i=o?o.replace(/\/$/,""):".",s=i==="."?"HEAD":`HEAD:${i}`;this.validateNoSensitiveFiles(n,s);try{Mn("git",["-C",n,"archive","--format=zip",`--output=${t}`,s])}catch(l){let p=l instanceof Error?l.message:String(l);throw new Error(`Failed to create source archive: ${p}`)}let c=(Re.statSync(t).size/1024/1024).toFixed(2);return console.log(`\u2705 Source packaged: ${Z.basename(t)} (${c} MB)`),t}validateNoSensitiveFiles(t,n){let o=Mn("git",["-C",t,"ls-tree","-r","--name-only",n],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().split(`
|
|
238
|
+
`).filter(Boolean),i=r(a=>{let c=a.replace(/\\/g,"/");return!vh(c)&&c.split("/").some(l=>Sh.some(p=>p.test(l)))},"isSensitive"),s=o.filter(i);if(s.length>0)throw new Error(`Source archive would include sensitive files \u2014 remove them from git tracking first:
|
|
239
239
|
`+s.map(a=>` ${a}`).join(`
|
|
240
240
|
`)+`
|
|
241
|
-
Hint: git rm --cached <file>`)}};r(
|
|
241
|
+
Hint: git rm --cached <file>`)}};r(Cr,"ApplicationPackager");var Ie=Cr;async function Ar(e,t,{existsSync:n=wh,mkdir:o=Ch,createZip:i=r((s,a)=>new Ie(s).createZip(a,!0),"createZipFn")}={}){let{externalId:s,versionTag:a}=e,c=ne(t,s,a);if(n(c)){let p=Ee.some(d=>n(`${c}${d}`))?"A signed bundle already exists here. Re-deploying will invalidate the signing process. Bump versionTag in app.json to deploy as a new version, or delete the bundle and its .sig files then re-sign after deploying.":"Bump versionTag in app.json to deploy as a new version, or delete the existing bundle from .cognite-bundles/ to redeploy the same version.";throw new m(`Bundle already exists: ${c}`,{hint:p,shouldReport:!1})}await o(bh(c),{recursive:!0}),await i(`${t}/dist`,c)}r(Ar,"packageBundle");async function Er(e,t,n,o,{readFile:i=Ah,upload:s=r(async(a,c)=>new _(e).deploy(t.externalId,t.name,t.description,t.versionTag,a,c,o),"uploadFn")}={}){let a=ne(n,t.externalId,t.versionTag),c;try{c=await i(a)}catch(l){throw new m(`Failed to read bundle file: ${a}`,{cause:l})}await s(c,Eh(a))}r(Er,"uploadBundle");import{execSync as xh}from"child_process";function Un(e,t=!0,n={execSync:xh}){console.log("\u{1F4E6} Building app with npm...");try{n.execSync("npm run build",{cwd:e,stdio:t?"inherit":"pipe"})}catch(o){throw new m(`npm run build failed in ${e}`,{cause:o,hint:"Check the build output above for errors."})}console.log("\u2705 Build successful")}r(Un,"buildApp");async function Th(e){let{confirmed:t}=await Tc.prompt({type:"confirm",name:"confirmed",message:e,initial:!1});return t}r(Th,"defaultConfirm");async function Rh(e,t){let{selected:n}=await Tc.prompt({type:"select",name:"selected",message:e,choices:t});return n}r(Rh,"defaultSelect");async function Ih(e){await Ph(e,{force:!0})}r(Ih,"defaultRm");function Dh(e,t,n){return n(e)?t.skipBuild?"use-existing":process.stdout.isTTY?"prompt":"package-fresh":"package-fresh"}r(Dh,"classifyExistingBundle");async function $h(e,t){let{versionTag:n,hasSigs:o}=e,i=o?`A signed bundle for v${n} already exists. What would you like to do?`:`A bundle for v${n} already exists. What would you like to do?`,s=await t.select(i,[{name:"reuse",message:"Deploy the existing bundle without rebuilding"},{name:"rebuild",message:"Rebuild and deploy (overwrites the existing bundle)",...o?{hint:"\u2014 discards existing signatures"}:{}},{name:"cancel",message:"Cancel \u2014 do nothing"}]);if(s==="rebuild"&&o){let a=P(process.stderr);if(console.warn(a.bold.red(`
|
|
242
242
|
WARNING: this bundle is already signed.`)),console.warn(a.red(`Rebuilding overwrites the bundle and permanently discards its signatures (${Ee.join(", ")}). You will have to re-sign before publishing.
|
|
243
|
-
`)),!await t.confirm("Rebuild anyway and discard the existing signatures?"))return"cancel"}return s==="reuse"?"reuse":s==="rebuild"?"rebuild":"cancel"}r(
|
|
244
|
-
`))}r(
|
|
243
|
+
`)),!await t.confirm("Rebuild anyway and discard the existing signatures?"))return"cancel"}return s==="reuse"?"reuse":s==="rebuild"?"rebuild":"cancel"}r($h,"promptBundleAction");async function Oh(e,t){for(let n of[e,...Ee.map(o=>`${e}${o}`)])t.existsSync(n)&&await t.rm(n)}r(Oh,"removeBundleArtifacts");function Rc(e){let{appConfig:t,deployment:n,interactive:o}=e,i=o?"Deploy (Interactive)":"Deploy",s=o?`${n.project} @ ${n.baseUrl}`:`${n.org}/${n.project}`;console.log(["",i,"=".repeat(i.length),`App: ${t.name} (${t.externalId})`,`Version: ${t.versionTag}`,`Target: ${s}`,""].join(`
|
|
244
|
+
`))}r(Rc,"printDeployInfo");function Ic(e){let{appConfig:t,deployment:n}=e;console.log(`
|
|
245
245
|
Successfully deployed ${t.name} version ${t.versionTag} to ${n.org?`${n.org}/`:""}${n.project}`),console.log("App is deployed in draft mode");let o=t.deployments.length>1?` -d ${n.project}`:"";console.log(`
|
|
246
246
|
To sign: npx @cognite/cli apps sign --interactive${o}`),console.log(`To publish: npx @cognite/cli apps publish .${o}`),console.log(`To activate: npx @cognite/cli apps activate .${o}`),console.log(`
|
|
247
|
-
To submit for certification: npx @cognite/cli apps submit`);let i=
|
|
247
|
+
To submit for certification: npx @cognite/cli apps submit`);let i=ha(n,t);i&&console.log(`
|
|
248
248
|
Open your app:
|
|
249
|
-
${i}`)}r(
|
|
250
|
-
Deploying to ${o.org}/${o.project}...`);let f=
|
|
251
|
-
Deploying to ${o.project}...`);let f=
|
|
252
|
-
Deployment cancelled. Nothing was deployed.`);return}A==="reuse"?
|
|
249
|
+
${i}`)}r(Ic,"printDeployResult");function Dc(e){let{externalId:t,name:n,description:o,versionTag:i}=e;return{externalId:t,name:n,description:o,versionTag:i}}r(Dc,"toApp");async function Fh(e,t){let{appConfig:n,deployment:o,cwd:i,options:s,useExistingBundle:a}=e,{buildApp:c,buildClient:l,packageBundle:p,uploadBundle:d}=t;Rc({appConfig:n,deployment:o,interactive:!1});let u=await l(o,{interactive:!1,appId:n.externalId,orgHint:s.org,authMethod:s.authMethod,confirmActionTarget:s.confirmActionTarget,action:"deploy"});!s.skipBuild&&!a&&c(i),console.log(`
|
|
250
|
+
Deploying to ${o.org}/${o.project}...`);let f=Dc(n);a||await p(f,i),await d(u,f,i,!1),Ic({appConfig:n,deployment:o})}r(Fh,"handleDeployNonInteractive");async function Lh(e,t){let{appConfig:n,deployment:o,cwd:i,options:s,useExistingBundle:a}=e,{buildApp:c,buildClient:l,packageBundle:p,uploadBundle:d}=t;Rc({appConfig:n,deployment:o,interactive:!0}),!s.skipBuild&&!a&&c(i);let u=await l(o,{interactive:!0,appId:n.externalId,orgHint:s.org,authMethod:s.authMethod});console.log(`
|
|
251
|
+
Deploying to ${o.project}...`);let f=Dc(n);a||await p(f,i),await d(u,f,i,!1),Ic({appConfig:n,deployment:o})}r(Lh,"handleDeployInteractive");async function Mh(e,t=process.cwd(),n={}){let{loadEnvFile:o=H,loadAppConfig:i=k,confirm:s=Th,select:a=Rh,existsSync:c=kh,rm:l=Ih,buildApp:p=Un,buildClient:d=j,packageBundle:u=Ar,uploadBundle:f=Er}=n;o(t);let y=i(t);B(y);let g=ne(t,y.externalId,y.versionTag),h=Dh(g,e,c),v=h==="use-existing";if(h==="prompt"){let C=Ee.some(x=>c(`${g}${x}`)),A=await $h({versionTag:y.versionTag,hasSigs:C},{select:a,confirm:s});if(A==="cancel"){console.log(`
|
|
252
|
+
Deployment cancelled. Nothing was deployed.`);return}A==="reuse"?v=!0:await Oh(g,{existsSync:c,rm:l})}if(e.interactive){let C=await L(y,e);await Lh({appConfig:y,deployment:C,cwd:t,options:e,useExistingBundle:v},{buildApp:p,buildClient:d,packageBundle:u,uploadBundle:f});return}let S=$(y.deployments,e.deployment);await Fh({appConfig:y,deployment:S,cwd:t,options:e,useExistingBundle:v},{buildApp:p,buildClient:d,packageBundle:u,uploadBundle:f})}r(Mh,"handleDeploy");function $c(e){let t=e.command("deploy").description("Deploy your app to Cognite Data Fusion. Run `auth login` to sign in, or use --interactive for a one-off browser login (no env-var secrets required).").option("-d, --deployment <target>","Deployment target (index or project name)").option("--skip-build","Skip the build step",!1).option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)");return W().forEach(n=>t.addOption(n)),t.addHelpText("after",`
|
|
253
253
|
Environment (non-interactive):
|
|
254
254
|
deployClientId and deploySecretName are configured per deployment in app.json.
|
|
255
255
|
deploySecretName is the name of the environment variable that holds the client
|
|
@@ -263,10 +263,10 @@ Examples:
|
|
|
263
263
|
npx @cognite/cli apps deploy -d my-project Deploy to project by name
|
|
264
264
|
npx @cognite/cli apps deploy --skip-build Deploy without rebuilding
|
|
265
265
|
npx @cognite/cli apps deploy --interactive Browser auth, prompts for target
|
|
266
|
-
npx @cognite/cli apps deploy --interactive -d 0 Browser auth, target chosen non-interactively`).action(n=>
|
|
267
|
-
Extracting bundles...`),await a(
|
|
266
|
+
npx @cognite/cli apps deploy --interactive -d 0 Browser auth, target chosen non-interactively`).action(n=>Mh(n))}r($c,"registerDeployCommand");import jn from"fs";import Kh from"os";import Me from"path";import Vh from"enquirer";import br from"fs";import _n from"path";import{BlobReader as Uh,Uint8ArrayWriter as _h,ZipReader as Nh}from"@zip.js/zip.js";import bt from"path";function Oc(e,t){let n=bt.resolve(e),o=bt.resolve(t),i=bt.relative(n,o);return i===""||bt.isAbsolute(i)?!1:i!==".."&&!i.startsWith(`..${bt.sep}`)}r(Oc,"isSafePath");var jh=1e5,Hh=2*1024**3;async function Fc(e,t,n={}){let{openAsBlob:o=r(d=>br.openAsBlob(d),"openAsBlob"),mkdir:i=r((d,u)=>br.promises.mkdir(d,u),"mkdir"),writeFile:s=r((d,u)=>br.promises.writeFile(d,u),"writeFile"),maxEntries:a=jh,maxTotalBytes:c=Hh}=n,l=await o(e),p=new Nh(new Uh(l));try{let d;try{d=await p.getEntries()}catch(y){throw new m(`Could not read bundle: ${_n.basename(e)} is not a valid zip file.`,{hint:"Make sure you are passing the correct bundle path.",shouldReport:!1,cause:y})}let u=0,f=0;for(let y of d){if(y.directory)continue;if(f++,f>a)throw new Error(`Zip contains too many entries (limit: ${a})`);if(u+=y.uncompressedSize,u>c)throw new Error(`Zip exceeds maximum allowed size (limit: ${Math.round(c/(1024*1024))} MB)`);if(_n.isAbsolute(y.filename))throw new Error(`Malicious zip entry rejected: ${y.filename}`);let g=_n.join(t,y.filename);if(!Oc(t,g))throw new Error(`Malicious zip entry rejected: ${y.filename}`);let h=await y.getData(new _h);await i(_n.dirname(g),{recursive:!0}),await s(g,h)}}finally{await p.close()}}r(Fc,"extractZip");import{execFileSync as Bh}from"child_process";function Mc(e){return e instanceof Error&&"status"in e&&typeof e.status=="number"}r(Mc,"isExitError");function Lc(e){if(!Mc(e)||e.status!==1)throw e}r(Lc,"swallowDiffExit");var xr=class xr{constructor(t={execFileSync:Bh}){this.deps=t}isSupported(){try{return this.deps.execFileSync("git",["--version"],{stdio:"pipe"}),!0}catch{return!1}}isIdentical(t,n){try{return this.deps.execFileSync("git",["diff","--no-index","--quiet","--ignore-cr-at-eol",t,n]),!0}catch(o){if(Mc(o)&&o.status===1)return!1;throw o}}showStat(t,n){try{this.deps.execFileSync("git",["--no-pager","diff","--stat","--no-index","--ignore-cr-at-eol",t,n],{stdio:"inherit"})}catch(o){Lc(o)}}showDiff(t,n,{usePager:o=!0}={}){let i=[];o||i.push("--no-pager"),i.push("diff","--word-diff=color","--no-index","--ignore-cr-at-eol",t,n);try{this.deps.execFileSync("git",i,{stdio:"inherit"})}catch(s){Lc(s)}}};r(xr,"GitDiffer");var Nn=xr;var Gh=r(async e=>(await Vh.prompt([{type:"confirm",name:"answer",message:e,initial:!1}])).answer,"defaultConfirm");async function Yh(e,t,n={}){let{cwd:o=process.cwd(),buildApp:i=Un,createPackager:s=r(A=>new Ie(A),"createPackager"),extractZip:a=Fc,differ:c=new Nn,existsSync:l=r(A=>jn.existsSync(A),"existsSync"),mkdtemp:p=r(A=>jn.promises.mkdtemp(A),"mkdtemp"),mkdir:d=r(async(A,x)=>{await jn.promises.mkdir(A,x)},"mkdir"),rm:u=r((A,x)=>jn.promises.rm(A,x),"rm"),isInteractive:f=r(()=>!!(process.stdin.isTTY&&process.stdout.isTTY),"isInteractive"),confirm:y=Gh,setExitCode:g=r(A=>{process.exitCode=A},"setExitCode")}=n;if(!c.isSupported())throw new m("git is required for the diff command",{hint:"Install git and ensure it is in your PATH.",shouldReport:!1});if(!l(e))throw new m(`Bundle not found: ${e}`,{hint:"Check the file path and try again.",shouldReport:!1});if(!t.skipBuild)await i(o);else{let A=Me.join(o,"dist");if(!l(A))throw new m("dist directory not found.",{hint:"Run without --skip-build to build the app first, or run `pnpm build` manually.",shouldReport:!1})}let h=await p(Me.join(Kh.tmpdir(),"cognite-diff-")),v=Me.join(h,"ours.zip"),S=Me.join(h,"ours"),C=Me.join(h,"theirs");try{if(await d(S,{recursive:!0}),await d(C,{recursive:!0}),await s(Me.join(o,"dist")).createZip(v),console.log(`
|
|
267
|
+
Extracting bundles...`),await a(v,S),await a(e,C),c.isIdentical(S,C)){console.log(`
|
|
268
268
|
Bundles are identical`);return}console.log(`
|
|
269
|
-
\u274C The local build at ${
|
|
269
|
+
\u274C The local build at ${Me.join(o,"dist")} differs from ${Me.basename(e)}.`);let x=f();(t.showStat!==void 0?t.showStat:x&&await y("Show stat summary?"))&&c.showStat(S,C),(t.showDiff!==void 0?t.showDiff:x&&await y("Show full diff?"))&&c.showDiff(S,C,{usePager:t.pager}),g(1)}finally{await u(h,{recursive:!0,force:!0})}}r(Yh,"handleDiff");function Uc(e){return e.command("diff <bundle>").description("Diff a trusted local build against an untrusted bundle zip").option("--skip-build","Skip rebuilding the app before diffing",!1).option("--no-pager","Disable the pager and print diff output directly").option("--show-stat","Show a compact stat summary when bundles differ").option("--show-diff","Show the full word diff when bundles differ").addHelpText("after",`
|
|
270
270
|
Builds the current source, packages it, then extracts both the local build
|
|
271
271
|
and the provided bundle to temporary directories and runs:
|
|
272
272
|
|
|
@@ -277,62 +277,62 @@ Exit code 0 means the bundles are identical; exit code 1 means they differ.
|
|
|
277
277
|
Examples:
|
|
278
278
|
npx @cognite/cli apps diff untrusted.zip
|
|
279
279
|
npx @cognite/cli apps diff untrusted.zip --skip-build
|
|
280
|
-
npx @cognite/cli apps diff untrusted.zip --show-stat --show-diff --no-pager`).action((t,n)=>
|
|
280
|
+
npx @cognite/cli apps diff untrusted.zip --show-stat --show-diff --no-pager`).action((t,n)=>Yh(t,n))}r(Uc,"registerDiffCommand");function zh(e,t){console.log(""),console.log(`Updating metadata for '${e}':`);for(let{field:n,remote:o,local:i}of t){let s=`${n}:`.padEnd(13);console.log(` ${s}"${o}" \u2192 "${i||"(none)"}"`)}}r(zh,"printMetadataDiff");async function qh(e,t=process.cwd(),n={}){let{loadEnvFile:o=H,loadAppConfig:i=k,buildApiClient:s=j,createMetadataClient:a=r(g=>new _(g),"createMetadataClient")}=n;o(t);let c=i(t);B(c);let l=e.interactive?await L(c,e):$(c.deployments,e.deployment),p=await s(l,{interactive:e.interactive,appId:c.externalId,orgHint:e.org,authMethod:e.authMethod,confirmActionTarget:e.confirmActionTarget,action:"metadata update"}),d=a(p),u;try{u=await d.getApp(c.externalId)}catch(g){throw g instanceof Ze?new Error(`App '${c.externalId}' is not deployed yet. Run \`npx @cognite/cli apps deploy\` first.`):g}let f={name:c.name,description:c.description||""},y=Io(u,f);if(y.length===0){console.log(""),console.log(`Metadata for '${c.externalId}' already matches the deployed app \u2014 nothing to update.`),console.log("Edit name/description in app.json to change them.");return}zh(c.externalId,y),await d.updateAppMetadata(c.externalId,c.name,c.description),console.log(""),console.log(`\u2705 Metadata for '${c.externalId}' updated`)}r(qh,"handleUpdateMetadata");function _c(e){let t=e.command("metadata").summary("Manage the deployed app's metadata").description("Manage the deployed app's metadata (name and description)."),n=t.command("update").description("Update the deployed app's name and description from app.json").argument("[path]","Path to the app folder (only `.` is currently supported)",".").option("-d, --deployment <target>","Deployment target from app.json (index or name)").option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)");return W().forEach(o=>n.addOption(o)),n.addHelpText("after",`
|
|
281
281
|
Examples:
|
|
282
282
|
npx @cognite/cli apps metadata update . Push name/description using env-var auth
|
|
283
|
-
npx @cognite/cli apps metadata update . --interactive Push using browser auth (no secrets needed)`).action((o,i)=>
|
|
283
|
+
npx @cognite/cli apps metadata update . --interactive Push using browser auth (no secrets needed)`).action((o,i)=>qh(i)),t}r(_c,"registerMetadataCommand");async function Jh(e,t,n){let o=await j(e,{interactive:t.interactive,appId:n.externalId,orgHint:t.org,authMethod:t.authMethod,confirmActionTarget:t.confirmActionTarget,action:"publish"});return new _(o)}r(Jh,"defaultBuildApiClient");async function Wh(e,t={}){let n=t.loadEnvFile??H,o=t.loadAppConfig??k,i=t.buildApiClient??Jh,s=t.discoverSignatures??Et,a=process.cwd();n(a);let c=o(a);B(c);let l=e.interactive?await L(c,e):$(c.deployments,e.deployment),p=await i(l,e,c),{externalId:d,versionTag:u}=c,f;try{f=await p.getVersion(d,u)}catch(g){throw g instanceof te?new Error(`Version ${u} of ${d} has not been deployed yet. Run \`npx @cognite/cli apps deploy\` first.`):g}if(f.alias==="ACTIVE"){console.log(` ${d} @ ${u} is already ACTIVE \u2014 nothing to do.`);return}if(f.lifecycleState==="PUBLISHED"){console.log(` ${d} @ ${u} is already PUBLISHED \u2014 nothing to do.`);return}if(f.lifecycleState==="DEPRECATED"||f.lifecycleState==="ARCHIVED")throw new Error(`Cannot publish ${d} @ ${u}: version is ${f.lifecycleState} (terminal).`);let y=s(ne(a,d,u));y.length>0&&await p.submitSignatures(d,u,y),await p.publishVersion(d,u),console.log(`\u2713 Published ${d} @ ${u} is now PUBLISHED`),console.log(""),console.log("Run `npx @cognite/cli apps activate .` to make it active.")}r(Wh,"handlePublish");function Nc(e){let t=e.command("publish").description("Publish the current app version (transition DRAFT \u2192 PUBLISHED)").argument("[path]","Path to the app folder (only `.` is currently supported)",".").option("-d, --deployment <target>","Deployment target from app.json (index or name)").option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)");return W().forEach(n=>t.addOption(n)),t.addHelpText("after",`
|
|
284
284
|
Examples:
|
|
285
285
|
npx @cognite/cli apps publish . Publish using env-var auth
|
|
286
|
-
npx @cognite/cli apps publish . --interactive Publish using browser auth (no secrets needed)`).action((n,o)=>
|
|
286
|
+
npx @cognite/cli apps publish . --interactive Publish using browser auth (no secrets needed)`).action((n,o)=>Wh(o))}r(Nc,"registerPublishCommand");import{spawnSync as Zh}from"child_process";import{mkdirSync as Xh}from"fs";import{join as Qh,resolve as jc}from"path";var ey=["localhost","local.cognite.ai","*.local.cognite.ai"],ty={info:r(e=>{process.stdout.write(`${e}
|
|
287
287
|
`)},"info"),error:r(e=>{process.stderr.write(`${e}
|
|
288
|
-
`)},"error")},
|
|
288
|
+
`)},"error")},ny={spawnSync:Zh,mkdirSync:Xh,logger:ty,getConfig:D};function oy(e){let t=e("mkcert",["-help"],{stdio:"ignore"});return t.status===0||t.status===1}r(oy,"hasMkcert");function ry({certDir:e,domains:t=ey,deps:n={}}={}){let o={...ny,...n},{spawnSync:i,mkdirSync:s,logger:a}=o,c=e??Qh(o.getConfig().home,"certificates","mkcert");if(!oy(i))throw a.error("Error: mkcert is not installed."),a.error("Install it with: brew install mkcert (macOS, Linux, WSL)"),a.error("On Windows: choco install mkcert (or scoop install mkcert)"),a.error("See https://github.com/FiloSottile/mkcert#installation for other methods."),new Error("mkcert is not installed");if(a.info("\u2139\uFE0F Installing mkcert root CA into your local trust store."),a.info(" This allows your browser to trust locally-generated certificates."),a.info(" You may be prompted for your system password."),i("mkcert",["-install"],{stdio:"inherit"}).status!==0)throw new Error("`mkcert -install` failed");s(c,{recursive:!0});let p=jc(c,"localhost.pem"),d=jc(c,"localhost-key.pem");if(i("mkcert",["-cert-file",p,"-key-file",d,...t],{stdio:"inherit"}).status!==0)throw new Error("mkcert failed to generate certificates");return a.info(""),a.info("Certificates generated:"),a.info(` cert: ${p}`),a.info(` key: ${d}`),{certFile:p,keyFile:d}}r(ry,"setupHttps");function iy(e){ry({certDir:e.certDir})}r(iy,"handleSetupHttps");function Hc(e){return e.command("setup-https").description("Generate trusted local HTTPS certificates via mkcert").option("--cert-dir <path>","Directory to write certs into (default: ~/.cognite-cli/certificates/mkcert)").addHelpText("after",`
|
|
289
289
|
Examples:
|
|
290
290
|
npx @cognite/cli@latest apps setup-https Generate certs in ~/.cognite-cli/certificates/mkcert
|
|
291
|
-
npx @cognite/cli@latest apps setup-https --cert-dir certs Use a custom directory`).action(t=>
|
|
291
|
+
npx @cognite/cli@latest apps setup-https --cert-dir certs Use a custom directory`).action(t=>iy(t))}r(Hc,"registerSetupHttpsCommand");import{existsSync as by,writeFileSync as xy}from"fs";import{basename as ky,dirname as Py,join as Ty,resolve as Ir}from"path";import{parseScope as Ry,signBundle as Iy,validateScopes as Dy}from"@cognite/app-sdk/codesigning";import{existsSync as Cy,readFileSync as Ay}from"fs";import{pbkdf2 as cy,randomBytes as ly}from"crypto";import{promisify as py}from"util";import{CompactEncrypt as dy,base64url as Bc,compactDecrypt as uy}from"jose";var sy=new TextEncoder,ay=new TextDecoder,kr={encode:r(e=>sy.encode(e),"encode"),decode:r(e=>ay.decode(e),"decode")};var my=py(cy),Rr=6e5,gy="sha512",Pr="PBKDF2-HMAC-SHA512",Tr=16,Hn="A256GCM",fy=32,Bn=2e6;async function Kc(e,t,n){return await my(e,t,n,fy,gy)}r(Kc,"deriveKey");async function Vc(e,t,n=Rr){if(!Number.isInteger(n)||n<1||n>Bn)throw new Error(`Invalid iterations: must be an integer between 1 and ${Bn}`);let o=ly(Tr),i=await Kc(t.expose(),o,n);return await new dy(kr.encode(e.expose())).setProtectedHeader({alg:"dir",enc:Hn,kdf:Pr,kdf_iter:n,kdf_salt:Bc.encode(o)}).encrypt(i)}r(Vc,"encryptStringAsJwe");async function Gc(e,t){let{plaintext:n}=await uy(e,async o=>{if(!e.length)throw new Error("Unexpected JWE empty value");let i=t.expose();if(i.length<15)throw new Error(`Invalid passphrase: must be at least ${15} characters`);if(o.alg!=="dir")throw new Error(`Unexpected JWE alg "${String(o.alg)}"; only "dir" is supported`);if(o.enc!==Hn)throw new Error(`Unexpected JWE enc "${String(o.enc)}"; only "${Hn}" is supported`);if(o.kdf!==Pr)throw new Error(`Unexpected KDF "${String(o.kdf)}"; only "${Pr}" is supported`);let s=Number(o.kdf_iter);if(!Number.isInteger(s)||s<1||s>Bn)throw new Error(`Invalid kdf_iter in JWE header: must be an integer between 1 and ${Bn}`);if(typeof o.kdf_salt!="string")throw new Error("Missing kdf_salt in JWE header");let a=Bc.decode(o.kdf_salt);if(a.length!==Tr)throw new Error(`Invalid kdf_salt length in JWE header: expected ${Tr} bytes, got ${a.length}`);return await Kc(i,a,s)},{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:[Hn]});return kr.decode(n)}r(Gc,"decryptJweAsString");function Yc(e){let t=e.trim();return t.startsWith("eyJ")&&t.split(".").length===5}r(Yc,"isJweCompact");import hy from"enquirer";async function yy(e){return hy.prompt(e)}r(yy,"defaultPrompt");async function zc(e,t={}){let{prompt:n=yy}=t,{passphrase:o}=await n({type:"password",name:"passphrase",message:e});return b.from(o)}r(zc,"promptPassphrase");import vy from"enquirer";import{statSync as Sy}from"fs";function qc(e,t=Sy){return e.map(n=>({key:n,mtime:t(n.publicKeyPath).mtimeMs})).sort((n,o)=>o.mtime-n.mtime).map(({key:n})=>n)}r(qc,"sortByMtime");async function wy(e){return vy.prompt(e)}r(wy,"defaultPrompt");async function Jc(e,t={}){if(e.length===1)return e[0];let{prompt:n=wy,sortByMtime:o=qc}=t,i=o(e),s=i[0],{choice:a}=await n({type:"select",name:"choice",message:"Select signing identity",choices:[{name:"latest",message:`Use latest: ${s.kid}`},{name:"pick",message:"Pick from list"}]});if(a==="latest")return s;if(a==="pick"){let{kid:c}=await n({type:"select",name:"kid",message:"Select signing identity",choices:i.map(p=>({name:p.kid,message:[p.kid,p.email,kn(p.source)].filter(Boolean).join(" \u2014 ")}))}),l=i.find(p=>p.kid===c);if(!l)throw new Error("No signing identity selected");return l}else throw new Error(`Unexpected choice: "${a}"`)}r(Jc,"promptSigningIdentity");function Ey(e){return{existsSync:e.existsSync??Cy,readFileSync:e.readFileSync??((t,n)=>Ay(t,n)),readKeyFromKeychain:e.readKeyFromKeychain??bn,readSigningKey:e.readSigningKey??xn,isOS:e.isOS??(t=>X(t)),decryptJweAsString:e.decryptJweAsString??Gc,discoverLocalKeys:e.discoverLocalKeys??Pn,keysDir:e.keysDir??D().keysDir,promptPassphrase:e.promptPassphrase??zc,promptSigningIdentity:e.promptSigningIdentity??Jc}}r(Ey,"resolveDeps");async function Wc(e,t={}){let n=Ey(t);if(e.keyPath){if(!n.existsSync(e.keyPath))throw new Error(`Key file not found: ${e.keyPath}`);if(!e.kid)throw new Error("--signing-identity <kid> is required when using --key");let s=n.readFileSync(e.keyPath,"utf-8").trim();if(Yc(s)){if(!e.interactive)throw new Error(`Key at ${e.keyPath} is passphrase-encrypted. Pass --interactive to enter the passphrase.`);let a=await n.promptPassphrase(`Passphrase for key ${e.kid}: `);return{privateKeyPem:b.from(await n.decryptJweAsString(s,a)),kid:e.kid}}return{privateKeyPem:b.from(s),kid:e.kid}}let o=await n.discoverLocalKeys(n.keysDir);if(o.length===0)throw new Error("No signing keys found. Run `cognite keys generate` or pass --key.");let i;if(e.kid)i=o.find(s=>s.kid===e.kid);else if(e.interactive)i=await n.promptSigningIdentity(o);else throw new Error("--signing-identity <kid> is required. Pass --interactive to select it interactively.");if(!i)throw new Error(`No key found with kid "${e.kid}"`);switch(i.source.kind){case"keychain":{let s=n.isOS("macos")?await n.readKeyFromKeychain(i.kid):await n.readSigningKey(i.kid);if(!s)throw new Error(`Key "${i.kid}" not found in OS credential store`);return{privateKeyPem:s,kid:i.kid}}case"encrypted-file":{if(!e.interactive)throw new Error(`Key "${i.kid}" is passphrase-encrypted. Pass --interactive to enter the passphrase, or store the key in macOS Keychain for non-interactive use.`);let s=await n.promptPassphrase(`Passphrase for key ${i.kid}: `);return{privateKeyPem:b.from(await n.decryptJweAsString(n.readFileSync(i.source.path,"utf-8"),s)),kid:i.kid}}case"public-only":throw new Error(`Key "${i.kid}" has no private key on this machine (public-only).`)}}r(Wc,"resolvePrivateKey");var $y=r(async(e,t,n,o,i)=>{let s=await j(e,{interactive:i.browserAuth??!1,appId:t,orgHint:i.org,authMethod:i.authMethod,confirmActionTarget:i.confirmActionTarget,action:"sign"});await new _(s).submitSignatures(t,n,o)},"defaultSubmitSignatures");function Oy(e){return{existsSync:e.existsSync??by,writeFileSync:e.writeFileSync??xy,createBundleStream:e.createBundleStream??Tn,signBundle:e.signBundle??Iy,parseScope:e.parseScope??Ry,validateScopes:e.validateScopes??Dy,loadAppConfig:e.loadAppConfig??k,resolvePrivateKey:e.resolvePrivateKey??(t=>Wc(t)),submitSignatures:e.submitSignatures??$y,discoverSignatures:e.discoverSignatures??Et}}r(Oy,"resolveDeps");async function Zc(e,t,n={},o=process.cwd()){let i=Oy(n),s=t.appid,a=t.appVersion,c=[],l=i.loadAppConfig(o);if(s=s??l.externalId,a=a??l.versionTag,t.scope&&t.scope.length>0?c=t.scope.map(i.parseScope):c=l.deployments.map(C=>({org:C.org,project:C.project})),!s)throw new Error("--appid is required (or set externalId in app.json)");if(!a)throw new Error("--app-version is required (or set versionTag in app.json)");let p=e?Ir(o,e):ne(o,s,a);if(!i.existsSync(p)){let C=e?"":" (default derived from app.json \u2014 pass [bundle] explicitly to override, or run `cognite apps deploy` first to populate .cognite-bundles/)";throw new Error(`Bundle not found: ${p}${C}`)}let d=i.validateScopes(c);if(d.length>0)throw new Error(`Invalid scopes:
|
|
292
292
|
${d.join(`
|
|
293
|
-
`)}`);let{privateKeyPem:u,kid:f}=await i.resolvePrivateKey({keyPath:t.key?
|
|
294
|
-
Payload:`,JSON.stringify(g.payload,null,2));let
|
|
295
|
-
To publish: npx @cognite/cli apps publish .`)}r(
|
|
293
|
+
`)}`);let{privateKeyPem:u,kid:f}=await i.resolvePrivateKey({keyPath:t.key?Ir(o,t.key):void 0,kid:t.signingIdentity,interactive:t.interactive}),y=i.createBundleStream(p),g=await i.signBundle({privateKeyPem:u.expose(),kid:f,appId:s,version:a,bundleStream:y,role:t.asCertifier?"certifier":"developer",scopes:c}),h=t.output?Ir(o,t.output):Ty(Py(p),`${ky(p)}.${t.asCertifier?"cert":"dev"}.sig`);i.writeFileSync(h,g.token,"utf-8"),console.log(`\u2705 Signed: ${h}`),console.log(` kid: ${g.kid}`),console.log(` bundle: ${g.payload.bundleSha256}`),console.log(` scopes: ${g.payload.scopes.map(C=>`${C.org}/${C.project}`).join(", ")}`),t.verbose&&console.log(`
|
|
294
|
+
Payload:`,JSON.stringify(g.payload,null,2));let v=Array.from(new Set([...i.discoverSignatures(p),g.token])),S=t.interactive?await L(l,{deployment:t.deployment,baseUrl:t.baseUrl,project:t.project,org:t.org}):$(l.deployments,t.deployment);await i.submitSignatures(S,s,a,v,t),console.log(`
|
|
295
|
+
To publish: npx @cognite/cli apps publish .`)}r(Zc,"handleSign");function Xc(e,t={}){let n=e.command("sign [bundle]").description("Sign an app bundle (defaults to .cognite-bundles/<app>-<version>.zip)").option("--key <path>","Private key PEM file path").option("-s, --signing-identity <kid>","Key ID for Keychain or file lookup").option("--appid <id>","Application ID (default: externalId from app.json)").option("-i, --identifier <id>","Alias for --appid").option("--app-version <version>","App version (default: versionTag from app.json)").option("--scope <org/project...>","Deployment scope(s) (default: deployments from app.json)").option("-r, --requirements <org/project...>","Alias for --scope").option("-o, --output <path>","Output file path (default: <bundle>.<dev|cert>.sig)").option("-v, --verbose","Display full payload after signing").option("--as-certifier","Counter-sign a developer signature as certifier").option("--interactive","Enable interactive prompts (key selection, passphrase, deployment target selection)",!1).option("--browser-auth","Use browser-based PKCE auth when submitting the signature",!1).option("-d, --deployment <target>","Deployment target from app.json (index or name; submit step only)").option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive or --browser-auth)");return W().forEach(o=>n.addOption(o)),n.action((o,i)=>{let s={...i,appid:i.identifier??i.appid,scope:i.requirements??i.scope};return Zc(o,s,t)})}r(Xc,"registerSignCommand");function Fy(e){return e.alias==="ACTIVE"?"ACTIVE":e.lifecycleState}r(Fy,"describeStatus");function Ly(e){if(e.length===0)return["Signatures: none stored"];let t=["Signatures:"];for(let n of e){let o=n.status==="VALID"?"\u2705":"\u274C",i=new Date(n.signatureIat).toISOString();t.push(` ${o} ${n.signerKid} (${n.signerRole}, signed ${i}) \u2014 ${n.status}`)}return t}r(Ly,"formatSignatures");async function My(e,t,n){let o=await j(e,{interactive:t.interactive,appId:n,orgHint:t.org,authMethod:t.authMethod});return new _(o)}r(My,"defaultBuildApiClient");async function Uy(e,t={}){let{loadEnvFile:n=H,loadAppConfig:o=k,getApiClient:i=My}=t,s=process.cwd();n(s);let a=o(s);B(a);let c=e.interactive?await L(a,e):$(a.deployments,e.deployment),l=await i(c,e,a.externalId);console.log(""),console.log(`App: ${a.name} (${a.externalId})`),console.log(`Version: ${a.versionTag} (local)`);try{let p=await l.getVersion(a.externalId,a.versionTag);console.log(`Status: ${Fy(p)}`);let d=await _y(l,a.externalId,a.versionTag);if(console.log(""),d==="endpoint-unavailable")console.log("Signatures: backend endpoint not available on this cluster yet");else for(let u of Ly(d))console.log(u);p.lifecycleState==="DRAFT"&&(console.log(""),console.log("Run `npx @cognite/cli apps publish .` to publish this version."))}catch(p){if(p instanceof te){console.log("Status: not deployed yet"),console.log(""),console.log("Run `npx @cognite/cli apps deploy` to upload this version.");return}throw p}}r(Uy,"handleStatus");async function _y(e,t,n){try{return await e.listSignatures(t,n)}catch(o){if(ae(o)&&o.status===404||o instanceof Error&&/status code: 404/.test(o.message))return"endpoint-unavailable";throw o}}r(_y,"fetchSignatures");function Qc(e){return e.command("status").description("Show the deployment status and signatures of the current app version").argument("[path]","Path to the app folder (only `.` is currently supported)",".").option("-d, --deployment <target>","Deployment target from app.json (index or name)").option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)").addOption(ur()).addHelpText("after",`
|
|
296
296
|
Examples:
|
|
297
297
|
npx @cognite/cli apps status . Status using env-var auth
|
|
298
|
-
npx @cognite/cli apps status . --interactive Status using browser auth (no secrets needed)`).action((n,o)=>
|
|
299
|
-
`))}</pre>`,c=
|
|
300
|
-
Press Enter to open the Zendesk form in your browser and reveal dist/submit/ in your file manager...`,()=>{t.close(),e()})})}r(
|
|
298
|
+
npx @cognite/cli apps status . --interactive Status using browser auth (no secrets needed)`).action((n,o)=>Uy(o))}r(Qc,"registerStatusCommand");import{execFileSync as Or}from"child_process";import $r from"fs";import xt from"path";import By from"readline";var el="https://cognite.zendesk.com",Ny="360001234312",jy="tf_360015295097",Hy="cognite_flows_certifications";function tl(e,t,n){let o=new URLSearchParams({ticket_form_id:Ny,tf_priority:"normal",tf_subject:e,[jy]:Hy,tf_description:t});return`${n}/hc/en-us/requests/new?${o}`}r(tl,"buildUrl");function nl(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}r(nl,"escapeHtml");function Dr(e){return e.map(nl).join("<br>")}r(Dr,"toHtml");function ol(e,t=el){let{appName:n,externalId:o,versionTag:i,archiveName:s,developerName:a,cdfProject:c,cdfCluster:l}=e,p=["Dear Cognite Platform Team,","","I would like to submit my Flows app for review and certification.","",`App name: ${n}`,`App external ID: ${o}`,`Version: ${i}`,c?`CDF project: ${c}`:void 0,l?`CDF cluster: ${l}`:void 0,"","`npx @cognite/cli apps submit` verified App-Brief.md,","code-review-report.md, and design-review-report.md are committed to git.","","Attached (all from dist/submit/):",`[ ] ${s??"src-<sha>.zip"} \u2014 source archive`,`[ ] ${o}-${i}.zip \u2014 deploy bundle`,"[ ] Screen recording of the application (required for design review)","","Best regards,",a??"[Your name]"];return tl(`App Review Request: ${n}`,Dr(p.filter(d=>d!==void 0)),t)}r(ol,"buildAppReviewUrl");function rl(e,t,n,o,i=el){let s=Dr(["Dear Cognite Platform Team,","","I would like to register my Flows app signing key for certified deployments.","",`Key ID (kid): ${e}`,`Developer email: ${t}`,`Expires: ${n}`,"","Please add the following entry to public_keys.yaml:"]),a=`<pre>${nl(o.replace(/\r\n/g,`
|
|
299
|
+
`))}</pre>`,c=Dr(["","Best Regards,","[Your name]","","(This registration request was generated by `npx @cognite/cli keys generate`.)"]);return tl(`Public Key Registration: ${t}`,`${s}<br>${a}${c}`,i)}r(rl,"buildKeyRegistrationUrl");function Ky(){return new Promise(e=>{let t=By.createInterface({input:process.stdin,output:process.stdout});t.question(`
|
|
300
|
+
Press Enter to open the Zendesk form in your browser and reveal dist/submit/ in your file manager...`,()=>{t.close(),e()})})}r(Ky,"defaultPressEnter");var Vy=[{pattern:"App-Brief.md",label:"App-Brief.md",skill:"flows-app-brief"},{pattern:"reviews/code-review/*/code-review-report.md",label:"reviews/code-review/feedback-round-<N>/code-review-report.md",skill:"flows-code-review"},{pattern:"reviews/design-review/*/design-review-report.md",label:"reviews/design-review/feedback-round-<N>/design-review-report.md",skill:"flows-design-review"}];function Gy(e){let t=Vy.filter(({pattern:n})=>Or("git",["-C",e,"ls-files","--",n],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().length===0);if(t.length>0){let n=t.map(({label:o,skill:i})=>` ${o} \u2192 /${i}`);throw new Error(`Certification files are missing or not committed. Run the required skills in Claude Code first:
|
|
301
301
|
|
|
302
302
|
`+n.join(`
|
|
303
|
-
`)+"\n\nAfter running the skills, commit the generated files and re-run `apps submit`.")}}r(
|
|
303
|
+
`)+"\n\nAfter running the skills, commit the generated files and re-run `apps submit`.")}}r(Gy,"assertArtifactsCommitted");var Yy="\u2197 Launched your browser \u2014 look for a new tab with the Zendesk form.";async function zy(e=process.cwd(),t={}){let{openInBrowser:n=Sn,revealInFileManager:o=va,pressEnter:i=Ky,isInteractive:s=r(()=>process.stdout.isTTY===!0,"isInteractive")}=t;if(Ae(),!An(e))throw new Error("Not a git repository. Run this command from your app's root directory.");H(e);let a=k(e);B(a),Gy(e);let c=xt.join(e,"dist","submit");$r.mkdirSync(c,{recursive:!0});let l=Or("git",["-C",e,"rev-parse","--short","HEAD"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(Or("git",["-C",e,"status","--porcelain"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().length>0)throw new Error(`Working tree has uncommitted changes. Commit or stash them before submitting for certification.
|
|
304
304
|
|
|
305
|
-
The source archive must exactly match the committed code so reviewers can verify what they receive.`);let d=`src-${l}.zip`,u=
|
|
305
|
+
The source archive must exactly match the committed code so reviewers can verify what they receive.`);let d=`src-${l}.zip`,u=xt.join(c,d);await new Ie(xt.join(e,"dist")).createSourceArchive(u);let y=`${a.externalId}-${a.versionTag}.zip`,g=xt.join(e,".cognite-bundles",y),h=!1;$r.existsSync(g)&&($r.copyFileSync(g,xt.join(c,y)),h=!0);let v=ol({appName:a.name,externalId:a.externalId,versionTag:a.versionTag,archiveName:d,developerName:Ta(),cdfProject:a.deployments[0].project,cdfCluster:a.deployments[0].baseUrl});if(console.log(`
|
|
306
306
|
\u2705 Certification package ready: dist/submit/`),console.log(` ${d} \u2014 source archive (commit ${l})`),console.log(h?` ${y} \u2014 deploy bundle`:" \u26A0 Deploy bundle missing \u2014 run `apps deploy` to generate it, then re-run submit"),console.log(" \u2190 add your screen recording to this folder"),console.log(`
|
|
307
|
-
Attach all files from dist/submit/ to the Zendesk ticket.`),s()){await i();let S=n(
|
|
308
|
-
${
|
|
309
|
-
\u{1F517} ${
|
|
307
|
+
Attach all files from dist/submit/ to the Zendesk ticket.`),s()){await i();let S=n(v);o(u),S&&(console.log(`
|
|
308
|
+
${Yy}`),console.log(" If nothing opened, submit here:"),console.log(` \u{1F517} ${v}`))}else console.log(`
|
|
309
|
+
\u{1F517} ${v}`)}r(zy,"handleSubmit");function il(e){return e.command("submit").description("Package source and open a pre-filled Zendesk form for app certification submission").addHelpText("after",`
|
|
310
310
|
Examples:
|
|
311
|
-
npx @cognite/cli apps submit Package source, open browser + file manager`).action(()=>
|
|
311
|
+
npx @cognite/cli apps submit Package source, open browser + file manager`).action(()=>zy())}r(il,"registerSubmitCommand");function sl(e){let t=e.command("apps").description("Manage Fusion Custom Apps \u2014 create, deploy, and manage version lifecycle");return bc(t),$c(t),Uc(t),Qc(t),_c(t),Nc(t),sc(t),xc(t),kc(t),Hc(t),il(t),Cc(t),Xc(t),rc(t),t}r(sl,"registerAppsCommand");import Fr from"enquirer";function qy(e){return{loadAppConfig:e.loadAppConfig??k,cwd:e.cwd??(()=>process.cwd()),loginForSession:e.loginForSession??(t=>ji(t)),writeSession:e.writeSession??(t=>jt(t)),readSessionMetadata:e.readSessionMetadata??(()=>ke()),clearSession:e.clearSession??(()=>Ht()),promptSelectOrg:e.promptSelectOrg??Jy,promptOrg:e.promptOrg??Wy,promptConfirm:e.promptConfirm??Zy,logger:e.logger??console,platform:e.platform??process.platform}}r(qy,"resolveDeps");async function Jy(e){let{selected:t}=await Fr.prompt({type:"select",name:"selected",message:"Select the organization to sign in to",choices:e});return t}r(Jy,"defaultPromptSelectOrg");async function Wy(){let{org:e}=await Fr.prompt({type:"input",name:"org",message:"Enter your organization name",validate:r(t=>t.trim().length>0?!0:"Organization name is required","validate")});return e.trim()}r(Wy,"defaultPromptOrg");async function Zy(e){let{confirmed:t}=await Fr.prompt({type:"confirm",name:"confirmed",message:e,initial:!1});return t}r(Zy,"defaultPromptConfirm");function Xy(e){if(e.port===void 0)return;let t=Number(e.port);if(!Vt(t))throw new m(Gt(e.port));return t}r(Xy,"resolvePort");async function Qy(e,t){let{logger:n,promptSelectOrg:o,promptOrg:i}=t;if(e.org)return e.org;let s=eS(t);if(s){let a=[...new Set(s.deployments.map(c=>c.org))];return a.length===1?(n.log(`Resolved organization from app.json: ${a[0]}`),a[0]):o(a)}return i()}r(Qy,"resolveOrg");function eS(e){let{loadAppConfig:t,cwd:n}=e;try{return t(n())}catch(o){let i=o instanceof Error?o.message:String(o);if(/No app\.json found/.test(i))return null;throw o}}r(eS,"tryLoadAppConfig");function tS(e){switch(e){case"darwin":return"macOS Keychain";case"win32":return"Windows Credential Manager";default:return"Secret Service (libsecret / KWallet)"}}r(tS,"keyringBackendLabel");function nS(e){let t=e,n=new Set;for(;t!=null&&!n.has(t)&&(n.add(t),typeof t=="object");){if("code"in t&&t.code==="ERR_DLOPEN_FAILED")return!0;let o="message"in t&&typeof t.message=="string"?t.message:null;if(o&&/cannot find native binding/i.test(o))return!0;t="cause"in t?t.cause:void 0}return!1}r(nS,"isNativeModuleLoadError");async function oS(e,t){let{logger:n,loginForSession:o,writeSession:i,readSessionMetadata:s,clearSession:a,promptConfirm:c,platform:l}=t,p=Xy(e),d=s();if(d){if(!e.force&&je(d)!=="EXPIRED"&&!await c(`A session for organization "${d.org}" already exists. Replace it?`)){n.error("Aborted.");return}await a()}let u=await Qy(e,t),f=await o({org:u,port:p});try{await i(f)}catch(g){if(nS(g)){let h=l==="win32"?"Install the Microsoft Visual C++ Redistributable from https://learn.microsoft.com/en-us/cpp/windows/latest-supported-vc-redist and restart your terminal, then run `cognite auth login` again.":"Ensure the required system libraries are installed for your platform, then run `cognite auth login` again.";throw new m("The keyring native module could not be loaded \u2014 tokens were not persisted.",{hint:h,cause:g})}throw new m("Login succeeded but tokens could not be saved to the credential store.",{hint:`Ensure a credential store (${tS(l)}) is available and unlocked, then run \`cognite auth login\` again.`,cause:g})}let y=P(process.stdout);n.log(""),n.log(`${y.green("\u2713")} Signed in to organization ${f.org}`)}r(oS,"handleLogin");function rS(e){return e.commands.find(t=>t.name()==="auth")??e.command("auth").description("Manage your persisted CDF login session")}r(rS,"getOrCreateAuthGroup");function al(e,t={}){let n=qy(t);rS(e).command("login").description("Sign in via the browser and persist a refreshable session").option("--org <org>","Organization to sign in to (resolved from app.json or prompted when omitted)").option("--force","Replace an existing session without prompting").option("--port <port>",`Pin the local callback port for the OAuth redirect (${ut}). Defaults to 3000.`).action(i=>oS(i,n))}r(al,"registerAuthLoginCommand");function iS(e){return{readSession:e.readSession??(()=>pt()),readSessionMetadata:e.readSessionMetadata??(()=>ke()),clearSession:e.clearSession??(()=>Ht()),revokeRefreshToken:e.revokeRefreshToken??((t,n)=>Hi(t,{},n)),logger:e.logger??console}}r(iS,"resolveDeps");async function sS(e){let{readSessionMetadata:t,readSession:n,clearSession:o,revokeRefreshToken:i,logger:s}=e,a=null;try{a=t()}catch{await o(),s.log("Cleared corrupt session.");return}if(!a){s.log("No active session.");return}let c;try{c=(await n())?.refreshToken}catch{}if(await o(),c)try{await i(c,a?.org)}catch{s.error("Logged out locally, but revoking the token at the identity provider failed. It may remain valid until it expires naturally."),s.log("Logged out.");return}s.log("Logged out.")}r(sS,"handleLogout");function aS(e){return e.commands.find(t=>t.name()==="auth")??e.command("auth").description("Manage your persisted CDF login session")}r(aS,"getOrCreateAuthGroup");function cl(e,t={}){let n=iS(t);aS(e).command("logout").description("Revoke and remove the persisted session").action(()=>sS(n))}r(cl,"registerAuthLogoutCommand");function cS(e){return{ensureFreshSession:e.ensureFreshSession??We,fetchUserInfo:e.fetchUserInfo??(t=>qt(t)),logger:e.logger??console}}r(cS,"resolveDeps");function lS(e){return e.email??e.preferredUsername??e.name??e.sub}r(lS,"describeUser");var pS="(unknown cluster)";function dS(e,t){if(e.length===0)return[" - Projects: (none)"];let n=new Map;for(let i of e){let s=i.cluster??pS,a=n.get(s);a?a.push(i):n.set(s,[i])}let o=[` - Projects (${e.length}):`];for(let[i,s]of n){o.push(` ${t.dim(i)}`);for(let a of s){let c=a.isDefault?` ${t.green("[default]")}`:"";o.push(` ${a.name}${c}`)}}return o}r(dS,"formatProjects");function uS(){switch(process.platform){case"darwin":return"macOS Keychain";case"win32":return"Windows Credential Manager";default:return"Secret Service (libsecret / KWallet)"}}r(uS,"keyringBackendLabel");async function mS(e){let{ensureFreshSession:t,fetchUserInfo:n,logger:o}=e,i;try{i=await t()}catch(s){if(s instanceof He){o.error(" Session expired. Run `npx @cognite/cli auth login` to sign in again."),process.exitCode=1;return}throw s}if(!i){o.error("Not signed in. Run `npx @cognite/cli auth login` to start a session."),process.exitCode=1;return}o.log(i.org);try{let s=await n(i),a=P(process.stdout);o.log(` ${a.green("\u2713")} Signed in as ${lS(s)}`);for(let c of dS(s.projects,a))o.log(c);o.log(` - Token storage: ${uS()}`)}catch(s){if(s instanceof Je&&s.kind==="unreachable"){let a=new URL(Pe(process.env,i.org)).host;o.error(` \u2717 Couldn't reach Cognite (${a}): ${s.message}`),o.error(" Check your network connection, or run `npx @cognite/cli auth login` to sign in again.")}else{let a=s instanceof Error?s.message:String(s);o.error(` \u2717 ${a}`),o.error(" Run `npx @cognite/cli auth login` to sign in again.")}process.exitCode=1}}r(mS,"handleStatus");function gS(e){return e.commands.find(t=>t.name()==="auth")??e.command("auth").description("Manage your persisted CDF login session")}r(gS,"getOrCreateAuthGroup");function ll(e,t={}){let n=cS(t);gS(e).command("status").alias("whoami").description("Show the active session, verified against the identity provider").action(()=>mS(n))}r(ll,"registerAuthStatusCommand");import{existsSync as SS,mkdirSync as vS,writeFileSync as wS}from"fs";import{dirname as Ur,join as kt}from"path";import{generateSigningKeyPair as CS}from"@cognite/app-sdk/codesigning";import AS from"open";function pl(e,t){let n=e.getUTCFullYear(),o=e.getUTCMonth()+t,i=new Date(Date.UTC(n,o+1,0)).getUTCDate(),s=Math.min(e.getUTCDate(),i);return new Date(Date.UTC(n,o,s))}r(pl,"addMonthsClamped");function Lr(e){return e.toISOString().slice(0,10)}r(Lr,"formatIsoDate");function dl(e=new Date){return Lr(e)}r(dl,"todayIso");var Kn=Uint8Array.from([48,42,48,5,6,3,43,101,112,3,33,0]),ul=32,ml=44,gl=60,fS="services/app-hosting/src/kotlin/com/cognite/apphosting/signing/public_keys.yaml";function hS(e){let t=e.replace(/-----BEGIN [^-]+-----/g,"").replace(/-----END [^-]+-----/g,"").replace(/\s+/g,"");if(t.length!==ml&&t.length!==gl)throw new Error(`Unexpected Ed25519 public key base64 length: got ${t.length} chars, expected ${ml} (raw) or ${gl} (X.509-wrapped)`);let n=Buffer.from(t,"base64");if(n.length===Kn.length+ul&&n.subarray(0,Kn.length).equals(Kn))return n.subarray(Kn.length).toString("base64");if(n.length===ul)return n.toString("base64");throw new Error(`Unexpected Ed25519 public key length: got ${n.length} bytes, expected 32 (raw) or 44 (X.509-wrapped)`)}r(hS,"pemBodyOneLine");function Mr(e,t=rt,n=new Date){let o=fl(e.issuedAt??dl(n)),i=fl(e.expires),s=hS(e.publicKeyPem),a=" ",c=r((p,d)=>`${a}${t.cyan(p)}${t.dim(":")} ${d}
|
|
312
312
|
`,"kv"),l="";return l+=`
|
|
313
|
-
${t.bold("Add this entry to")} ${t.magenta(
|
|
313
|
+
${t.bold("Add this entry to")} ${t.magenta(fS)} ${t.bold("under")} ${t.cyan("publicKeys:")}
|
|
314
314
|
|
|
315
315
|
`,l+=` ${t.dim("-")} ${t.cyan("kid")}${t.dim(":")} ${t.green(e.kid)}
|
|
316
|
-
`,l+=c("publicKey",t.green(s)),l+=c("email",t.yellow(e.email)),l+=c("roles",`${t.dim("[")}${t.yellow("developer")}${t.dim("]")}`),l+=c("issuedAt",t.green(o)),l+=c("expiresAt",t.green(i)),l+=c("revokedAt",t.dim("null")),l}r(
|
|
316
|
+
`,l+=c("publicKey",t.green(s)),l+=c("email",t.yellow(e.email)),l+=c("roles",`${t.dim("[")}${t.yellow("developer")}${t.dim("]")}`),l+=c("issuedAt",t.green(o)),l+=c("expiresAt",t.green(i)),l+=c("revokedAt",t.dim("null")),l}r(Mr,"renderRegistryYamlBlock");function fl(e){let t=e.trim();if(/^\d{4}-\d{2}-\d{2}$/.test(t))return`${t}T00:00:00Z`;let n=new Date(t);if(Number.isNaN(n.getTime()))throw new Error(`Invalid date '${e}': expected YYYY-MM-DD or ISO-8601 instant`);return n.toISOString()}r(fl,"toIsoInstant");import yS from"clipboardy";function hl(e){return yS.write(e)}r(hl,"copyToClipboard");var yl=12;function ES(e){return{writeFileSync:e.writeFileSync??wS,mkdirSync:e.mkdirSync??vS,existsSync:e.existsSync??SS,generateSigningKeyPair:e.generateSigningKeyPair??CS,encryptStringAsJwe:e.encryptStringAsJwe??Vc,storeKeyInKeychain:e.storeKeyInKeychain??Ja,storeSigningKey:e.storeSigningKey??ec,isOS:e.isOS??(t=>X(t)),promptKid:e.promptKid??Ba,promptEmail:e.promptEmail??Va,promptPassphrase:e.promptPassphrase??Ga,promptConfirmOverwrite:e.promptConfirmOverwrite??Ya,discoverLocalKeys:e.discoverLocalKeys??(()=>Pn()),promptZendeskAction:e.promptZendeskAction??Ka,openUrl:e.openUrl??(t=>AS(t)),copyToClipboard:e.copyToClipboard??hl}}r(ES,"resolveDeps");function vl(e,t={}){let n=ES(t),o=e.command("keys").description("Manage code signing keys");o.command("generate").description("Generate an Ed25519 keypair for code signing").option("-o, --output <path>","Encrypted private key output path (forces file storage even on macOS)").option("--no-keychain",`Skip the OS credential store (macOS Keychain / Windows Credential Manager) and write a passphrase-encrypted private key under ${D().keysDir} instead`).option("--email <address>","Email address for the registry entry; skips the interactive prompt").option("--kid <identifier>","Signing identity name for the registry (e.g. jsmith-dev-001); skips the interactive prompt").option("--force","Overwrite an existing key without prompting for confirmation").option("--copy-link","Copy the Zendesk registration link to the clipboard without prompting").option("--interactive","Prompt for any required flags that are not supplied",!1).action(i=>PS(i,n)),o.command("list").description("List local signing identities and their storage location").action(()=>bS(n))}r(vl,"registerKeysCommand");async function bS(e){let t=await e.discoverLocalKeys();if(t.length===0){process.stdout.write(`No signing identities found.
|
|
317
317
|
`),process.stdout.write(`Run \`cognite keys generate\` to create one (storage: ${D().keysDir}).
|
|
318
|
-
`);return}let n=["KID","SOURCE","EMAIL"],o=t.map(a=>[a.kid,
|
|
318
|
+
`);return}let n=["KID","SOURCE","EMAIL"],o=t.map(a=>[a.kid,kn(a.source),a.email??"\u2014"]),i=hn(n,o),s=r(a=>wt(a,i),"fmt");process.stdout.write(`${s(n)}
|
|
319
319
|
`);for(let a of o)process.stdout.write(`${s(a)}
|
|
320
|
-
`)}r(
|
|
321
|
-
`))}let
|
|
322
|
-
`);return}let x;e.email!==void 0?x=
|
|
320
|
+
`)}r(bS,"handleList");function Sl(e,t,n){let o=kt(D().keysDir,`${e}${Le}`);return n.mkdirSync(Ur(o),{recursive:!0}),n.writeFileSync(o,t),o}r(Sl,"writePublicKey");async function xS(e,t,n,o,i,{force:s=!1}={}){let a=o??kt(D().keysDir,`${e}${pr}`);if(i.mkdirSync(Ur(a),{recursive:!0}),!s&&i.existsSync(a))throw new Error(`Refusing to overwrite existing key at ${a}. Delete it first if you really want to regenerate: rm ${a}`);let c=await i.encryptStringAsJwe(t,n);return i.writeFileSync(a,c,{mode:384}),a}r(xS,"writeEncryptedPrivateKey");function kS(e,t,n){let o=[];if(e.kid===void 0)o.push("--kid <identifier> is required. Pass --interactive to enter it interactively.");else try{let i=Ge(e.kid),s=kt(D().keysDir,`${i}${Le}`);n(s)&&!e.force&&o.push(`Key "${i}" already exists. Use --force to overwrite without prompting.`)}catch(i){o.push(i instanceof Error?i.message:String(i))}if(e.email===void 0)o.push("--email <address> is required. Pass --interactive to enter it interactively.");else try{tt(e.email,"--email")}catch(i){o.push(i instanceof Error?i.message:String(i))}return t||o.push("A passphrase is required for encrypted key storage. Pass --interactive to enter it interactively."),o}r(kS,"collectNonInteractiveErrors");async function PS(e,t,n=new Date){let{isOS:o,existsSync:i,mkdirSync:s,writeFileSync:a,generateSigningKeyPair:c,storeKeyInKeychain:l,storeSigningKey:p,promptKid:d,promptEmail:u,promptPassphrase:f,promptConfirmOverwrite:y}=t,g=e.interactive??!1,h=e.keychain!==!1&&!e.output&&(o("macos")||o("windows"));if(!g){let V=kS(e,h,i);if(V.length>0)throw new Error(V.join(`
|
|
321
|
+
`))}let v=Lr(pl(n,yl)),S;e.kid!==void 0?S=Ge(e.kid):S=await d();let C=kt(D().keysDir,`${S}${Le}`),A=i(C);if(A&&!e.force&&!await y(S)){process.stderr.write(`Aborted.
|
|
322
|
+
`);return}let x;e.email!==void 0?x=tt(e.email,"--email"):x=await u();let M=h?{kind:"keychain"}:{kind:"file",passphrase:await f()};process.stderr.write(`
|
|
323
323
|
Generating Ed25519 keypair...
|
|
324
324
|
|
|
325
|
-
`);let{privateKeyPem:K,publicKeyPem:R}=await c(S),Y=b.from(K);if(M.kind==="keychain"){o("macos")?await l(S,Y):await p(S,Y);let V=
|
|
325
|
+
`);let{privateKeyPem:K,publicKeyPem:R}=await c(S),Y=b.from(K);if(M.kind==="keychain"){o("macos")?await l(S,Y):await p(S,Y);let V=Sl(S,R,t);process.stderr.write(`Public key: ${V}
|
|
326
326
|
`),process.stderr.write(`Private key: OS credential store (account: ${S})
|
|
327
|
-
`)}else{let V=await
|
|
328
|
-
`),process.stderr.write(`Private key: ${V} (JWE, AES-256-GCM, PBKDF2-SHA512 x${
|
|
329
|
-
`)}let le=
|
|
327
|
+
`)}else{let V=await xS(S,Y,M.passphrase,e.output,t,{force:A}),Yn=Sl(S,R,t);process.stderr.write(`Public key: ${Yn}
|
|
328
|
+
`),process.stderr.write(`Private key: ${V} (JWE, AES-256-GCM, PBKDF2-SHA512 x${Rr.toLocaleString()})
|
|
329
|
+
`)}let le=kt(D().keysDir,`${S}${dr}`);s(Ur(le),{recursive:!0}),a(le,JSON.stringify({email:x}));let I=P(process.stderr);process.stderr.write(`
|
|
330
330
|
Signing identity (kid): ${I.green(S)}
|
|
331
|
-
`),process.stderr.write(`Expires: ${
|
|
332
|
-
`);let oe={kid:S,publicKeyPem:R,email:x,expires:
|
|
331
|
+
`),process.stderr.write(`Expires: ${v} (${yl} months from today)
|
|
332
|
+
`);let oe={kid:S,publicKeyPem:R,email:x,expires:v};g||(process.stderr.write(`
|
|
333
333
|
Key registration data:
|
|
334
334
|
|
|
335
|
-
`),process.stderr.write(
|
|
335
|
+
`),process.stderr.write(Mr(oe,I,n)));let F=rl(S,x,v,Mr(oe,rt,n));process.stderr.write(`
|
|
336
336
|
${I.bold("Next:")}
|
|
337
337
|
`),process.stderr.write(` 1. Register your signing key \u2014 submit this pre-filled Zendesk request:
|
|
338
338
|
`);let re;if(e.copyLink?re="clipboard":g?re=await t.promptZendeskAction():re=null,re==="browser")try{await t.openUrl(F),process.stderr.write(` Opening in browser...
|
|
@@ -343,8 +343,8 @@ ${I.bold("Next:")}
|
|
|
343
343
|
`);process.stderr.write(`
|
|
344
344
|
2. Once your key is approved, sign your Dune app:
|
|
345
345
|
`),process.stderr.write(` ${I.cyan(`cognite sign -s ${S}`)}
|
|
346
|
-
`)}r(
|
|
347
|
-
`);return
|
|
348
|
-
${
|
|
349
|
-
`)},"onOutdated")})});
|
|
350
|
-
Cancelled.`),process.exit(130)),(!(e instanceof m)||e.shouldReport)&&(await
|
|
346
|
+
`)}r(PS,"handleGenerate");function wl(e){return sl(e),al(e),cl(e),ll(e),vl(e),e}r(wl,"registerCommands");import{homedir as TS,userInfo as RS}from"os";var IS=TS(),DS=(()=>{try{return RS().username}catch{return""}})();function nt(e,t=IS){if(!t||t==="/")return e;let n=e.replaceAll(t,"~"),o=t.replaceAll("\\","/");return o!==t&&(n=n.replaceAll(o,"~")),n=n.replace(/(?<![A-Za-z0-9_])[A-Za-z]:[/\\]Users[/\\][^\s/\\]+(?=[/\\]|$)/g,"~"),n=n.replace(/(?<![A-Za-z0-9_])\/(?:Users|home)\/[^\s/]+(?=[/\\]|$)/g,"~"),n}r(nt,"redactHomedir");function $S(e,t=DS){if(!t||t.length<3)return e;let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp("(^|[\\/\\s:])"+n+"(?=[\\/\\s:.@]|$)","g");return e.replace(o,"$1<user>")}r($S,"redactUsername");var OS=/(['"]?(?:access_token|accessToken|client_secret|clientSecret|refresh_token|refreshToken|password|token|passphrase)['"]?\s*:\s*)(?:"(?:\\.|[^\\"])*"|'(?:\\.|[^\\'])*')/gi;function Cl(e){return e.replace(OS,(t,n)=>{let o=t[n.length];return`${n}${o}[REDACTED]${o}`})}r(Cl,"redactCredentials");var FS=1e3,LS="https://0a118cb02e3be57b1838bcfb5783a2bf@o4508040730968064.ingest.de.sentry.io/4510719268290640",MS={captureError:r(async()=>{},"captureError"),flush:r(async()=>{},"flush")};function US(e){return e.packageName&&e.cliVersion?`${e.packageName}@${e.cliVersion}`:e.cliVersion??"unknown"}r(US,"buildRelease");var _S="192.0.2.0";function NS(e){return e?.map(t=>({...t,...t.filename!==void 0&&{filename:nt(t.filename)},...t.abs_path!==void 0&&{abs_path:nt(t.abs_path)},...t.module!==void 0&&{module:nt(t.module)}}))}r(NS,"scrubStackFrames");function Vn(e){return Cl($S(nt(e)))}r(Vn,"redactPii");function jS(e){let t={...e.user,email:void 0,username:void 0,ip_address:_S,id:void 0},n=e.exception?.values?.map(s=>({...s,value:s.value!==void 0?Vn(s.value):s.value,...s.stacktrace!==void 0&&{stacktrace:{...s.stacktrace,frames:NS(s.stacktrace.frames)}}})),o=e.contexts?.cli,i=o!==void 0?Object.fromEntries(Object.entries(o).map(([s,a])=>[s,typeof a=="string"?Vn(a):a])):void 0;return{...e,message:e.message!==void 0?Vn(e.message):e.message,...typeof e.culprit=="string"&&{culprit:Vn(e.culprit)},user:t,server_name:void 0,...n!==void 0&&{exception:{...e.exception,values:n}},...i!==void 0&&{contexts:{...e.contexts,cli:i}}}}r(jS,"scrubPii");function Al(e={}){let t=e.env??process.env;if(So(t))return MS;let n=US(e),o="production",i=null,s=null;function a(){return{dsn:LS,release:n,environment:o,defaultIntegrations:!1,integrations:[],sendDefaultPii:!1,enableLogs:!1,initialScope:{tags:{component:"cli",applicationId:dt},contexts:{cli:{applicationId:dt,node:process.version,platform:process.platform}}},beforeSend:jS}}r(a,"buildInitOptions");async function c(){return i||(s||(s=(async()=>{try{let l=e.sdk??await import("@sentry/node");return l.init(a()),i=l,l}catch{return null}})()),s)}return r(c,"ensureSdk"),{async captureError(l,p){try{let d=await c();if(!d)return;d.captureException(l,HS(l,p))}catch{}},async flush(l=FS){try{if(!i)return;await i.flush(l)}catch{}}}}r(Al,"createErrorReporter");function HS(e,t){let n={level:"fatal"},o={applicationId:dt,node:process.version,platform:process.platform};if(t?.command&&(n.tags={command:t.command},o.command=t.command),ue(e)&&(e.hint&&(o.hint=e.hint),e.helpUrl&&(o.helpUrl=e.helpUrl),o.shouldReport=e.shouldReport),n.contexts={cli:o},Tt(e)&&(n.contexts.http={url:e.requestUrl!==void 0?nt(e.requestUrl):void 0,status_code:e.httpStatusCode},e.responseBody!==void 0)){let i=typeof e.responseBody=="string"?e.responseBody:JSON.stringify(e.responseBody);n.extra={responseBody:Cl(nt(i))}}return n}r(HS,"buildCaptureContext");import{mkdirSync as BS,readFileSync as KS,writeFileSync as VS}from"fs";import{homedir as GS}from"os";import{resolve as Gn}from"path";import{debuglog as YS}from"util";import{lt as zS,parse as El}from"semver";var qS="https://registry.npmjs.org/@cognite/cli/latest",JS=1500,bl="upgrade-check.json",xl=Gn(process.env.XDG_CACHE_HOME||Gn(GS(),".cache"),"@cognite","cli"),_r=YS("cognite-flows");function WS(e,t){return!e||!t||!El(e)||!El(t)?!1:zS(e,t)}r(WS,"isOutdated");async function ZS({timeout:e=JS,registryUrl:t=qS,fetchImpl:n=globalThis.fetch}={}){if(typeof n!="function")return null;try{let o=await n(t,{signal:AbortSignal.timeout(e)});if(!o?.ok)return null;let i=await o.json();return typeof i?.version=="string"?i.version:null}catch(o){return _r("fetchLatestVersion failed (%s): %O",t,o),null}}r(ZS,"fetchLatestVersion");function XS(e=xl,t=864e5){try{let n=KS(Gn(e,bl),"utf-8"),o=JSON.parse(n);return typeof o.latest!="string"||typeof o.fetchedAt!="number"||Date.now()-o.fetchedAt>t?null:{latest:o.latest,fetchedAt:o.fetchedAt}}catch(n){return _r("readUpgradeCheckCache failed (%s): %O",e,n),null}}r(XS,"readUpgradeCheckCache");function QS(e,t){try{BS(e,{recursive:!0});let n={latest:t,fetchedAt:Date.now()};VS(Gn(e,bl),JSON.stringify(n))}catch(n){_r("writeUpgradeCheckCache failed (%s): %O",e,n)}}r(QS,"writeUpgradeCheckCache");async function ev({cacheDir:e=xl,...t}={}){let n=await ZS(t);n&&QS(e,n)}r(ev,"startBackgroundUpgradeCheck");function kl(e,{onOutdated:t,cacheDir:n,...o}={}){let i=XS(n);if(i){WS(e,i.latest)&&t?.(e,i.latest);return}ev({cacheDir:n,...o})}r(kl,"preActionUpgradeCheck");import{default as BF,chalkStderr as Pl}from"chalk";function Tl(e,t){let n=[`\u26A0 Update available: ${e} -> ${t}`," Run npx @cognite/cli@latest"],o=Math.max(...n.map(c=>[...c].length))+2,i="\u2500".repeat(o),s=r(c=>`\u2502 ${c}${" ".repeat(o-1-[...c].length)}\u2502`,"pad"),a=[`\u250C${i}\u2510`,...n.map(s),`\u2514${i}\u2518`].join(`
|
|
347
|
+
`);return Pl.bold.yellow(a)}r(Tl,"formatUpgradeWarning");function ov(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&e.code==="DEP0040"}r(ov,"isDep0040Warning");var jr=process,rv=jr.emit.bind(jr);jr.emit=function(e,...t){return e==="warning"&&ov(t[0])?!1:rv(e,...t)};Ot();var ot=new nv;ot.name("cognite").description("Build and deploy React apps and Atlas agents to Cognite Data Fusion").version("1.11.0").showHelpAfterError().configureOutput({writeOut:r(e=>tv(1,e),"writeOut")});ot.hook("preAction",()=>{kl("1.11.0",{onOutdated:r((e,t)=>{console.warn(`
|
|
348
|
+
${Tl(e,t)}
|
|
349
|
+
`)},"onOutdated")})});wl(ot);var Hr=Bt({packageName:"@cognite/cli",cliVersion:"1.11.0"}),Rl=Al({packageName:"@cognite/cli",cliVersion:"1.11.0"});oi(ot,Hr);ka(ot,{telemetry:Hr});var Nr=process.argv.slice(2);ot.parseAsync(Nr,{from:"user"}).catch(async e=>{await ri(Hr,Nr),ao(e)&&(console.error(`
|
|
350
|
+
Cancelled.`),process.exit(130)),(!(e instanceof m)||e.shouldReport)&&(await Rl.captureError(e,{command:so(Nr)}),await Rl.flush());let t=e instanceof Error?e.message:String(e);console.error(`\u274C ${t}`),e instanceof m&&(e.hint||e.helpUrl)&&(console.error(""),e.hint&&console.error(`\u{1F4A1} ${e.hint}`),e.helpUrl&&console.error(`\u{1F4DA} ${e.helpUrl}`)),process.exit(1)});
|