langwatch 0.35.0 → 0.36.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-KH2GOLFO.mjs → chunk-AEFZHF6V.mjs} +2 -2
- package/dist/{chunk-KH2GOLFO.mjs.map → chunk-AEFZHF6V.mjs.map} +1 -1
- package/dist/{chunk-EDWIKCYX.js → chunk-BT76Q2SR.js} +2 -2
- package/dist/{chunk-EDWIKCYX.js.map → chunk-BT76Q2SR.js.map} +1 -1
- package/dist/{chunk-XMAFHMLS.mjs → chunk-G5VAIDUJ.mjs} +2 -2
- package/dist/{chunk-53AMPF5E.js → chunk-N7WBYSM6.js} +12 -12
- package/dist/{chunk-53AMPF5E.js.map → chunk-N7WBYSM6.js.map} +1 -1
- package/dist/cli/bundle.js +6 -6
- package/dist/index.js +24 -24
- package/dist/index.mjs +2 -2
- package/dist/observability-sdk/index.js +2 -2
- package/dist/observability-sdk/index.mjs +1 -1
- package/dist/observability-sdk/setup/node/index.js +3 -3
- package/dist/observability-sdk/setup/node/index.mjs +2 -2
- package/package.json +1 -1
- /package/dist/{chunk-XMAFHMLS.mjs.map → chunk-G5VAIDUJ.mjs.map} +0 -0
package/dist/cli/bundle.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var Cx=Object.create;var $a=Object.defineProperty,Rx=Object.defineProperties,Ix=Object.getOwnPropertyDescriptor,Px=Object.getOwnPropertyDescriptors,Lx=Object.getOwnPropertyNames,Oa=Object.getOwnPropertySymbols,Ox=Object.getPrototypeOf,Fi=Object.prototype.hasOwnProperty,Tp=Object.prototype.propertyIsEnumerable;var kp=(t,e,n)=>e in t?$a(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,x=(t,e)=>{for(var n in e||(e={}))Fi.call(e,n)&&kp(t,n,e[n]);if(Oa)for(var n of Oa(e))Tp.call(e,n)&&kp(t,n,e[n]);return t},$=(t,e)=>Rx(t,Px(e));var mo=(t,e)=>{var n={};for(var o in t)Fi.call(t,o)&&e.indexOf(o)<0&&(n[o]=t[o]);if(t!=null&&Oa)for(var o of Oa(t))e.indexOf(o)<0&&Tp.call(t,o)&&(n[o]=t[o]);return n};var h=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(o){throw n=[o],o}};var k=(t,e)=>{for(var n in e)$a(t,n,{get:e[n],enumerable:!0})},$x=(t,e,n,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Lx(e))!Fi.call(t,r)&&r!==n&&$a(t,r,{get:()=>e[r],enumerable:!(o=Ix(e,r))||o.enumerable});return t};var b=(t,e,n)=>(n=t!=null?Cx(Ox(t)):{},$x(e||!t||!t.__esModule?$a(n,"default",{value:t,enumerable:!0}):n,t));var Na,Gi=h(()=>{Na="0.
|
|
2
|
+
"use strict";var Cx=Object.create;var $a=Object.defineProperty,Rx=Object.defineProperties,Ix=Object.getOwnPropertyDescriptor,Px=Object.getOwnPropertyDescriptors,Lx=Object.getOwnPropertyNames,Oa=Object.getOwnPropertySymbols,Ox=Object.getPrototypeOf,Fi=Object.prototype.hasOwnProperty,Tp=Object.prototype.propertyIsEnumerable;var kp=(t,e,n)=>e in t?$a(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,x=(t,e)=>{for(var n in e||(e={}))Fi.call(e,n)&&kp(t,n,e[n]);if(Oa)for(var n of Oa(e))Tp.call(e,n)&&kp(t,n,e[n]);return t},$=(t,e)=>Rx(t,Px(e));var mo=(t,e)=>{var n={};for(var o in t)Fi.call(t,o)&&e.indexOf(o)<0&&(n[o]=t[o]);if(t!=null&&Oa)for(var o of Oa(t))e.indexOf(o)<0&&Tp.call(t,o)&&(n[o]=t[o]);return n};var h=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(o){throw n=[o],o}};var k=(t,e)=>{for(var n in e)$a(t,n,{get:e[n],enumerable:!0})},$x=(t,e,n,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Lx(e))!Fi.call(t,r)&&r!==n&&$a(t,r,{get:()=>e[r],enumerable:!(o=Ix(e,r))||o.enumerable});return t};var b=(t,e,n)=>(n=t!=null?Cx(Ox(t)):{},$x(e||!t||!t.__esModule?$a(n,"default",{value:t,enumerable:!0}):n,t));var Na,Gi=h(()=>{Na="0.36.0"});function Dx(t){var n;let e=globalThis;t&&(process.env.NODE_ENV==="test"?e=t:console.warn("[LangWatch Observability] overriding detectRuntime is only supported when running in NODE_ENV=test"));try{return"Deno"in e&&typeof e.Deno=="object"&&e.Deno&&"version"in e.Deno&&typeof e.Deno.version=="object"?"deno":"Bun"in e&&typeof e.Bun=="object"&&e.Bun&&"version"in e.Bun&&typeof e.Bun.version=="string"?"bun":"process"in e&&typeof e.process=="object"&&e.process&&typeof e.process.versions=="object"&&typeof e.process.versions.node=="string"?"node":typeof((n=e.window)==null?void 0:n.document)!="undefined"&&e===e.window?"web":"unknown"}catch(o){return console.warn("[LangWatch Observability] Failed to detect runtime",o),"unknown"}}var Da,Rp,Ip=h(()=>{"use strict";Rp=()=>(Da!=null||(Da=Dx()),Da)});var ja,Ma,Ua,Fa,zt,Fe,ct=h(()=>{"use strict";Gi();Ip();ja=Rp,Ma="langwatch-observability-sdk",Ua="langwatch-client-sdk",Fa="typescript",zt=Na,Fe="https://app.langwatch.ai"});function Pp(){var o;let t=(o=process.env.LANGWATCH_ENDPOINT)!=null?o:"https://app.langwatch.ai",e=process.env.LANGWATCH_GATEWAY_URL;return{gateway_url:e!=null?e:/^https?:\/\/(localhost|127\.0\.0\.1)/.test(t)?"http://localhost:5563":"https://gateway.langwatch.ai",control_plane_url:t}}function Mx(t){return!!t&&t.startsWith(jx)}function go(){let t=process.env.LANGWATCH_CLI_CONFIG;return t||Ga.join(Lp.homedir(),".langwatch","config.json")}function re(){let t=go();if(!Rt.existsSync(t))return Pp();try{let e=Rt.readFileSync(t,"utf8"),n=JSON.parse(e),o=x(x({},Pp()),n);return o.default_personal_vk&&!Mx(o.default_personal_vk.secret)&&delete o.default_personal_vk,o}catch(e){throw new Error(`Failed to parse ${t}: ${e.message}`)}}function Le(t){let e=go(),n=Ga.dirname(e);Rt.mkdirSync(n,{recursive:!0,mode:448});let o=e+".tmp";Rt.writeFileSync(o,JSON.stringify(t,null,2),{mode:384}),Rt.renameSync(o,e)}function Wi(){let t=go();try{Rt.unlinkSync(t)}catch(e){if(e.code!=="ENOENT")throw e}}function Ae(t){return!!t&&!!t.access_token}var Rt,Lp,Ga,jx,Ge=h(()=>{"use strict";Rt=b(require("fs")),Lp=b(require("os")),Ga=b(require("path"));jx="vk-lw-"});function Wo(t={}){if(t.flag)return{url:Wa(t.flag),source:"flag"};let e=process.env.LANGWATCH_ENDPOINT;if(e&&e.trim()!=="")return{url:Wa(e),source:"env"};let n=t.cfg;if(n===void 0)try{n=re()}catch(r){n=void 0}let o=n==null?void 0:n.control_plane_url;return o&&o!==Fe?{url:Wa(o),source:"config"}:{url:Wa(Fe),source:"default"}}function V(t={}){return Wo(t).url}function Wa(t){return t.replace(/\/+$/,"")}var ae=h(()=>{"use strict";ct();Ge()});function Fr(){return process.platform!=="win32"}function Fx(){let t=process.env.LANGWATCH_DAEMON_DIR;if(t)return t;let n=`langwatch-${typeof process.getuid=="function"?process.getuid():0}`,o=process.env.XDG_RUNTIME_DIR;if(o&&o.trim()!=="")return ho.join(o,n);let r=Ha.homedir();if(r!==""){let a=ho.join(r,".langwatch","run",n);if(Buffer.byteLength(a,"utf8")+Ux<=Np)return a}return ho.join(Ha.tmpdir(),n)}function Ho(t=process.env){var l,m;let e=V(),n=(l=t.LANGWATCH_API_KEY)!=null?l:"",o=typeof process.getuid=="function"?process.getuid():0,r=(m=t.LANGWATCH_CLI_CONFIG)!=null?m:"",s=$p.createHash("sha256").update(`${e}\0${n}\0${o}\0${r}`).digest("hex"),i=Fx(),c=ho.join(i,`${s.slice(0,16)}.sock`);return{fingerprint:s,socketPath:c,socketDir:i,endpoint:e}}function Ka(t,e){try{let n=Yt.statSync(e);return`${t}+${n.size}-${Math.trunc(n.mtimeMs)}`}catch(n){return t}}function Dp(t,e){var n,o;return{LANGWATCH_ENDPOINT:e.endpoint,LANGWATCH_API_KEY:(n=t.LANGWATCH_API_KEY)!=null?n:"",LANGWATCH_CLI_CONFIG:(o=t.LANGWATCH_CLI_CONFIG)!=null?o:""}}function qa(t){return Buffer.byteLength(t,"utf8")<=Np}function Op(t){return(t&63)!==0}function _n(t){if(typeof process.getuid!="function")return null;let e=process.getuid(),n;try{n=Yt.lstatSync(ho.dirname(t))}catch(r){return"socket-dir-missing"}if(!n.isDirectory())return"socket-dir-not-a-directory";if(n.uid!==e)return"socket-dir-foreign-owner";if(Op(n.mode))return"socket-dir-loose-mode";let o;try{o=Yt.lstatSync(t)}catch(r){return"socket-missing"}return o.isSocket()?o.uid!==e?"socket-foreign-owner":Op(o.mode)?"socket-loose-mode":null:"socket-not-a-socket"}function Va(t){Yt.mkdirSync(t,{recursive:!0,mode:448});let e=Yt.lstatSync(t);if(!e.isDirectory())throw new Gn(t,"not a directory");if(typeof process.getuid=="function"&&e.uid!==process.getuid())throw new Gn(t,"owned by another user");Yt.chmodSync(t,448)}function jp(t){Yt.chmodSync(t,384)}var $p,Yt,Ha,ho,Np,Ux,Gn,fo=h(()=>{"use strict";$p=b(require("crypto")),Yt=b(require("fs")),Ha=b(require("os")),ho=b(require("path"));ae();Np=100,Ux=22;Gn=class extends Error{constructor(n,o){super(`refusing to use socket directory ${n}: ${o}`);this.socketDir=n;this.problem=o;this.name="UntrustedSocketDirError"}}});function wo(t){return JSON.stringify(t)+`
|
|
3
3
|
`}var yo,Hi=h(()=>{"use strict";yo=class{constructor(e=64*1024*1024){this.maxLineBytes=e;this.buffer=""}push(e){if(this.buffer+=typeof e=="string"?e:e.toString("utf8"),this.buffer.length>this.maxLineBytes)throw this.buffer="",new Error("daemon protocol: frame exceeded maximum size");let n=[],o=this.buffer.indexOf(`
|
|
4
4
|
`);for(;o!==-1;){let r=this.buffer.slice(0,o);this.buffer=this.buffer.slice(o+1),r.trim()!==""&&n.push(JSON.parse(r)),o=this.buffer.indexOf(`
|
|
5
5
|
`)}return n}}});async function Mp(t){var a,s,i;let e=(a=t.stdout)!=null?a:process.stdout,n=(s=t.stderr)!=null?s:process.stderr,o=(i=t.maxBufferBytes)!=null?i:Wx,r=_n(t.socketPath);return r?{served:!1,reason:r}:new Promise(c=>{let l=Ba.connect(t.socketPath),m=new yo,f=[],A=0,T=!1,C=!1,E,M=!1,N=H=>{l.destroyed||l.write(wo(H))},_=()=>{for(let H of f)(H.stream==="stdout"?e:n).write(H.data);f.length=0,A=0},L=H=>{C||(C=!0,E&&clearTimeout(E),F(),l.destroy(),c(H))},O=()=>{M=!0,N({t:"cancel"}),setTimeout(()=>{T&&_(),L({served:!0,exitCode:130})},500).unref()},F=()=>{process.removeListener("SIGINT",O),process.removeListener("SIGTERM",O)};l.setTimeout(Gx,()=>{T||L({served:!1,reason:"connect-timeout"})}),l.on("error",H=>{var D,U;if(T){n.write(`langwatch: daemon connection lost mid-command (${(D=H.code)!=null?D:H.message})
|
|
@@ -72,7 +72,7 @@ ${n.end}
|
|
|
72
72
|
`+a}return Ln.writeFileSync(o,c),o}function Us(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function el(t,e={begin:Fs,end:Gs}){let n=_o(t),o;try{o=Ln.readFileSync(n,"utf8")}catch(a){return!1}let r=new RegExp(`\\n?${Us(e.begin)}[\\s\\S]*?${Us(e.end)}\\n?`,"m");return r.test(o)?(Ln.writeFileSync(n,o.replace(r,"")),!0):!1}async function Jc(t,e){if(!process.stdin.isTTY)return"skip";let n=ug.createInterface({input:process.stdin,output:process.stdout}),o=await new Promise(a=>{n.question(`Install env vars to ${t} so that next time the plain \`${e}\` command keeps capturing telemetry data? [Y/n/never] `,s=>a(s))});n.close();let r=o.trim().toLowerCase();return r===""||r==="y"||r==="yes"?"yes":r==="never"?"never":"no"}async function mg({cfg:t,tool:e,vars:n}){var c,l;if(t.shell_rc_preference==="skip"||process.env.OTEL_EXPORTER_OTLP_ENDPOINT||Object.keys(n).length===0)return;let o=Ms(e);if(o){if(rg(o,n))return;console.log();let m=await Jc(o.displayPath,e);if(m==="skip"||m==="no")return;if(m==="never"){Xc(t);return}try{sg(o,n),console.log(To.default.green(` \u2713 Installed langwatch telemetry exports to ${o.displayPath}`))}catch(f){console.log(To.default.yellow(` ! Couldn't write to ${o.displayPath}: ${f.message}`))}return}if(e==="codex"){let m=mn();if(Bc(m))return;let f=n.OTEL_EXPORTER_OTLP_ENDPOINT,A=$k(n.OTEL_EXPORTER_OTLP_HEADERS);if(!f||!A)return;console.log();let T=await Jc(ko(),e);if(T==="skip"||T==="no")return;if(T==="never"){Xc(t);return}try{sr({endpoint:$s(f),ingestionToken:A,environment:(l=(c=t.organization)==null?void 0:c.slug)!=null?l:"langwatch"},{persistAuthHeader:!0}),console.log(To.default.green(` \u2713 Installed langwatch telemetry exports to ${ko()}`))}catch(C){console.log(To.default.yellow(` ! Couldn't write to ${ko()}: ${C.message}`))}return}let r=Pk();if(!r)return;let a=Qc(e);if(Ws({shell:r,requiredKeys:[n.OTEL_EXPORTER_OTLP_ENDPOINT].filter(Boolean),markers:a}))return;let s=_o(r);console.log();let i=await Jc(s,e);if(!(i==="skip"||i==="no")){if(i==="never"){Xc(t);return}try{let m=Ok(r,Lk(e,n,r),a);console.log(To.default.green(` \u2713 Installed a scoped \`${e}\` telemetry wrapper in ${m}`))}catch(m){console.log(To.default.yellow(` ! Couldn't write to ${s}: ${m.message}`))}}}function Xc(t){t.shell_rc_preference="skip";try{Le(t)}catch(e){}}function $k(t){if(!t)return null;let e=/Bearer\s+(\S+)/.exec(t);return e?e[1]:null}var Ln,dg,ir,ug,To,Fs,Gs,Zc,tl=h(()=>{"use strict";Ln=b(require("fs")),dg=b(require("os")),ir=b(require("path")),ug=b(require("readline")),To=b(require("chalk"));ca();Yc();Ge();Ks();Fs="# >>> langwatch begin >>>",Gs="# <<< langwatch end <<<",Zc={begin:Fs,end:Gs}});function Nk(){let t=process.env.XDG_CONFIG_HOME,e=t&&t.length>0?t:qs.default.join(gg.default.homedir(),".config");return qs.default.join(e,"opencode","opencode.jsonc")}function Dk(t){return t.replace(/\/\*[\s\S]*?\*\//g,"").replace(/^\s*\/\/.*$/gm,"")}function hg(t={}){var s,i;let e=(s=t.filePath)!=null?s:Nk();if(!cr.default.existsSync(e)){cr.default.mkdirSync(qs.default.dirname(e),{recursive:!0});let c=JSON.stringify({$schema:"https://opencode.ai/config.json",experimental:{openTelemetry:!0}},null,2)+`
|
|
73
73
|
`;return cr.default.writeFileSync(e,c,{mode:384}),{action:"created",path:e}}let n=cr.default.readFileSync(e,"utf8"),o;try{o=JSON.parse(Dk(n))}catch(c){o={$schema:"https://opencode.ai/config.json"}}let r=(i=o.experimental)!=null?i:{},a=r.openTelemetry;return a===!0?{action:"unchanged",path:e}:a===!1?{action:"disabled-by-user",path:e}:(o.experimental=$(x({},r),{openTelemetry:!0}),cr.default.writeFileSync(e,JSON.stringify(o,null,2)+`
|
|
74
74
|
`,{mode:384}),{action:"updated",path:e})}var cr,gg,qs,fg=h(()=>{"use strict";cr=b(require("fs")),gg=b(require("os")),qs=b(require("path"))});function jk(){var e;let t=(e=process.env.HOME)!=null?e:yg.homedir();return wg.join(t,".gemini","settings.json")}function Mk(t){return t.replace(/\/\*[\s\S]*?\*\//g,"").replace(/^\s*\/\/.*$/gm,"")}function vg(t={}){var s,i;let e=(s=t.filePath)!=null?s:jk(),n=(i=t.writeLine)!=null?i:(c=>process.stderr.write(c+`
|
|
75
|
-
`));if(!Vs.existsSync(e))return{action:"no-settings",warned:!1};let o;try{o=Vs.readFileSync(e,"utf8")}catch(c){return{action:"parse-error",warned:!1}}let r;try{r=JSON.parse(Mk(o))}catch(c){return{action:"parse-error",warned:!1}}return Uk(r)==="gemini-oauth"?(n('warning: ~/.gemini/settings.json has security.auth.selectedType="gemini-oauth". gemini-cli 0.46 will use cached OAuth and ignore GOOGLE_API_KEY / GEMINI_API_KEY, so this `langwatch gemini` call will bypass the gateway. To route through langwatch: edit ~/.gemini/settings.json and set security.auth.selectedType to "gemini-api-key".'),{action:"oauth-selected",warned:!0}):{action:"api-key-selected",warned:!1}}function Uk(t){if(t===null||typeof t!="object")return null;let e=t.security;if(e===null||typeof e!="object")return null;let n=e.auth;if(n===null||typeof n!="object")return null;let o=n.selectedType;return typeof o=="string"?o:null}var Vs,yg,wg,bg=h(()=>{"use strict";Vs=b(require("fs")),yg=b(require("os")),wg=b(require("path"))});async function nl(t,e,n,o=[],r){var L,O,F,H,D,U,J;let a=(L=t.tool_mode)==null?void 0:L[e],s=!!((O=t.default_personal_vk)!=null&&O.secret),i=or(e,t.tool_policies);if(!i.allowVk&&!i.allowOtelDirect)throw new me(403,"tool_disabled",`Tool '${e}' is disabled in the platform policy (both gateway and direct OTLP paths off). Ask your org admin to enable allow_vk or allow_otel_direct.`);let c,l=r!=null?r:a==="gateway"?"gateway":a==="ingestion"?"ingestion":s?"gateway":"ingestion";if(l==="gateway"&&!i.allowVk&&(l="ingestion",c=`${Ot()} gateway path is disabled for ${e} by your org admin; using direct OTLP ingestion instead.`),l==="ingestion"&&!i.allowOtelDirect&&(l="gateway",c=`${Ot()} direct OTLP ingestion is disabled for ${e} by your org admin; routing through the gateway instead.`),l==="gateway"){if(e==="gemini"&&vg(),e==="codex"){let z=Ym({gatewayUrl:t.gateway_url,envKey:"OPENAI_API_KEY"});return{mode:l,vars:n,clears:o,codexConfigPath:z.path,codexProfilePath:z.profilePath,extraArgs:["--profile",z.profile],notice:c}}return{mode:l,vars:n,clears:o,notice:c}}let m=Fk[e];if(!m)return{mode:"gateway",vars:n,clears:o,notice:c};if(!i.allowOtelDirect)throw new me(403,"otel_direct_disabled",`Direct OTLP ingestion is disabled for '${e}' by your org admin. Ask them to enable allow_otel_direct, or run with the gateway path.`);let f=(F=t.default_personal_ingest_keys)==null?void 0:F[m],A,T,C,E;if(f!=null&&f.secret){let z=As(f.secret),K=!0;try{(await ks(t)).find(te=>te.sourceType===m&&te.lookupId===z)||(K=!1)}catch(W){}if(K)A=f.secret,T=f.prefix,C=`${t.control_plane_url.replace(/\/+$/,"")}/api/otel`,E=!1;else{let W=await na(t,m);A=W.token,T=W.prefix,C=W.endpoint,E=!0}}else{let z=await na(t,m);A=z.token,T=z.prefix,C=z.endpoint,E=!0}let M=Sg(e,C,A),N;e==="codex"&&(N=sr({endpoint:$s(C),ingestionToken:A,environment:(D=(H=t.organization)==null?void 0:H.slug)!=null?D:"langwatch"}).path),e==="opencode"&&hg();let _=$(x({},t),{tool_mode:$(x({},(U=t.tool_mode)!=null?U:{}),{[e]:"ingestion"})});E&&(_.default_personal_ingest_keys=$(x({},(J=t.default_personal_ingest_keys)!=null?J:{}),{[m]:{secret:A,prefix:T}}));try{Le(_)}catch(z){}return{mode:l,vars:M,codexConfigPath:N,newKeyMinted:E,notice:c,endpoint:C,ingestionToken:A}}function xg(t){return Object.keys(Sg(t,"",""))}function Sg(t,e,n){let o={OTEL_EXPORTER_OTLP_ENDPOINT:e,OTEL_EXPORTER_OTLP_HEADERS:`Authorization=Bearer ${n}`};switch(t){case"claude":return $(x({CLAUDE_CODE_ENABLE_TELEMETRY:"1",OTEL_TRACES_EXPORTER:"otlp",OTEL_LOGS_EXPORTER:"otlp",OTEL_METRICS_EXPORTER:"otlp",OTEL_EXPORTER_OTLP_PROTOCOL:"http/json",OTEL_LOG_USER_PROMPTS:"1",OTEL_LOG_TOOL_DETAILS:"1",OTEL_LOG_TOOL_CONTENT:"1",OTEL_LOG_RAW_API_BODIES:"1"},o),{OTEL_RESOURCE_ATTRIBUTES:"service.name=claude-code"});case"codex":return $(x({OTEL_TRACES_EXPORTER:"otlp",OTEL_EXPORTER_OTLP_PROTOCOL:"http/json"},o),{OTEL_RESOURCE_ATTRIBUTES:"service.name=codex"});case"gemini":return $(x({GEMINI_TELEMETRY_ENABLED:"true",GEMINI_TELEMETRY_TARGET:"local",GEMINI_TELEMETRY_USE_COLLECTOR:"true",GEMINI_TELEMETRY_TRACES_ENABLED:"true",GEMINI_TELEMETRY_OTLP_PROTOCOL:"http",GEMINI_TELEMETRY_OTLP_ENDPOINT:e,GEMINI_TELEMETRY_LOG_PROMPTS:"true",OTEL_TRACES_EXPORTER:"otlp",OTEL_EXPORTER_OTLP_PROTOCOL:"http/json"},o),{OTEL_RESOURCE_ATTRIBUTES:"service.name=gemini-cli"});case"opencode":return $(x({OTEL_TRACES_EXPORTER:"otlp",OTEL_LOGS_EXPORTER:"otlp",OTEL_METRICS_EXPORTER:"otlp",OTEL_EXPORTER_OTLP_PROTOCOL:"http/json"},o),{OTEL_RESOURCE_ATTRIBUTES:"service.name=opencode"});default:return o}}var Fk,ol=h(()=>{"use strict";ca();fg();Ps();Ge();dn();bg();Ls();Fk={claude:"claude_code",codex:"codex",gemini:"gemini",opencode:"opencode"}});function Bs(t,e){return t.length>e?`${t.slice(0,e)}\u2026[truncated]`:t}function Gk(t){if(!Array.isArray(t))return"";let e=[];for(let n of t)if(n&&typeof n=="object"){let o=n.text,r=n.output_text;typeof o=="string"?e.push(o):typeof r=="string"&&e.push(r)}return e.join("").trim()}function Wk(t){if(typeof t=="string")return t;if(t&&typeof t=="object"){let e=t.output;if(typeof e=="string")return e;try{return JSON.stringify(t)}catch(n){return""}}return typeof t=="number"||typeof t=="boolean"?String(t):""}function Hk(t){var r;let e=t.map(a=>typeof a.content=="string"&&a.content.length>3e4?$(x({},a),{content:Bs(a.content,3e4)}):a),n=()=>JSON.stringify(e).length,o=0;for(;n()>12e4&&o<e.length;){if(((r=e[o])==null?void 0:r.role)==="system"){o++;continue}e.splice(o,1)}return e}function Ag(t){return typeof t.call_id=="string"&&t.call_id?t.call_id:typeof t.id=="string"&&t.id?t.id:null}function kg(t){let e=new rl;for(let n of t.split(`
|
|
75
|
+
`));if(!Vs.existsSync(e))return{action:"no-settings",warned:!1};let o;try{o=Vs.readFileSync(e,"utf8")}catch(c){return{action:"parse-error",warned:!1}}let r;try{r=JSON.parse(Mk(o))}catch(c){return{action:"parse-error",warned:!1}}return Uk(r)==="gemini-oauth"?(n('warning: ~/.gemini/settings.json has security.auth.selectedType="gemini-oauth". gemini-cli 0.46 will use cached OAuth and ignore GOOGLE_API_KEY / GEMINI_API_KEY, so this `langwatch gemini` call will bypass the gateway. To route through langwatch: edit ~/.gemini/settings.json and set security.auth.selectedType to "gemini-api-key".'),{action:"oauth-selected",warned:!0}):{action:"api-key-selected",warned:!1}}function Uk(t){if(t===null||typeof t!="object")return null;let e=t.security;if(e===null||typeof e!="object")return null;let n=e.auth;if(n===null||typeof n!="object")return null;let o=n.selectedType;return typeof o=="string"?o:null}var Vs,yg,wg,bg=h(()=>{"use strict";Vs=b(require("fs")),yg=b(require("os")),wg=b(require("path"))});async function nl(t,e,n,o=[],r){var L,O,F,H,D,U,J;let a=(L=t.tool_mode)==null?void 0:L[e],s=!!((O=t.default_personal_vk)!=null&&O.secret),i=or(e,t.tool_policies);if(!i.allowVk&&!i.allowOtelDirect)throw new me(403,"tool_disabled",`Tool '${e}' is disabled in the platform policy (both gateway and direct OTLP paths off). Ask your org admin to enable allow_vk or allow_otel_direct.`);let c,l=r!=null?r:a==="gateway"?"gateway":a==="ingestion"?"ingestion":s?"gateway":"ingestion";if(l==="gateway"&&!i.allowVk&&(l="ingestion",c=`${Ot()} gateway path is disabled for ${e} by your org admin; using direct OTLP ingestion instead.`),l==="ingestion"&&!i.allowOtelDirect&&(l="gateway",c=`${Ot()} direct OTLP ingestion is disabled for ${e} by your org admin; routing through the gateway instead.`),l==="gateway"){if(e==="gemini"&&vg(),e==="codex"){let z=Ym({gatewayUrl:t.gateway_url,envKey:"OPENAI_API_KEY"});return{mode:l,vars:n,clears:o,codexConfigPath:z.path,codexProfilePath:z.profilePath,extraArgs:["--profile",z.profile],notice:c}}return{mode:l,vars:n,clears:o,notice:c}}let m=Fk[e];if(!m)return{mode:"gateway",vars:n,clears:o,notice:c};if(!i.allowOtelDirect)throw new me(403,"otel_direct_disabled",`Direct OTLP ingestion is disabled for '${e}' by your org admin. Ask them to enable allow_otel_direct, or run with the gateway path.`);let f=(F=t.default_personal_ingest_keys)==null?void 0:F[m],A,T,C,E;if(f!=null&&f.secret){let z=As(f.secret),K=!0;try{(await ks(t)).find(te=>te.sourceType===m&&te.lookupId===z)||(K=!1)}catch(W){}if(K)A=f.secret,T=f.prefix,C=`${t.control_plane_url.replace(/\/+$/,"")}/api/otel`,E=!1;else{let W=await na(t,m);A=W.token,T=W.prefix,C=W.endpoint,E=!0}}else{let z=await na(t,m);A=z.token,T=z.prefix,C=z.endpoint,E=!0}let M=Sg(e,C,A),N;e==="codex"&&(N=sr({endpoint:$s(C),ingestionToken:A,environment:(D=(H=t.organization)==null?void 0:H.slug)!=null?D:"langwatch"}).path),e==="opencode"&&hg();let _=$(x({},t),{tool_mode:$(x({},(U=t.tool_mode)!=null?U:{}),{[e]:"ingestion"})});E&&(_.default_personal_ingest_keys=$(x({},(J=t.default_personal_ingest_keys)!=null?J:{}),{[m]:{secret:A,prefix:T}}));try{Le(_)}catch(z){}return{mode:l,vars:M,codexConfigPath:N,newKeyMinted:E,notice:c,endpoint:C,ingestionToken:A}}function xg(t){return Object.keys(Sg(t,"",""))}function Sg(t,e,n){let o={OTEL_EXPORTER_OTLP_ENDPOINT:e,OTEL_EXPORTER_OTLP_HEADERS:`Authorization=Bearer ${n}`};switch(t){case"claude":return $(x({CLAUDE_CODE_ENABLE_TELEMETRY:"1",CLAUDE_CODE_ENHANCED_TELEMETRY_BETA:"1",OTEL_TRACES_EXPORTER:"otlp",OTEL_LOGS_EXPORTER:"otlp",OTEL_METRICS_EXPORTER:"otlp",OTEL_EXPORTER_OTLP_PROTOCOL:"http/json",OTEL_LOG_USER_PROMPTS:"1",OTEL_LOG_TOOL_DETAILS:"1",OTEL_LOG_TOOL_CONTENT:"1",OTEL_LOG_RAW_API_BODIES:"1"},o),{OTEL_RESOURCE_ATTRIBUTES:"service.name=claude-code"});case"codex":return $(x({OTEL_TRACES_EXPORTER:"otlp",OTEL_EXPORTER_OTLP_PROTOCOL:"http/json"},o),{OTEL_RESOURCE_ATTRIBUTES:"service.name=codex"});case"gemini":return $(x({GEMINI_TELEMETRY_ENABLED:"true",GEMINI_TELEMETRY_TARGET:"local",GEMINI_TELEMETRY_USE_COLLECTOR:"true",GEMINI_TELEMETRY_TRACES_ENABLED:"true",GEMINI_TELEMETRY_OTLP_PROTOCOL:"http",GEMINI_TELEMETRY_OTLP_ENDPOINT:e,GEMINI_TELEMETRY_LOG_PROMPTS:"true",OTEL_TRACES_EXPORTER:"otlp",OTEL_EXPORTER_OTLP_PROTOCOL:"http/json"},o),{OTEL_RESOURCE_ATTRIBUTES:"service.name=gemini-cli"});case"opencode":return $(x({OTEL_TRACES_EXPORTER:"otlp",OTEL_LOGS_EXPORTER:"otlp",OTEL_METRICS_EXPORTER:"otlp",OTEL_EXPORTER_OTLP_PROTOCOL:"http/json"},o),{OTEL_RESOURCE_ATTRIBUTES:"service.name=opencode"});default:return o}}var Fk,ol=h(()=>{"use strict";ca();fg();Ps();Ge();dn();bg();Ls();Fk={claude:"claude_code",codex:"codex",gemini:"gemini",opencode:"opencode"}});function Bs(t,e){return t.length>e?`${t.slice(0,e)}\u2026[truncated]`:t}function Gk(t){if(!Array.isArray(t))return"";let e=[];for(let n of t)if(n&&typeof n=="object"){let o=n.text,r=n.output_text;typeof o=="string"?e.push(o):typeof r=="string"&&e.push(r)}return e.join("").trim()}function Wk(t){if(typeof t=="string")return t;if(t&&typeof t=="object"){let e=t.output;if(typeof e=="string")return e;try{return JSON.stringify(t)}catch(n){return""}}return typeof t=="number"||typeof t=="boolean"?String(t):""}function Hk(t){var r;let e=t.map(a=>typeof a.content=="string"&&a.content.length>3e4?$(x({},a),{content:Bs(a.content,3e4)}):a),n=()=>JSON.stringify(e).length,o=0;for(;n()>12e4&&o<e.length;){if(((r=e[o])==null?void 0:r.role)==="system"){o++;continue}e.splice(o,1)}return e}function Ag(t){return typeof t.call_id=="string"&&t.call_id?t.call_id:typeof t.id=="string"&&t.id?t.id:null}function kg(t){let e=new rl;for(let n of t.split(`
|
|
76
76
|
`)){let o=n.trim();if(!o)continue;let r;try{r=JSON.parse(o)}catch(a){continue}e.handle(r)}return e.finish()}var rl,Tg=h(()=>{"use strict";rl=class{constructor(){this.turns=[];this.history=[];this.sessionModel=null;this.cur=null;this.pendingAssistant=null;this.agentFinal=null;this.pendingToolCallIds=[];this.autoToolCallSeq=0}handle(e){var o;let n=(o=e.payload)!=null?o:{};switch(e.type){case"session_meta":return this.onSessionMeta(n);case"turn_context":return this.onTurnContext(n);case"event_msg":return this.onEventMsg(n);case"response_item":return this.onResponseItem(n)}}finish(){return this.closeTurn(),this.turns}onSessionMeta(e){let n=e.base_instructions;typeof n=="string"&&n.trim()&&this.history.push({role:"system",content:n.trim()})}onTurnContext(e){let n=e.model;typeof n=="string"&&n&&(this.sessionModel=n,this.cur&&(this.cur.model=n))}onEventMsg(e){if(e.type==="task_started")return this.onTaskStarted(e);if(e.type==="task_complete")return this.closeTurn();this.cur&&e.type==="agent_message"&&this.onAgentMessage(e)}onTaskStarted(e){this.closeTurn();let n=typeof e.trace_id=="string"?e.trace_id:null;n&&(this.cur={traceId:n,turnId:typeof e.turn_id=="string"?e.turn_id:null,model:this.sessionModel,startedAtMs:typeof e.started_at=="number"?e.started_at*1e3:null})}onAgentMessage(e){let n=e.message;typeof n=="string"&&n.trim()&&e.phase==="final_answer"&&(this.agentFinal=n.trim())}onResponseItem(e){if(this.cur)switch(e.type){case"message":return this.onMessage(e);case"function_call":return this.onFunctionCall(e);case"function_call_output":return this.onFunctionCallOutput(e)}}onMessage(e){let n=e.role,o=Gk(e.content);o&&(n==="developer"?(this.flushPendingAssistant(),this.history.push({role:"system",content:o})):n==="user"?(this.flushPendingAssistant(),this.history.push({role:"user",content:o})):n==="assistant"&&(this.flushPendingAssistant(),this.pendingAssistant=o))}onFunctionCall(e){this.flushPendingAssistant();let n=Ag(e);n||(n=`call_auto_${this.autoToolCallSeq++}`,this.pendingToolCallIds.push(n));let o=typeof e.name=="string"?e.name:"tool",r=typeof e.arguments=="string"?e.arguments:e.arguments!=null?JSON.stringify(e.arguments):"";this.history.push({role:"assistant",tool_calls:[{id:n,type:"function",function:{name:o,arguments:Bs(r,3e4)}}]})}onFunctionCallOutput(e){var o,r;this.flushPendingAssistant();let n=(r=(o=Ag(e))!=null?o:this.pendingToolCallIds.shift())!=null?r:`call_auto_${this.autoToolCallSeq++}`;this.history.push({role:"tool",tool_call_id:n,content:Bs(Wk(e.output),3e4)})}flushPendingAssistant(){this.pendingAssistant!==null&&(this.history.push({role:"assistant",content:this.pendingAssistant}),this.pendingAssistant=null)}closeTurn(){var e,n;if(this.cur){let o=(e=this.agentFinal)!=null?e:this.pendingAssistant;o!=null&&o.trim()&&(this.turns.push({traceId:this.cur.traceId,turnId:this.cur.turnId,model:(n=this.cur.model)!=null?n:this.sessionModel,inputMessages:Hk([...this.history]),output:Bs(o.trim(),3e4),startedAtMs:this.cur.startedAtMs}),this.history.push({role:"assistant",content:o.trim()}))}this.pendingToolCallIds.length=0,this.cur=null,this.pendingAssistant=null,this.agentFinal=null}}});function Kk(t){return(0,_g.createHash)("sha256").update(`${t}:langwatch.io`).digest("hex").slice(0,16)}function lr(t,e){return{key:t,value:{stringValue:e}}}function qk(t,e){let n=t.map(o=>{var i;let r=(i=o.startedAtMs)!=null?i:e,a=Math.max(r,e),s=[lr("langwatch.span.type","llm"),lr("langwatch.input",JSON.stringify({type:"chat_messages",value:o.inputMessages})),lr("langwatch.output",o.output)];return o.model&&(s.push(lr("gen_ai.request.model",o.model)),s.push(lr("gen_ai.response.model",o.model))),{traceId:o.traceId,spanId:Kk(o.traceId),name:"codex.turn.response",kind:1,startTimeUnixNano:`${r}000000`,endTimeUnixNano:`${a}000000`,attributes:s,status:{}}});return{resourceSpans:[{resource:{attributes:[lr("service.name","codex")]},scopeSpans:[{scope:{name:"langwatch.codex.rollout"},spans:n}]}]}}async function Vk(t,e=(0,zs.join)((0,al.homedir)(),".codex","sessions")){let n=[];async function o(r,a){let s;try{s=await(0,pr.readdir)(r,{withFileTypes:!0})}catch(i){return}for(let i of s){let c=(0,zs.join)(r,i.name);if(i.isDirectory())a<3&&await o(c,a+1);else if(i.isFile()&&i.name.startsWith("rollout-")&&i.name.endsWith(".jsonl"))try{(await(0,pr.stat)(c)).mtimeMs>=t&&n.push(c)}catch(l){}}}return await o(e,0),n}async function Bk(t,e){let n=await Vk(t,e),o=[];for(let r of n)try{o.push(...kg(await(0,pr.readFile)(r,"utf8")))}catch(a){}return o}async function zk(t){let{turns:e,nowMs:n,endpoint:o,token:r,fetchImpl:a}=t,s=qk(e,n),i=a!=null?a:fetch,c=new AbortController,l=setTimeout(()=>c.abort(),5e3);try{await i(o,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${r}`},body:JSON.stringify(s),signal:c.signal})}finally{clearTimeout(l)}}function Eg(t){var o;let e=(o=t.sessionsRoot)!=null?o:(0,zs.join)((0,al.homedir)(),".codex","sessions"),n=new Set;return{async harvest(r){let s=(await Bk(t.sinceMs,e)).filter(i=>i.traceId&&!n.has(i.traceId));if(s.length===0)return 0;await zk({turns:s,nowMs:r,endpoint:t.endpoint,token:t.token,fetchImpl:t.fetchImpl});for(let i of s)n.add(i.traceId);return s.length}}}var _g,pr,al,zs,Cg=h(()=>{"use strict";_g=require("crypto"),pr=require("fs/promises"),al=require("os"),zs=require("path");Tg()});function Ys(t){let e=(t!=null?t:"").trim().toLowerCase();return e==="gateway"||e==="vk"?"gateway":e==="otlp"||e==="ingestion"||e==="direct"?"ingestion":null}function Ig(t,e=process.env){var a;let n=[],o;for(let s=0;s<t.length;s++){let i=t[s];if(i===sl){let c=t[s+1],l=Ys(c);l&&(o=l),c!==void 0&&s++;continue}if(i.startsWith(`${sl}=`)){let c=i.slice(sl.length+1),l=Ys(c);l&&(o=l);continue}n.push(i)}let r=(a=o!=null?o:Ys(e.LANGWATCH_TOOL_MODE))!=null?a:void 0;return{args:n,override:r}}function Yk(t){let e=t.LANGWATCH_AUTO_LOGIN;return e==="1"||e==="true"}function Jk(t){return`How should \`langwatch ${t}\` run?`}function Xk(){return"Gateway (virtual key) - route LLM calls through LangWatch (usage billed per token)"}function Zk(t){return`Direct OTLP - use your own ${t} plan, send only telemetry to LangWatch`}async function Pg(t){var _,L,O;let{cfg:e,tool:n,override:o,promptImpl:r=Rg.default,saveImpl:a=Le,writeImpl:s=F=>{process.stderr.write(F)},env:i=process.env}=t,c=(_=t.isTTY)!=null?_:!!process.stdin.isTTY&&!!process.stdout.isTTY;if(o)return{mode:o,prompted:!1};let l=(L=e.tool_mode)==null?void 0:L[n];if(l==="gateway"||l==="ingestion")return{mode:l,prompted:!1};if(t.refreshPolicies)try{let F=await t.refreshPolicies(e);if(F){e.tool_policies=F;try{a($(x({},e),{tool_policies:F}))}catch(H){}}}catch(F){}let m=or(n,e.tool_policies),f=m.allowVk,A=m.allowOtelDirect;if(f&&!A)return{mode:"gateway",prompted:!1};if(!f&&A)return{mode:"ingestion",prompted:!1};if(!f&&!A)return{mode:"gateway",prompted:!1};if(!(c&&!Yk(i)))return{mode:"gateway",prompted:!1};let C=await r({type:"select",name:"path",message:Jk(n),choices:[{title:Xk(),value:"gateway"},{title:Zk(n),value:"ingestion"}],initial:0}),E=Ys(C==null?void 0:C.path);if(!E)return{mode:"gateway",prompted:!1};let M=$(x({},e),{tool_mode:$(x({},(O=e.tool_mode)!=null?O:{}),{[n]:E})});try{a(M),e.tool_mode=M.tool_mode}catch(F){}let N=E==="gateway"?"gateway":"otlp";return s(`${Ot()} saved. \`${n}\` will use the ${N} path. Override with --tool-mode=${E==="gateway"?"otlp":"gateway"}, or edit ~/.langwatch/config.json (tool_mode.${n}).
|
|
77
77
|
`),{mode:E,prompted:!0}}var Rg,sl,Lg=h(()=>{"use strict";Rg=b(require("prompts"));Ps();Ge();Ls();sl="--tool-mode"});function Hs(t,e){var r;let n=t.gateway_url.replace(/\/+$/,""),o=(r=t.default_personal_vk)==null?void 0:r.secret;if(!o)return{vars:{}};switch(e){case"claude":return{vars:{ANTHROPIC_BASE_URL:n,ANTHROPIC_AUTH_TOKEN:o},clears:["ANTHROPIC_API_KEY"]};case"codex":return{vars:{OPENAI_BASE_URL:n,OPENAI_API_KEY:o}};case"cursor":return{vars:{OPENAI_BASE_URL:n,OPENAI_API_KEY:o,ANTHROPIC_BASE_URL:n,ANTHROPIC_AUTH_TOKEN:o},clears:["ANTHROPIC_API_KEY"]};case"gemini":return{vars:{GOOGLE_GEMINI_BASE_URL:n,GEMINI_API_KEY:o,GOOGLE_API_KEY:o}};case"opencode":return{vars:{OPENAI_BASE_URL:`${n}/v1`,OPENAI_API_KEY:o,ANTHROPIC_BASE_URL:`${n}/v1`,ANTHROPIC_AUTH_TOKEN:o,ANTHROPIC_API_KEY:o}};default:return{vars:{}}}}function tT(t){return t.pinnedMode==="gateway"&&t.retryable!==!0}function pa(t){return t?`Need help? Contact your LangWatch admin: ${t}
|
|
78
78
|
`:`If you need help, contact your LangWatch admin.
|
|
@@ -129,7 +129,7 @@ requests through the gateway. If you're an admin, add one at
|
|
|
129
129
|
`),process.exit(1)}if(e.json){console.log(JSON.stringify(o,null,2));return}let{source:r,health:a}=o;console.log(`${Co.default.bold(r.name)} ${Co.default.gray("("+r.id+")")}`),console.log(`Status: ${AT(r.status)}`),console.log(`Events (24h): ${a.events24h}`),console.log(`Events (7d): ${a.events7d}`),console.log(`Events (30d): ${a.events30d}`),console.log(`Last event: ${a.lastSuccessIso?kT(new Date(a.lastSuccessIso)):Co.default.gray("\u2014")}`)}function AT(t){switch(t){case"active":return Co.default.green(t);case"awaiting_first_event":return Co.default.yellow(t);case"archived":return Co.default.gray(t);default:return t}}function kT(t){let e=Date.now()-t.getTime();if(e<0)return t.toISOString();let n=Math.floor(e/1e3);if(n<60)return`${n}s ago`;let o=Math.floor(n/60);if(o<60)return`${o}m ago`;let r=Math.floor(o/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}var Co,th=h(()=>{"use strict";Co=b(require("chalk"));Ge();dn()});var oh={};k(oh,{installCommand:()=>TT});async function TT(t,e={}){let n=re();if(!Ae(n)){process.stderr.write("Not logged in. Run `langwatch login --device` first.\n"),process.exit(1);return}let o=_T(t);if(!o){process.stderr.write(`Unknown tool '${t}'. Supported: ${nh.join(", ")}.
|
|
130
130
|
`),process.exit(1);return}try{let r=await ET(n,o,e);if(e.json){process.stdout.write(JSON.stringify(r,null,2)+`
|
|
131
131
|
`);return}RT(r)}catch(r){let a=r instanceof me?r.message:String(r);process.stderr.write(`Error: ${a}
|
|
132
|
-
`),process.exit(1)}}function _T(t){let e=t.trim().toLowerCase().replace(/-/g,"_");return nh.includes(e)?e:null}async function ET(t,e,n){var c,l;let{token:o,prefix:r,endpoint:a}=await na(t,e),s=CT(e,a,o),i={tool:e,source_type:e,endpoint:a,ingestion_token:o,token_prefix:r,env_block:s};if(e==="codex"&&!n.envOnly){let m=sr({endpoint:`${a}/v1/traces`,ingestionToken:o,environment:(l=(c=t.organization)==null?void 0:c.slug)!=null?l:"langwatch"},{filePath:n.codexConfigPath});i.codex_config_action=m.action,i.codex_config_path=m.path}return i}function CT(t,e,n){let o=[`export OTEL_EXPORTER_OTLP_ENDPOINT="${e}"`,`export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer ${n}"`];switch(t){case"codex":return["export OTEL_TRACES_EXPORTER=otlp","export OTEL_EXPORTER_OTLP_PROTOCOL=http/json",...o,'export OTEL_RESOURCE_ATTRIBUTES="service.name=codex"'];case"claude_code":return["export CLAUDE_CODE_ENABLE_TELEMETRY=1","export OTEL_LOG_USER_PROMPTS=1","export OTEL_LOG_TOOL_DETAILS=1","export OTEL_LOG_TOOL_CONTENT=1","export OTEL_LOG_RAW_API_BODIES=1","export OTEL_TRACES_EXPORTER=otlp","export OTEL_LOGS_EXPORTER=otlp","export OTEL_METRICS_EXPORTER=otlp","export OTEL_EXPORTER_OTLP_PROTOCOL=http/json",...o,'export OTEL_RESOURCE_ATTRIBUTES="service.name=claude-code"'];case"gemini":return["export GEMINI_TELEMETRY_ENABLED=true","export GEMINI_TELEMETRY_TARGET=local","export GEMINI_TELEMETRY_USE_COLLECTOR=true","export GEMINI_TELEMETRY_TRACES_ENABLED=true","export GEMINI_TELEMETRY_OTLP_PROTOCOL=http",`export GEMINI_TELEMETRY_OTLP_ENDPOINT="${e}"`,"export GEMINI_TELEMETRY_LOG_PROMPTS=true","export OTEL_TRACES_EXPORTER=otlp","export OTEL_EXPORTER_OTLP_PROTOCOL=http/json",...o,'export OTEL_RESOURCE_ATTRIBUTES="service.name=gemini-cli"'];case"opencode":return["export OTEL_TRACES_EXPORTER=otlp","export OTEL_LOGS_EXPORTER=otlp","export OTEL_METRICS_EXPORTER=otlp","export OTEL_EXPORTER_OTLP_PROTOCOL=http/json",...o,'export OTEL_RESOURCE_ATTRIBUTES="service.name=opencode"']}}function RT(t){if(process.stdout.write(`${Js.default.green("\u2713")} Minted ingestion key for ${Js.default.bold(t.tool)}
|
|
132
|
+
`),process.exit(1)}}function _T(t){let e=t.trim().toLowerCase().replace(/-/g,"_");return nh.includes(e)?e:null}async function ET(t,e,n){var c,l;let{token:o,prefix:r,endpoint:a}=await na(t,e),s=CT(e,a,o),i={tool:e,source_type:e,endpoint:a,ingestion_token:o,token_prefix:r,env_block:s};if(e==="codex"&&!n.envOnly){let m=sr({endpoint:`${a}/v1/traces`,ingestionToken:o,environment:(l=(c=t.organization)==null?void 0:c.slug)!=null?l:"langwatch"},{filePath:n.codexConfigPath});i.codex_config_action=m.action,i.codex_config_path=m.path}return i}function CT(t,e,n){let o=[`export OTEL_EXPORTER_OTLP_ENDPOINT="${e}"`,`export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer ${n}"`];switch(t){case"codex":return["export OTEL_TRACES_EXPORTER=otlp","export OTEL_EXPORTER_OTLP_PROTOCOL=http/json",...o,'export OTEL_RESOURCE_ATTRIBUTES="service.name=codex"'];case"claude_code":return["export CLAUDE_CODE_ENABLE_TELEMETRY=1","export CLAUDE_CODE_ENHANCED_TELEMETRY_BETA=1","export OTEL_LOG_USER_PROMPTS=1","export OTEL_LOG_TOOL_DETAILS=1","export OTEL_LOG_TOOL_CONTENT=1","export OTEL_LOG_RAW_API_BODIES=1","export OTEL_TRACES_EXPORTER=otlp","export OTEL_LOGS_EXPORTER=otlp","export OTEL_METRICS_EXPORTER=otlp","export OTEL_EXPORTER_OTLP_PROTOCOL=http/json",...o,'export OTEL_RESOURCE_ATTRIBUTES="service.name=claude-code"'];case"gemini":return["export GEMINI_TELEMETRY_ENABLED=true","export GEMINI_TELEMETRY_TARGET=local","export GEMINI_TELEMETRY_USE_COLLECTOR=true","export GEMINI_TELEMETRY_TRACES_ENABLED=true","export GEMINI_TELEMETRY_OTLP_PROTOCOL=http",`export GEMINI_TELEMETRY_OTLP_ENDPOINT="${e}"`,"export GEMINI_TELEMETRY_LOG_PROMPTS=true","export OTEL_TRACES_EXPORTER=otlp","export OTEL_EXPORTER_OTLP_PROTOCOL=http/json",...o,'export OTEL_RESOURCE_ATTRIBUTES="service.name=gemini-cli"'];case"opencode":return["export OTEL_TRACES_EXPORTER=otlp","export OTEL_LOGS_EXPORTER=otlp","export OTEL_METRICS_EXPORTER=otlp","export OTEL_EXPORTER_OTLP_PROTOCOL=http/json",...o,'export OTEL_RESOURCE_ATTRIBUTES="service.name=opencode"']}}function RT(t){if(process.stdout.write(`${Js.default.green("\u2713")} Minted ingestion key for ${Js.default.bold(t.tool)}
|
|
133
133
|
`),process.stdout.write(` endpoint: ${t.endpoint}
|
|
134
134
|
`),process.stdout.write(` token: ${t.ingestion_token}
|
|
135
135
|
`),t.codex_config_action){let e=t.codex_config_action==="created"?"created":t.codex_config_action==="updated"?"updated":"already up to date";process.stdout.write(`${Js.default.green("\u2713")} ${t.codex_config_path} ${e}
|
|
@@ -206,7 +206,7 @@ DAEMON
|
|
|
206
206
|
PIPING RULES
|
|
207
207
|
NEVER merge stderr into stdout (2>&1) when parsing JSON \u2014 hints, spinners
|
|
208
208
|
and human error blocks live on stderr BY DESIGN so stdout stays parseable.
|
|
209
|
-
Prefer --jq over piping through jq when the built-in subset suffices.`,bl={"agent-mode":Wh},c_=Object.keys(bl),l_=(t,e)=>{let[n,...o]=e;if(n===void 0){t.outputHelp();return}let r=t.commands.find(a=>a.name()===n||a.aliases().includes(n));for(let a of o)r=r==null?void 0:r.commands.find(s=>s.name()===a||s.aliases().includes(a));if(!r&&o.length===0){let a=bl[n];if(a){console.log(a());return}}if(!r){console.error(`error: unknown command or help topic '${e.join(" ")}'`),process.exitCode=1;return}r.outputHelp()}});var At,Nt,qh=h(()=>{"use strict";At="0.
|
|
209
|
+
Prefer --jq over piping through jq when the built-in subset suffices.`,bl={"agent-mode":Wh},c_=Object.keys(bl),l_=(t,e)=>{let[n,...o]=e;if(n===void 0){t.outputHelp();return}let r=t.commands.find(a=>a.name()===n||a.aliases().includes(n));for(let a of o)r=r==null?void 0:r.commands.find(s=>s.name()===a||s.aliases().includes(a));if(!r&&o.length===0){let a=bl[n];if(a){console.log(a());return}}if(!r){console.error(`error: unknown command or help topic '${e.join(" ")}'`),process.exitCode=1;return}r.outputHelp()}});var At,Nt,qh=h(()=>{"use strict";At="0.7.0",Nt=[{slug:"tracing",name:"tracing",description:"Add LangWatch tracing and observability to your code. Use for both onboarding (instrument an entire codebase) and targeted operations (add tracing to a specific function or module). Supports Python and TypeScript with all major frameworks.",userPrompt:"Instrument my code with LangWatch",isRecipe:!1,body:`---
|
|
210
210
|
name: tracing
|
|
211
211
|
user-prompt: "Instrument my code with LangWatch"
|
|
212
212
|
description: Add LangWatch tracing and observability to your code. Use for both onboarding (instrument an entire codebase) and targeted operations (add tracing to a specific function or module). Supports Python and TypeScript with all major frameworks.
|
|
@@ -3761,8 +3761,8 @@ To test this agent, use it within a workflow in the UI.`)),process.exit(1));let
|
|
|
3761
3761
|
`),{data:o,table:()=>{console.log(),console.log(Ct.default.bold.yellow("\u26A0 Save the service API key below NOW. It will not be shown again.")),console.log(),console.log(` ${Ct.default.green(o.serviceApiKey)}`),console.log(),console.log(Ct.default.gray("Use it to authenticate project-scoped operations:")),console.log(Ct.default.cyan(` export LANGWATCH_API_KEY="${o.serviceApiKey}"`)),console.log(),console.log(Ct.default.gray("Project id: ")+o.id),console.log(Ct.default.gray("Slug: ")+o.slug),console.log(Ct.default.gray("Service API key id: ")+o.serviceApiKeyId),console.log()}}}catch(o){y({spinner:n,error:o,action:"create project"}),process.exit(1)}}});var Jb={};k(Jb,{updateProjectCommand:()=>aR});var rn,aR,Xb=h(()=>{"use strict";rn=b(require("chalk"));I();Mr();R();j();aR=async(t,e)=>{w(),e.name===void 0&&e.language===void 0&&e.framework===void 0&&e.piiRedactionLevel===void 0&&(console.error(rn.default.red("Error: nothing to update. Provide at least one of --name, --language, --framework, --pii-redaction-level.")),process.exit(1));let o=new Kt,r=v(`Updating project "${t}"...`).start();try{let a=await o.update(t,{name:e.name,language:e.language,framework:e.framework,piiRedactionLevel:e.piiRedactionLevel});return r.succeed(`Updated project "${rn.default.cyan(a.name)}"`),{data:a,table:()=>{console.log(),console.log(`${rn.default.bold("ID:")} ${a.id}`),console.log(`${rn.default.bold("Name:")} ${rn.default.cyan(a.name)}`),console.log(`${rn.default.bold("Slug:")} ${a.slug}`),console.log(`${rn.default.bold("Language:")} ${a.language}`),console.log(`${rn.default.bold("Framework:")} ${a.framework}`),console.log(`${rn.default.bold("PII Redaction:")} ${a.piiRedactionLevel}`),console.log(`${rn.default.bold("Updated:")} ${new Date(a.updatedAt).toLocaleString()}`),console.log()}}}catch(a){y({spinner:r,error:a,action:"update project"}),process.exit(1)}}});var Zb={};k(Zb,{deleteProjectCommand:()=>sR});var Li,sR,Qb=h(()=>{"use strict";Li=b(require("chalk"));I();Mr();R();j();sR=async t=>{w();let e=new Kt,n=v(`Archiving project "${t}"...`).start();try{let o=await e.archive(t);return n.succeed(`Archived project "${Li.default.cyan(o.name)}"`),{data:o,table:()=>{console.log(),console.log(Li.default.gray("Project has been archived (soft-deleted).")),console.log(Li.default.gray("Archived at: ")+new Date(o.archivedAt).toLocaleString()),console.log()}}}catch(o){y({spinner:n,error:o,action:"archive project"}),process.exit(1)}}});var gp,po,Oi=h(()=>{"use strict";ye();vr();ct();gp=class extends Error{constructor(n,o,r){super(n);this.operation=o;this.originalError=r;this.name="ApiKeysApiError"}},po=class{constructor(e){var n,o,r,a;this.endpoint=((o=(n=e==null?void 0:e.endpoint)!=null?n:process.env.LANGWATCH_ENDPOINT)!=null?o:Fe).replace(/\/+$/,""),this.apiKey=(a=(r=e==null?void 0:e.apiKey)!=null?r:process.env.LANGWATCH_API_KEY)!=null?a:""}headers(){return{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"}}async request(e,n,o){var a;let r=await fetch(`${this.endpoint}${n}`,$(x({},o),{headers:x(x({},this.headers()),(a=o==null?void 0:o.headers)!=null?a:{})}));if(!r.ok){let s;try{s=await r.json()}catch(c){s=await r.text()}let i=ue({operation:e,error:s,options:{status:r.status}});throw hn({operation:e,error:s,status:r.status,message:i}),new gp(i,e,s)}return await r.json()}async list(){let{data:e}=await this.request("list API keys","/api/api-keys");return e}async create(e){return this.request("create API key","/api/api-keys",{method:"POST",body:JSON.stringify(e)})}async revoke(e){return this.request(`revoke API key "${e}"`,`/api/api-keys/${encodeURIComponent(e)}`,{method:"DELETE"})}}});var ex={};k(ex,{listApiKeysCommand:()=>iR});var an,iR,tx=h(()=>{"use strict";an=b(require("chalk"));I();Oi();R();ge();j();iR=async()=>{w();let t=new po,e=v("Fetching API keys...").start();try{let n=await t.list();return e.succeed(`Found ${n.length} API key${n.length!==1?"s":""}`),{data:n,table:()=>{if(n.length===0){console.log(),console.log(an.default.gray("No API keys found.")),console.log(an.default.gray("Create one with:")),console.log(an.default.cyan(' langwatch api-keys create --name "my-key"'));return}console.log();let o=Date.now(),r=n.map(a=>{let s=!!a.expiresAt&&new Date(a.expiresAt).getTime()<=o,i=a.revokedAt?an.default.red("revoked"):s?an.default.yellow("expired"):an.default.green("active");return{ID:a.id,Name:a.name,Status:i,Bindings:String(a.roleBindings.length),Expires:a.expiresAt?new Date(a.expiresAt).toLocaleDateString():an.default.gray("never"),"Last used":a.lastUsedAt?new Date(a.lastUsedAt).toLocaleDateString():an.default.gray("\u2014"),Created:new Date(a.createdAt).toLocaleDateString()}});Y({data:r,headers:["ID","Name","Status","Bindings","Expires","Last used","Created"],colorMap:{Name:an.default.cyan,ID:an.default.gray}}),console.log()}}}catch(n){y({spinner:e,error:n,action:"fetch API keys"}),process.exit(1)}}});var nx={};k(nx,{createApiKeyCommand:()=>cR});var Go,cR,ox=h(()=>{"use strict";Go=b(require("chalk"));I();Oi();R();j();cR=async t=>{var r;w(),t.name||(console.error(Go.default.red("Error: --name is required")),process.exit(1));let e=new po,n=(r=t.keyType)!=null?r:"service",o=v(`Creating ${n} API key "${t.name}"...`).start();try{let a=await e.create({keyType:n,name:t.name,description:t.description,expiresAt:t.expiresAt,projectIds:t.projectId});return o.succeed(`Created ${n} API key "${Go.default.cyan(a.apiKey.name)}"`),{data:a,table:()=>{console.log(),console.log(Go.default.bold.yellow("\u26A0 Save the token below NOW. It will not be shown again.")),console.log(),console.log(` ${Go.default.green(a.token)}`),console.log(),console.log(Go.default.gray("API key id: ")+a.apiKey.id),console.log(Go.default.gray("Created: ")+new Date(a.apiKey.createdAt).toLocaleString()),console.log()}}}catch(a){y({spinner:o,error:a,action:"create API key"}),process.exit(1)}}});var ax={};k(ax,{revokeApiKeyCommand:()=>lR});var rx,lR,sx=h(()=>{"use strict";rx=b(require("chalk"));I();Oi();R();j();lR=async t=>{w();let e=new po,n=v(`Revoking API key "${t}"...`).start();try{let o=await e.revoke(t);return n.succeed(`Revoked API key "${t}"`),{data:x({id:t},o),table:()=>{console.log(),console.log(rx.default.gray("API key has been revoked and can no longer be used.")),console.log()}}}catch(o){y({spinner:n,error:o,action:"revoke API key"}),process.exit(1)}}});function cx(t){return t instanceof $i||typeof t=="object"&&t!==null&&t.isDaemonExitSignal===!0}function lx(t,e){return wp.run(t,()=>Za(e))}function px(){if(hp)return()=>{};hp=!0;let t=process.stdout.write.bind(process.stdout),e=process.stderr.write.bind(process.stderr),n=process.exit.bind(process),o=(r,a)=>((s,i,c)=>{let l=wp.getStore();if(!l)return a(s,i,c);let m=typeof i=="string"?i:"utf8",f=typeof s=="string"?Buffer.from(s,m):Buffer.from(s);l.write(r,f);let A=typeof i=="function"?i:c;return A==null||A(),!0});return process.stdout.write=o("stdout",t),process.stderr.write=o("stderr",e),process.exit=(r=>{let a=wp.getStore();if(!a)return n(r);throw a.finalize(r!=null?r:0),new $i(a.exitCode)}),()=>{process.stdout.write=t,process.stderr.write=e,process.exit=n,hp=!1}}function mR(t){let e=Object.entries(t.env).sort(([n],[o])=>n<o?-1:n>o?1:0);return JSON.stringify([t.cwd,t.colorLevel,e])}var ix,fp,yp,pR,dR,uR,$i,Ni,wp,hp,Di,vp=h(()=>{"use strict";ix=require("async_hooks"),fp=require("string_decoder"),yp=b(require("chalk"));ht();q();pR=new Set(qr),dR=/\u001B\[[0-9;]*m/g,uR=/\u001B(?:\[[0-9;]*)?$/,$i=class extends Error{constructor(n){super(`process.exit(${n})`);this.code=n;this.isDaemonExitSignal=!0;this.name="DaemonExitSignal"}};Ni=class{constructor(e,n){this.id=e;this.sink=n;this.finished=!1;this.code=null;this.pendingEscape={stdout:null,stderr:null};this.decoders={stdout:new fp.StringDecoder("utf8"),stderr:new fp.StringDecoder("utf8")}}write(e,n){if(this.finished)return;let o=qo();o&&!o.hasColor&&(n=this.stripSgr({stream:e,chunk:n})),this.sink(e,n)}stripSgr({stream:e,chunk:n}){let o=this.pendingEscape[e],r=(o===null?"":o.toString("utf8"))+this.decoders[e].write(n);this.pendingEscape[e]=null;let a=uR.exec(r);return a&&(this.pendingEscape[e]=Buffer.from(a[0],"utf8"),r=r.slice(0,-a[0].length)),Buffer.from(r.replace(dR,""),"utf8")}finalize(e){if(!this.finished){for(let n of["stdout","stderr"]){let o=this.decoders[n].end();o&&this.sink(n,Buffer.from(o,"utf8"))}this.finished=!0,this.code=e}}get exitCode(){var e;return(e=this.code)!=null?e:0}get isFinished(){return this.finished}},wp=new ix.AsyncLocalStorage;hp=!1;Di=class{constructor(e=process.cwd()){this.baselineCwd=e;this.activeKey=null;this.inflight=0;this.queue=[];this.baselineEnv=x({},process.env)}get inflightCount(){return this.inflight}get queuedCount(){return this.queue.length}async acquire({request:e,signal:n}){let o=mR(e);return this.queue.length===0&&(this.inflight===0||this.activeKey===o)?this.admit(o,e):new Promise((r,a)=>{let s={key:o,request:e,resolve:r,reject:a};if(this.queue.push(s),!n)return;let i=()=>{let c=this.queue.indexOf(s);c!==-1&&(this.queue.splice(c,1),a(new Error("request cancelled while queued")))};if(n.aborted){i();return}n.addEventListener("abort",i,{once:!0})})}admit(e,n){this.activeKey!==e&&(this.applyWindow(n),this.activeKey=e),yp.default.level=n.colorLevel,this.inflight++;let o=!1;return()=>{o||(o=!0,this.release())}}release(){this.inflight--,!(this.inflight>0)&&this.drain()}drain(){for(;this.queue.length>0;){let e=this.queue[0];try{this.applyWindow(e.request),this.activeKey=e.key}catch(o){this.queue.shift(),e.reject(o);continue}let n=[];for(let o of this.queue)if(o.key===e.key){this.inflight++;let r=!1;o.resolve(()=>{r||(r=!0,this.release())})}else n.push(o);this.queue=n;return}this.activeKey=null}applyWindow(e){process.chdir(e.cwd);for(let n of Object.keys(process.env))n in this.baselineEnv||delete process.env[n];for(let[n,o]of Object.entries(this.baselineEnv))o===void 0?delete process.env[n]:process.env[n]=o;for(let n of Object.keys(process.env))(n.startsWith("LANGWATCH_")||pR.has(n))&&!(n in e.env)&&delete process.env[n];Object.assign(process.env,e.env),yp.default.level=e.colorLevel}reset(){process.chdir(this.baselineCwd);for(let e of Object.keys(process.env))e in this.baselineEnv||delete process.env[e];for(let[e,n]of Object.entries(this.baselineEnv))n===void 0?delete process.env[e]:process.env[e]=n;this.activeKey=null}}});function fR(){return dx(process.env.LANGWATCH_DAEMON_REQUEST_TIMEOUT_MS,gR)}function yR(){return dx(process.env.LANGWATCH_DAEMON_ABANDON_GRACE_MS,hR)}function dx(t,e){if(t){let n=Number(t);if(Number.isSafeInteger(n)&&n>0)return n}return e}function ux({window:t,telemetry:e,requestTimeoutMs:n,abandonGraceMs:o,onWedged:r=wR}){let a=n!=null?n:fR(),s=o!=null?o:yR();return i=>{let c=new Ni(i.requestId,(O,F)=>{i.sink(O,F),e.requestProgress({requestId:i.requestId,stream:O,bytes:F.byteLength})}),l=!1,m,f,A,T=new AbortController,C=()=>{A&&(clearTimeout(A),A=void 0);let O=f;f=void 0,O==null||O()},E=()=>{f===void 0||A||(A=setTimeout(()=>{A=void 0,r({requestId:i.requestId,graceMs:s})},s),A.unref())},M=({code:O,note:F})=>{c.isFinished||(l=!0,F!==void 0&&c.write("stderr",Buffer.from(F,"utf8")),c.finalize(O),T.abort(),m==null||m(O),E())},N=setTimeout(()=>{M({code:124,note:`langwatch: request timed out after ${Math.round(a/1e3)}s; the daemon abandoned it
|
|
3762
3762
|
`})},a);N.unref();let _=(async()=>{var D;let O=Date.now(),F;try{F=await t.acquire({request:{cwd:i.cwd,env:i.env,colorLevel:i.colorLevel},signal:T.signal})}catch(U){if(l)return c.exitCode;throw U}if(f=F,l)return C(),c.exitCode;e.requestStarted({requestId:i.requestId,args:i.args,cwd:i.cwd});let H;try{let U=On();await lx(c,()=>U.parseAsync(i.args,{from:"user"})),c.finalize(0)}catch(U){if(cx(U))c.finalize(U.code);else{H=U;let J=U instanceof Error?(D=U.stack)!=null?D:`${U.name}: ${U.message}`:String(U);c.write("stderr",Buffer.from(J+`
|
|
3763
3763
|
`,"utf8")),c.finalize(1)}}finally{C()}return e.requestFinished({requestId:i.requestId,exitCode:c.exitCode,durationMs:Date.now()-O,error:H,cancelled:l}),c.exitCode})();return{completed:new Promise((O,F)=>{let H=D=>{clearTimeout(N),O(D)};m=H,_.then(H,D=>{clearTimeout(N),F(D instanceof Error?D:new Error(String(D)))})}),cancel:O=>M({code:O})}}}var gR,hR,wR,mx=h(()=>{"use strict";xr();vp();gR=600*1e3,hR=60*1e3;wR=({requestId:t,graceMs:e})=>{process.stderr.write(`langwatch: daemon exiting \u2014 abandoned request ${t} did not settle within ${Math.round(e/1e3)}s, so its execution window can never be reused safely
|
|
3764
|
-
`),process.exit(70)}});var gx,hx=h(()=>{"use strict";gx={daemonStarted:()=>{},daemonStopping:()=>{},requestStarted:()=>{},requestProgress:()=>{},requestFinished:()=>{},shutdown:()=>Promise.resolve()}});async function fx(t){return!Ur.existsSync(t)||_n(t)!==null?!1:new Promise(e=>{let n=ji.connect(t),o=r=>{n.removeAllListeners(),n.destroy(),e(r)};n.once("connect",()=>o(!0)),n.once("error",()=>o(!1)),n.setTimeout(1e3,()=>o(!1))})}async function xp(t){if(!Ur.existsSync(t)||await fx(t))return!1;try{return Ur.unlinkSync(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}function yx(t){var U,J,z,K;let e=(U=t.telemetry)!=null?U:gx,n=(J=t.idleTimeoutMs)!=null?J:bp,o=(z=t.shutdownGraceMs)!=null?z:vR,r=Date.now(),a=new Di,s=(K=t.executor)!=null?K:ux({window:a,telemetry:e}),i=0,c=0,l=!1,m,f,A=new Set,T=[],C=ji.createServer(),E,M=new Promise(W=>{E=W}),N=()=>{m&&clearTimeout(m),!(l||c>0)&&(m=setTimeout(()=>{O("idle")},n),m.unref())},_=()=>{if(c>0)return;let W=T;T=[];for(let oe of W)oe()},L=async W=>c===0?!0:new Promise(oe=>{let te=setTimeout(()=>oe(!1),W);te.unref(),T.push(()=>{clearTimeout(te),oe(!0)})}),O=async W=>{if(l)return M;l=!0,m&&clearTimeout(m),e.daemonStopping({pid:process.pid,socketPath:t.socketPath,cliVersion:t.cliVersion,reason:W}),C.close();try{Ur.unlinkSync(t.socketPath)}catch(oe){}if(!await L(o)){for(let oe of A)oe.destroyed||oe.end(wo({t:"fallback",reason:"shutting-down-mid-command"}),()=>oe.destroy());A.clear()}return await e.shutdown(),f==null||f(),process.removeListener("SIGTERM",D),process.removeListener("SIGINT",D),a.reset(),E(),M},F=W=>{let oe=new yo,te=!1,ce,Q=!1;A.add(W);let Ie=()=>{Q&&(Q=!1,c--,N(),_())},u=G=>{W.destroyed||W.write(wo(G))},g=()=>{W.destroyed||W.end()};W.on("error",()=>{ce==null||ce.cancel(130)}),W.on("close",()=>{A.delete(W),ce==null||ce.cancel(130)});let S=G=>{switch(G.t){case"hello":{if(G.protocol!==1){u({t:"hello-err",reason:"protocol-skew",cliVersion:t.cliVersion}),g();return}if(G.build!==t.build){u({t:"hello-err",reason:"version-skew",cliVersion:t.cliVersion}),g();return}if(G.fingerprint!==t.fingerprint){u({t:"hello-err",reason:"identity-mismatch",cliVersion:t.cliVersion}),g();return}if(l){u({t:"hello-err",reason:"shutting-down",cliVersion:t.cliVersion}),g();return}te=!0,u({t:"hello-ok",protocol:1,cliVersion:t.cliVersion,build:t.build,pid:process.pid});return}case"status":{u({t:"status-ok",pid:process.pid,cliVersion:t.cliVersion,protocol:1,socketPath:t.socketPath,uptimeMs:Date.now()-r,idleTimeoutMs:n,served:i,inflight:c}),g();return}case"stop":{g(),O("stop-requested");return}case"cancel":{ce==null||ce.cancel(130);return}case"exec":{if(!te){u({t:"fallback",reason:"no-handshake"}),g();return}if(l){u({t:"fallback",reason:"shutting-down"}),g();return}c++,Q=!0,m&&clearTimeout(m);let he=`${process.pid}-${++i}`,Vt=s({requestId:he,args:G.args,cwd:G.cwd,env:G.env,colorLevel:G.colorLevel,sink:(Bt,uo)=>{u(Bt==="stdout"?{t:"out",d:uo.toString("base64")}:{t:"err",d:uo.toString("base64")})}});ce=Vt,Vt.completed.then(Bt=>{u({t:"exit",code:Bt}),g(),Ie()},Bt=>{u({t:"fallback",reason:Bt instanceof Error?Bt.message:"execution-failed"}),g(),Ie()});return}}};W.on("data",G=>{let he;try{he=oe.push(G)}catch(Vt){g();return}for(let Vt of he)try{S(Vt)}catch(Bt){Ie(),u({t:"fallback",reason:"daemon-error"}),g()}})},H=async()=>{if(!qa(t.socketPath))throw new Error(`socket path is too long for a unix domain socket: ${t.socketPath}`);Va(t.socketDir);let W=_n(t.socketPath);if(W!==null&&bR.has(W))throw new Gn(t.socketPath,W);if(await fx(t.socketPath))throw new La(t.socketPath);await xp(t.socketPath),f=px(),C.on("connection",F),await new Promise((oe,te)=>{C.once("error",te),C.listen(t.socketPath,()=>{C.removeListener("error",te),oe()})}),jp(t.socketPath),process.once("SIGTERM",D),process.once("SIGINT",D),e.daemonStarted({pid:process.pid,socketPath:t.socketPath,cliVersion:t.cliVersion}),N()},D=()=>{O("signal")};return{socketPath:t.socketPath,listen:H,closed:()=>M,stop:O,stats:()=>({served:i,inflight:c,uptimeMs:Date.now()-r})}}var Ur,ji,bp,vR,bR,La,wx=h(()=>{"use strict";Ur=b(require("fs")),ji=b(require("net"));fo();Hi();vp();mx();hx();bp=600*1e3,vR=5e3,bR=new Set(["socket-dir-not-a-directory","socket-dir-foreign-owner","socket-dir-loose-mode","socket-foreign-owner","socket-loose-mode"]),La=class extends Error{constructor(n){super(`a langwatch daemon is already listening on ${n}`);this.socketPath=n;this.name="DaemonAlreadyRunningError"}}});function vx(){return xR.length}var xR,bx=h(()=>{"use strict";dl();vl();Zl();op();Ql();xR=[Ti,_i,ki,Xs,ri]});var Mi={};k(Mi,{daemonStartCommand:()=>kR,daemonStatusCommand:()=>_R,daemonStopCommand:()=>TR});function SR(t){if(t!==void 0){let n=Number.parseInt(t,10);if(Number.isNaN(n)||n<=0)throw new Error(`Invalid --idle-timeout: ${t}`);return n}let e=process.env.LANGWATCH_DAEMON_IDLE_MS;if(e){let n=Number.parseInt(e,10);if(!Number.isNaN(n)&&n>0)return n}return bp}function AR(t){switch(t){case"socket-missing":case"socket-dir-missing":return null;case"socket-dir-not-a-directory":return"its socket directory is not a directory";case"socket-dir-foreign-owner":return"its socket directory is owned by another user";case"socket-dir-loose-mode":return"its socket directory is readable or writable by other users";case"socket-not-a-socket":return"another file is sitting at the socket path";case"socket-foreign-owner":return"the socket is owned by another user";case"socket-loose-mode":return"the socket is readable or writable by other users"}}function xx(t){let e=_n(t);if(!e)return!1;let n=AR(e);return n===null?!1:(console.error(Pe.default.red(`Refusing to use the langwatch daemon: ${n}.`)),console.error(Pe.default.gray(` socket: ${t}`)),console.error(Pe.default.gray(" Commands will keep working \u2014 they run in-process. Remove or fix the path above, or point LANGWATCH_DAEMON_DIR at a directory you own, to use the daemon again.")),!0)}function Sx(){Fr()||(console.error(Pe.default.red("The langwatch daemon is not available on this platform. Commands run in-process.")),process.exit(1))}async function kR(t){var r,a;Sx();let e=Ho(process.env),n=SR(t.idleTimeout);if(!t.foreground){if(xx(e.socketPath)){process.exitCode=1;return}let s=await qi(e.socketPath);if(s){console.log(Pe.default.gray(`Daemon already running (pid ${s.pid}) at ${s.socketPath}`));return}Ja({cliPath:(r=process.argv[1])!=null?r:"",env:Ya(process.env),identity:e,idleTimeoutMs:n}),console.log(Pe.default.green("Daemon starting in the background.")),console.log(Pe.default.gray(` socket: ${e.socketPath}`)),console.log(Pe.default.gray(` idle timeout: ${Math.round(n/1e3)}s`));return}let o=yx({socketPath:e.socketPath,socketDir:e.socketDir,fingerprint:e.fingerprint,cliVersion:"0.35.0",build:Ka("0.35.0",(a=process.argv[1])!=null?a:""),idleTimeoutMs:n});try{await o.listen()}catch(s){if(s instanceof La)return;if(s instanceof Gn){console.error(Pe.default.red(s.message)),console.error(Pe.default.gray(" Commands still work \u2014 they run in-process. Point LANGWATCH_DAEMON_DIR at a directory you own to use the daemon.")),process.exitCode=1;return}throw s}vx(),await o.closed()}async function TR(){Sx();let t=Ho(process.env);if(xx(t.socketPath)){process.exitCode=1;return}if(await za(t.socketPath)){console.log(Pe.default.green("Daemon stopped."));return}let n=await xp(t.socketPath);console.log(Pe.default.gray(n?"No daemon running (removed a stale socket left by a crashed daemon).":"No daemon running."))}async function _R(t){let e=Ho(process.env),n=Fr()?await qi(e.socketPath):null;if(t.json){console.log(JSON.stringify(x({running:n!==null,supported:Fr(),socketPath:e.socketPath},n!=null?n:{}),null,2));return}if(!Fr()){console.log(Pe.default.gray("Daemon: not supported on this platform."));return}if(!n){console.log(Pe.default.gray("Daemon: not running.")),console.log(Pe.default.gray(` socket: ${e.socketPath}`));return}console.log(Pe.default.green("Daemon: running")),console.log(Pe.default.gray(` pid: ${n.pid}`)),console.log(Pe.default.gray(` version: ${n.cliVersion}`)),console.log(Pe.default.gray(` socket: ${n.socketPath}`)),console.log(Pe.default.gray(` uptime: ${Math.round(n.uptimeMs/1e3)}s`)),console.log(Pe.default.gray(` idle timeout: ${Math.round(n.idleTimeoutMs/1e3)}s`)),console.log(Pe.default.gray(` served: ${n.served}`)),console.log(Pe.default.gray(` in flight: ${n.inflight}`))}var Pe,Ui=h(()=>{"use strict";Pe=b(require("chalk"));Vi();fo();wx();zi();bx();Bi()});var Tx={};k(Tx,{buildProgram:()=>On});function On(){var Ie;let t=new kx.Command;t.name(((Ie=process.argv[1])==null?void 0:Ie.split(/[\\/]/).pop())==="lw"?"lw":"langwatch").description("LangWatch CLI - Manage prompts, datasets, evaluators, scenarios, suites, and more").version("0.35.0","-v, --version","Display the current version").enablePositionalOptions().passThroughOptions().configureHelp({showGlobalOptions:!0}).showHelpAfterError().showSuggestionAfterError(),t.hook("preAction",async(u,g)=>{let S=Qi(g),G=await bd(g,S);await xd(G)}),t.command("login").description("Login to LangWatch. With no flags, asks where (cloud vs self-hosted) and how (AI tools vs project SDK). For CI/agents pass --device, --project, --api-key, or --token to skip prompts.").option("--api-key <key>","Set API key non-interactively (CI/agents that already have a project API key) \u2014 writes to .env").option("--endpoint <url>","Override the LangWatch control-plane URL for this login (self-hosted instances)").option("--device","RFC 8628 device-flow login via your company SSO; provisions a personal virtual key for Claude Code / Codex / Cursor / Gemini CLI").option("--project","Force project login: mint a project SDK key via the browser and write it to .env (for the SDK, `langwatch eval`, prompts). The implicit default in non-TTY contexts.").option("--token <token>","Set device-session token non-interactively (CI/agents that already have a pre-minted token from the dashboard) \u2014 writes to ~/.langwatch/config.json").option("--browser <name>","browser to open for device-flow approval (chrome|chromium|firefox|safari|none|<path>)").action(async u=>{try{await RR(u)}catch(g){let{reportCommandError:S}=await Promise.resolve().then(()=>(q(),ne));S({error:g}),process.exit(1)}});let n=t.command("config").description("Read or write user-global CLI configuration (endpoint, gateway-url, daemon)");n.command("set <key> <value>").description("Persist a config value to ~/.langwatch/config.json (e.g. `langwatch config set endpoint https://lw.acme.internal`)").action(async(u,g)=>{let{configSetCommand:S}=await Promise.resolve().then(()=>(Is(),Rs));await S(u,g)}),n.command("get <key>").description("Print the resolved value for a config key (uses the same flag > env > config > default priority as the CLI)").action(async u=>{let{configGetCommand:g}=await Promise.resolve().then(()=>(Is(),Rs));await g(u)}),n.command("list").description("List the current resolved values + their sources (no secrets shown)").action(async()=>{let{configListCommand:u}=await Promise.resolve().then(()=>(Is(),Rs));await u()}),t.command("open [path]").description("Open the LangWatch app in your browser. No path: /me in personal mode, project home if LANGWATCH_API_KEY is set. With a path: BASE/<path>.").option("--browser <name>","browser to open (chrome|chromium|firefox|safari|none|<path>)").action(async(u,g)=>{try{let{openCommand:S}=await Promise.resolve().then(()=>(jm(),Dm));await S({path:u,browser:g.browser})}catch(S){let{reportCommandError:G}=await Promise.resolve().then(()=>(q(),ne));G({error:S}),process.exit(1)}}),t.command("whoami").description("Print the identity persisted by `langwatch login --device` (governance plane).").action(async()=>{try{let{whoamiCommand:u}=await Promise.resolve().then(()=>(Fm(),Um));await u()}catch(u){let{reportCommandError:g}=await Promise.resolve().then(()=>(q(),ne));g({error:u}),process.exit(1)}}),t.command("request-increase").description("Open the budget-increase request page (uses the gateway-issued signed URL when available).").option("--browser <name>","browser to open (chrome|chromium|firefox|safari|none|<path>)").action(async u=>{try{let{requestIncreaseCommand:g}=await Promise.resolve().then(()=>(Hm(),Wm));await g(u)}catch(g){let{reportCommandError:S}=await Promise.resolve().then(()=>(q(),ne));S({error:g}),process.exit(1)}}),t.command("claude",{hidden:!0}).description("Run `claude` (Claude Code) routed through the LangWatch gateway.").allowUnknownOption(!0).allowExcessArguments(!0).helpOption(!1).action(async(u,g)=>{var S;try{let{wrapClaude:G}=await Promise.resolve().then(()=>(mr(),ur));await G((S=g.args)!=null?S:[])}catch(G){let{reportCommandError:he}=await Promise.resolve().then(()=>(q(),ne));he({error:G}),process.exit(1)}}),t.command("codex",{hidden:!0}).description("Run `codex` (OpenAI Codex CLI) routed through the LangWatch gateway.").allowUnknownOption(!0).allowExcessArguments(!0).helpOption(!1).action(async(u,g)=>{var S;try{let{wrapCodex:G}=await Promise.resolve().then(()=>(mr(),ur));await G((S=g.args)!=null?S:[])}catch(G){let{reportCommandError:he}=await Promise.resolve().then(()=>(q(),ne));he({error:G}),process.exit(1)}}),t.command("cursor",{hidden:!0}).description("Run `cursor` routed through the LangWatch gateway.").allowUnknownOption(!0).allowExcessArguments(!0).helpOption(!1).action(async(u,g)=>{var S;try{let{wrapCursor:G}=await Promise.resolve().then(()=>(mr(),ur));await G((S=g.args)!=null?S:[])}catch(G){let{reportCommandError:he}=await Promise.resolve().then(()=>(q(),ne));he({error:G}),process.exit(1)}}),t.command("gemini",{hidden:!0}).description("Run `gemini` (Gemini CLI) routed through the LangWatch gateway.").allowUnknownOption(!0).allowExcessArguments(!0).helpOption(!1).action(async(u,g)=>{var S;try{let{wrapGemini:G}=await Promise.resolve().then(()=>(mr(),ur));await G((S=g.args)!=null?S:[])}catch(G){let{reportCommandError:he}=await Promise.resolve().then(()=>(q(),ne));he({error:G}),process.exit(1)}}),t.command("opencode").description("Run `opencode` routed through the LangWatch gateway (multi-provider; injects both Anthropic and OpenAI env vars).").allowUnknownOption(!0).allowExcessArguments(!0).helpOption(!1).action(async(u,g)=>{var S;try{let{wrapOpencode:G}=await Promise.resolve().then(()=>(mr(),ur));await G((S=g.args)!=null?S:[])}catch(G){let{reportCommandError:he}=await Promise.resolve().then(()=>(q(),ne));he({error:G}),process.exit(1)}}),t.addHelpText("after",["","Coding assistants:"," claude Run `claude` (Claude Code) routed through the gateway"," codex Run `codex` (OpenAI Codex CLI) routed through the gateway"," cursor Run `cursor` routed through the gateway"," gemini Run `gemini` (Gemini CLI) routed through the gateway"," opencode Run `opencode` (multi-provider) routed through the gateway","","`lw` and `langwatch` are the same binary \u2014 use whichever you prefer.",""].join(`
|
|
3764
|
+
`),process.exit(70)}});var gx,hx=h(()=>{"use strict";gx={daemonStarted:()=>{},daemonStopping:()=>{},requestStarted:()=>{},requestProgress:()=>{},requestFinished:()=>{},shutdown:()=>Promise.resolve()}});async function fx(t){return!Ur.existsSync(t)||_n(t)!==null?!1:new Promise(e=>{let n=ji.connect(t),o=r=>{n.removeAllListeners(),n.destroy(),e(r)};n.once("connect",()=>o(!0)),n.once("error",()=>o(!1)),n.setTimeout(1e3,()=>o(!1))})}async function xp(t){if(!Ur.existsSync(t)||await fx(t))return!1;try{return Ur.unlinkSync(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}function yx(t){var U,J,z,K;let e=(U=t.telemetry)!=null?U:gx,n=(J=t.idleTimeoutMs)!=null?J:bp,o=(z=t.shutdownGraceMs)!=null?z:vR,r=Date.now(),a=new Di,s=(K=t.executor)!=null?K:ux({window:a,telemetry:e}),i=0,c=0,l=!1,m,f,A=new Set,T=[],C=ji.createServer(),E,M=new Promise(W=>{E=W}),N=()=>{m&&clearTimeout(m),!(l||c>0)&&(m=setTimeout(()=>{O("idle")},n),m.unref())},_=()=>{if(c>0)return;let W=T;T=[];for(let oe of W)oe()},L=async W=>c===0?!0:new Promise(oe=>{let te=setTimeout(()=>oe(!1),W);te.unref(),T.push(()=>{clearTimeout(te),oe(!0)})}),O=async W=>{if(l)return M;l=!0,m&&clearTimeout(m),e.daemonStopping({pid:process.pid,socketPath:t.socketPath,cliVersion:t.cliVersion,reason:W}),C.close();try{Ur.unlinkSync(t.socketPath)}catch(oe){}if(!await L(o)){for(let oe of A)oe.destroyed||oe.end(wo({t:"fallback",reason:"shutting-down-mid-command"}),()=>oe.destroy());A.clear()}return await e.shutdown(),f==null||f(),process.removeListener("SIGTERM",D),process.removeListener("SIGINT",D),a.reset(),E(),M},F=W=>{let oe=new yo,te=!1,ce,Q=!1;A.add(W);let Ie=()=>{Q&&(Q=!1,c--,N(),_())},u=G=>{W.destroyed||W.write(wo(G))},g=()=>{W.destroyed||W.end()};W.on("error",()=>{ce==null||ce.cancel(130)}),W.on("close",()=>{A.delete(W),ce==null||ce.cancel(130)});let S=G=>{switch(G.t){case"hello":{if(G.protocol!==1){u({t:"hello-err",reason:"protocol-skew",cliVersion:t.cliVersion}),g();return}if(G.build!==t.build){u({t:"hello-err",reason:"version-skew",cliVersion:t.cliVersion}),g();return}if(G.fingerprint!==t.fingerprint){u({t:"hello-err",reason:"identity-mismatch",cliVersion:t.cliVersion}),g();return}if(l){u({t:"hello-err",reason:"shutting-down",cliVersion:t.cliVersion}),g();return}te=!0,u({t:"hello-ok",protocol:1,cliVersion:t.cliVersion,build:t.build,pid:process.pid});return}case"status":{u({t:"status-ok",pid:process.pid,cliVersion:t.cliVersion,protocol:1,socketPath:t.socketPath,uptimeMs:Date.now()-r,idleTimeoutMs:n,served:i,inflight:c}),g();return}case"stop":{g(),O("stop-requested");return}case"cancel":{ce==null||ce.cancel(130);return}case"exec":{if(!te){u({t:"fallback",reason:"no-handshake"}),g();return}if(l){u({t:"fallback",reason:"shutting-down"}),g();return}c++,Q=!0,m&&clearTimeout(m);let he=`${process.pid}-${++i}`,Vt=s({requestId:he,args:G.args,cwd:G.cwd,env:G.env,colorLevel:G.colorLevel,sink:(Bt,uo)=>{u(Bt==="stdout"?{t:"out",d:uo.toString("base64")}:{t:"err",d:uo.toString("base64")})}});ce=Vt,Vt.completed.then(Bt=>{u({t:"exit",code:Bt}),g(),Ie()},Bt=>{u({t:"fallback",reason:Bt instanceof Error?Bt.message:"execution-failed"}),g(),Ie()});return}}};W.on("data",G=>{let he;try{he=oe.push(G)}catch(Vt){g();return}for(let Vt of he)try{S(Vt)}catch(Bt){Ie(),u({t:"fallback",reason:"daemon-error"}),g()}})},H=async()=>{if(!qa(t.socketPath))throw new Error(`socket path is too long for a unix domain socket: ${t.socketPath}`);Va(t.socketDir);let W=_n(t.socketPath);if(W!==null&&bR.has(W))throw new Gn(t.socketPath,W);if(await fx(t.socketPath))throw new La(t.socketPath);await xp(t.socketPath),f=px(),C.on("connection",F),await new Promise((oe,te)=>{C.once("error",te),C.listen(t.socketPath,()=>{C.removeListener("error",te),oe()})}),jp(t.socketPath),process.once("SIGTERM",D),process.once("SIGINT",D),e.daemonStarted({pid:process.pid,socketPath:t.socketPath,cliVersion:t.cliVersion}),N()},D=()=>{O("signal")};return{socketPath:t.socketPath,listen:H,closed:()=>M,stop:O,stats:()=>({served:i,inflight:c,uptimeMs:Date.now()-r})}}var Ur,ji,bp,vR,bR,La,wx=h(()=>{"use strict";Ur=b(require("fs")),ji=b(require("net"));fo();Hi();vp();mx();hx();bp=600*1e3,vR=5e3,bR=new Set(["socket-dir-not-a-directory","socket-dir-foreign-owner","socket-dir-loose-mode","socket-foreign-owner","socket-loose-mode"]),La=class extends Error{constructor(n){super(`a langwatch daemon is already listening on ${n}`);this.socketPath=n;this.name="DaemonAlreadyRunningError"}}});function vx(){return xR.length}var xR,bx=h(()=>{"use strict";dl();vl();Zl();op();Ql();xR=[Ti,_i,ki,Xs,ri]});var Mi={};k(Mi,{daemonStartCommand:()=>kR,daemonStatusCommand:()=>_R,daemonStopCommand:()=>TR});function SR(t){if(t!==void 0){let n=Number.parseInt(t,10);if(Number.isNaN(n)||n<=0)throw new Error(`Invalid --idle-timeout: ${t}`);return n}let e=process.env.LANGWATCH_DAEMON_IDLE_MS;if(e){let n=Number.parseInt(e,10);if(!Number.isNaN(n)&&n>0)return n}return bp}function AR(t){switch(t){case"socket-missing":case"socket-dir-missing":return null;case"socket-dir-not-a-directory":return"its socket directory is not a directory";case"socket-dir-foreign-owner":return"its socket directory is owned by another user";case"socket-dir-loose-mode":return"its socket directory is readable or writable by other users";case"socket-not-a-socket":return"another file is sitting at the socket path";case"socket-foreign-owner":return"the socket is owned by another user";case"socket-loose-mode":return"the socket is readable or writable by other users"}}function xx(t){let e=_n(t);if(!e)return!1;let n=AR(e);return n===null?!1:(console.error(Pe.default.red(`Refusing to use the langwatch daemon: ${n}.`)),console.error(Pe.default.gray(` socket: ${t}`)),console.error(Pe.default.gray(" Commands will keep working \u2014 they run in-process. Remove or fix the path above, or point LANGWATCH_DAEMON_DIR at a directory you own, to use the daemon again.")),!0)}function Sx(){Fr()||(console.error(Pe.default.red("The langwatch daemon is not available on this platform. Commands run in-process.")),process.exit(1))}async function kR(t){var r,a;Sx();let e=Ho(process.env),n=SR(t.idleTimeout);if(!t.foreground){if(xx(e.socketPath)){process.exitCode=1;return}let s=await qi(e.socketPath);if(s){console.log(Pe.default.gray(`Daemon already running (pid ${s.pid}) at ${s.socketPath}`));return}Ja({cliPath:(r=process.argv[1])!=null?r:"",env:Ya(process.env),identity:e,idleTimeoutMs:n}),console.log(Pe.default.green("Daemon starting in the background.")),console.log(Pe.default.gray(` socket: ${e.socketPath}`)),console.log(Pe.default.gray(` idle timeout: ${Math.round(n/1e3)}s`));return}let o=yx({socketPath:e.socketPath,socketDir:e.socketDir,fingerprint:e.fingerprint,cliVersion:"0.36.0",build:Ka("0.36.0",(a=process.argv[1])!=null?a:""),idleTimeoutMs:n});try{await o.listen()}catch(s){if(s instanceof La)return;if(s instanceof Gn){console.error(Pe.default.red(s.message)),console.error(Pe.default.gray(" Commands still work \u2014 they run in-process. Point LANGWATCH_DAEMON_DIR at a directory you own to use the daemon.")),process.exitCode=1;return}throw s}vx(),await o.closed()}async function TR(){Sx();let t=Ho(process.env);if(xx(t.socketPath)){process.exitCode=1;return}if(await za(t.socketPath)){console.log(Pe.default.green("Daemon stopped."));return}let n=await xp(t.socketPath);console.log(Pe.default.gray(n?"No daemon running (removed a stale socket left by a crashed daemon).":"No daemon running."))}async function _R(t){let e=Ho(process.env),n=Fr()?await qi(e.socketPath):null;if(t.json){console.log(JSON.stringify(x({running:n!==null,supported:Fr(),socketPath:e.socketPath},n!=null?n:{}),null,2));return}if(!Fr()){console.log(Pe.default.gray("Daemon: not supported on this platform."));return}if(!n){console.log(Pe.default.gray("Daemon: not running.")),console.log(Pe.default.gray(` socket: ${e.socketPath}`));return}console.log(Pe.default.green("Daemon: running")),console.log(Pe.default.gray(` pid: ${n.pid}`)),console.log(Pe.default.gray(` version: ${n.cliVersion}`)),console.log(Pe.default.gray(` socket: ${n.socketPath}`)),console.log(Pe.default.gray(` uptime: ${Math.round(n.uptimeMs/1e3)}s`)),console.log(Pe.default.gray(` idle timeout: ${Math.round(n.idleTimeoutMs/1e3)}s`)),console.log(Pe.default.gray(` served: ${n.served}`)),console.log(Pe.default.gray(` in flight: ${n.inflight}`))}var Pe,Ui=h(()=>{"use strict";Pe=b(require("chalk"));Vi();fo();wx();zi();bx();Bi()});var Tx={};k(Tx,{buildProgram:()=>On});function On(){var Ie;let t=new kx.Command;t.name(((Ie=process.argv[1])==null?void 0:Ie.split(/[\\/]/).pop())==="lw"?"lw":"langwatch").description("LangWatch CLI - Manage prompts, datasets, evaluators, scenarios, suites, and more").version("0.36.0","-v, --version","Display the current version").enablePositionalOptions().passThroughOptions().configureHelp({showGlobalOptions:!0}).showHelpAfterError().showSuggestionAfterError(),t.hook("preAction",async(u,g)=>{let S=Qi(g),G=await bd(g,S);await xd(G)}),t.command("login").description("Login to LangWatch. With no flags, asks where (cloud vs self-hosted) and how (AI tools vs project SDK). For CI/agents pass --device, --project, --api-key, or --token to skip prompts.").option("--api-key <key>","Set API key non-interactively (CI/agents that already have a project API key) \u2014 writes to .env").option("--endpoint <url>","Override the LangWatch control-plane URL for this login (self-hosted instances)").option("--device","RFC 8628 device-flow login via your company SSO; provisions a personal virtual key for Claude Code / Codex / Cursor / Gemini CLI").option("--project","Force project login: mint a project SDK key via the browser and write it to .env (for the SDK, `langwatch eval`, prompts). The implicit default in non-TTY contexts.").option("--token <token>","Set device-session token non-interactively (CI/agents that already have a pre-minted token from the dashboard) \u2014 writes to ~/.langwatch/config.json").option("--browser <name>","browser to open for device-flow approval (chrome|chromium|firefox|safari|none|<path>)").action(async u=>{try{await RR(u)}catch(g){let{reportCommandError:S}=await Promise.resolve().then(()=>(q(),ne));S({error:g}),process.exit(1)}});let n=t.command("config").description("Read or write user-global CLI configuration (endpoint, gateway-url, daemon)");n.command("set <key> <value>").description("Persist a config value to ~/.langwatch/config.json (e.g. `langwatch config set endpoint https://lw.acme.internal`)").action(async(u,g)=>{let{configSetCommand:S}=await Promise.resolve().then(()=>(Is(),Rs));await S(u,g)}),n.command("get <key>").description("Print the resolved value for a config key (uses the same flag > env > config > default priority as the CLI)").action(async u=>{let{configGetCommand:g}=await Promise.resolve().then(()=>(Is(),Rs));await g(u)}),n.command("list").description("List the current resolved values + their sources (no secrets shown)").action(async()=>{let{configListCommand:u}=await Promise.resolve().then(()=>(Is(),Rs));await u()}),t.command("open [path]").description("Open the LangWatch app in your browser. No path: /me in personal mode, project home if LANGWATCH_API_KEY is set. With a path: BASE/<path>.").option("--browser <name>","browser to open (chrome|chromium|firefox|safari|none|<path>)").action(async(u,g)=>{try{let{openCommand:S}=await Promise.resolve().then(()=>(jm(),Dm));await S({path:u,browser:g.browser})}catch(S){let{reportCommandError:G}=await Promise.resolve().then(()=>(q(),ne));G({error:S}),process.exit(1)}}),t.command("whoami").description("Print the identity persisted by `langwatch login --device` (governance plane).").action(async()=>{try{let{whoamiCommand:u}=await Promise.resolve().then(()=>(Fm(),Um));await u()}catch(u){let{reportCommandError:g}=await Promise.resolve().then(()=>(q(),ne));g({error:u}),process.exit(1)}}),t.command("request-increase").description("Open the budget-increase request page (uses the gateway-issued signed URL when available).").option("--browser <name>","browser to open (chrome|chromium|firefox|safari|none|<path>)").action(async u=>{try{let{requestIncreaseCommand:g}=await Promise.resolve().then(()=>(Hm(),Wm));await g(u)}catch(g){let{reportCommandError:S}=await Promise.resolve().then(()=>(q(),ne));S({error:g}),process.exit(1)}}),t.command("claude",{hidden:!0}).description("Run `claude` (Claude Code) routed through the LangWatch gateway.").allowUnknownOption(!0).allowExcessArguments(!0).helpOption(!1).action(async(u,g)=>{var S;try{let{wrapClaude:G}=await Promise.resolve().then(()=>(mr(),ur));await G((S=g.args)!=null?S:[])}catch(G){let{reportCommandError:he}=await Promise.resolve().then(()=>(q(),ne));he({error:G}),process.exit(1)}}),t.command("codex",{hidden:!0}).description("Run `codex` (OpenAI Codex CLI) routed through the LangWatch gateway.").allowUnknownOption(!0).allowExcessArguments(!0).helpOption(!1).action(async(u,g)=>{var S;try{let{wrapCodex:G}=await Promise.resolve().then(()=>(mr(),ur));await G((S=g.args)!=null?S:[])}catch(G){let{reportCommandError:he}=await Promise.resolve().then(()=>(q(),ne));he({error:G}),process.exit(1)}}),t.command("cursor",{hidden:!0}).description("Run `cursor` routed through the LangWatch gateway.").allowUnknownOption(!0).allowExcessArguments(!0).helpOption(!1).action(async(u,g)=>{var S;try{let{wrapCursor:G}=await Promise.resolve().then(()=>(mr(),ur));await G((S=g.args)!=null?S:[])}catch(G){let{reportCommandError:he}=await Promise.resolve().then(()=>(q(),ne));he({error:G}),process.exit(1)}}),t.command("gemini",{hidden:!0}).description("Run `gemini` (Gemini CLI) routed through the LangWatch gateway.").allowUnknownOption(!0).allowExcessArguments(!0).helpOption(!1).action(async(u,g)=>{var S;try{let{wrapGemini:G}=await Promise.resolve().then(()=>(mr(),ur));await G((S=g.args)!=null?S:[])}catch(G){let{reportCommandError:he}=await Promise.resolve().then(()=>(q(),ne));he({error:G}),process.exit(1)}}),t.command("opencode").description("Run `opencode` routed through the LangWatch gateway (multi-provider; injects both Anthropic and OpenAI env vars).").allowUnknownOption(!0).allowExcessArguments(!0).helpOption(!1).action(async(u,g)=>{var S;try{let{wrapOpencode:G}=await Promise.resolve().then(()=>(mr(),ur));await G((S=g.args)!=null?S:[])}catch(G){let{reportCommandError:he}=await Promise.resolve().then(()=>(q(),ne));he({error:G}),process.exit(1)}}),t.addHelpText("after",["","Coding assistants:"," claude Run `claude` (Claude Code) routed through the gateway"," codex Run `codex` (OpenAI Codex CLI) routed through the gateway"," cursor Run `cursor` routed through the gateway"," gemini Run `gemini` (Gemini CLI) routed through the gateway"," opencode Run `opencode` (multi-provider) routed through the gateway","","`lw` and `langwatch` are the same binary \u2014 use whichever you prefer.",""].join(`
|
|
3765
3765
|
`)),t.command("logout").description("Log out: revoke + clear the device session AND remove the telemetry wiring `langwatch <tool>` installed (claude settings.json, codex config.toml, gemini/opencode shell functions). Only langwatch-authored blocks are removed; the project API key in .env is left alone. Idempotent.").option("-y, --yes","skip the confirmation prompt").option("--keep-credentials","remove the telemetry wiring but stay logged in").action(async u=>{try{let{logoutCommand:g}=await Promise.resolve().then(()=>(Ug(),Mg));await g(u)}catch(g){let{reportCommandError:S}=await Promise.resolve().then(()=>(q(),ne));S({error:g}),process.exit(1)}}),t.command("init-shell").description("Print an eval-able shell snippet so any shell session auto-exports the gateway env vars (alternative to `langwatch claude`).").argument("[shell]","zsh|bash|fish|cmd|powershell","zsh").action(async u=>{try{let{initShellCommand:g}=await Promise.resolve().then(()=>(Gg(),Fg));await g(u)}catch(g){let{reportCommandError:S}=await Promise.resolve().then(()=>(q(),ne));S({error:g}),process.exit(1)}});let o=t.command("ingest").description("Inspect IngestionSources and tail their recent OCSF-normalised events (read-only governance debug helpers).");o.command("list").description("List the org's IngestionSources (active by default; --all includes archived).").option("--all","include archived sources").option("--json","emit machine-readable JSON").action(async u=>{try{let{ingestListCommand:g}=await Promise.resolve().then(()=>(Bg(),Vg));await g(u)}catch(g){let{reportCommandError:S}=await Promise.resolve().then(()=>(q(),ne));S({error:g}),process.exit(1)}}),o.command("tail <sourceId>").description("Stream the most recent events for an IngestionSource. --follow polls every 3s.").option("--limit <n>","how many events to fetch on first poll (default 50)",u=>parseInt(u,10)).option("--follow","keep polling for new events; exit on Ctrl-C").option("--json","emit machine-readable JSON").action(async(u,g)=>{try{let{ingestTailCommand:S}=await Promise.resolve().then(()=>(Qg(),Zg));await S(u,g)}catch(S){let{reportCommandError:G}=await Promise.resolve().then(()=>(q(),ne));G({error:S}),process.exit(1)}}),o.command("health <sourceId>").description("Show events received in the last 24h / 7d / 30d + last-success timestamp for one IngestionSource.").option("--json","emit machine-readable JSON").action(async(u,g)=>{try{let{ingestHealthCommand:S}=await Promise.resolve().then(()=>(th(),eh));await S(u,g)}catch(S){let{reportCommandError:G}=await Promise.resolve().then(()=>(q(),ne));G({error:S}),process.exit(1)}}),o.command("install <tool>",{hidden:!0}).description("Hidden: low-level Path B install primitive. Normal users run `langwatch <tool>` which auto-installs when needed.").option("--env-only","skip the codex config.toml write; print exports only").option("--json","emit machine-readable JSON").action(async(u,g)=>{let{installCommand:S}=await Promise.resolve().then(()=>(rh(),oh));await S(u,g)});let r=t.command("governance").description("Manage governance resources (ingestion templates). Every change is recorded in the organization's audit log.");r.command("status").description("Show how far your organization's governance setup has progressed (sources, tools, telemetry).").option("--json","emit machine-readable JSON").action(async u=>{try{let{governanceStatusCommand:g}=await Promise.resolve().then(()=>(sh(),ah));await g(u)}catch(g){let{reportCommandError:S}=await Promise.resolve().then(()=>(q(),ne));S({error:g}),process.exit(1)}});let a=r.command("ingestion-templates").description("CRUD on IngestionTemplate rows. Reads use aiTools:view; mutations use aiTools:manage.");a.command("admin-list").description("Admin readonly catalog \u2014 includes ottl_rules. Requires aiTools:manage.").option("--json","emit machine-readable JSON").action(async u=>{let{adminListCommand:g}=await Promise.resolve().then(()=>(Io(),Ro));await g(u)}),a.command("get <id>").description("Fetch a single ingestion template by id.").option("--json","emit machine-readable JSON").action(async(u,g)=>{let{getCommand:S}=await Promise.resolve().then(()=>(Io(),Ro));await S(u,g)}),a.command("create").description("Author a new org-authored ingestion template.").requiredOption("--source-type <slug>","lowercase letters/digits/underscores, max 40 chars").requiredOption("--display-name <name>","human-readable label").option("--description <text>","optional description").option("--icon-asset <asset>","preset:<kind> | data:image/svg+xml;base64,...").option("--credential-schema <kind>","otlp_token | static_api_key | agent_id (defaults to otlp_token)").option("--ottl-rules <text>","OTTL rules (newline-separated statements)").option("--json","emit machine-readable JSON").action(async u=>{let{createCommand:g}=await Promise.resolve().then(()=>(Io(),Ro));await g(u)}),a.command("update-ottl-rules <id>").description("Replace ottl_rules on an org-authored template. Platform rows reject.").requiredOption("--ottl-rules <text>","OTTL rules (newline-separated statements)").option("--json","emit machine-readable JSON").action(async(u,g)=>{let{updateOttlRulesCommand:S}=await Promise.resolve().then(()=>(Io(),Ro));await S(u,g)}),a.command("archive <id>").description("Soft-archive an org-authored template. Platform rows reject.").option("--json","emit machine-readable JSON").action(async(u,g)=>{let{archiveCommand:S}=await Promise.resolve().then(()=>(Io(),Ro));await S(u,g)}),a.command("clone-from-platform <sourceTemplateId>").description("Clone a platform-published template into the caller's org for OTTL customisation.").option("--json","emit machine-readable JSON").action(async(u,g)=>{let{cloneFromPlatformCommand:S}=await Promise.resolve().then(()=>(Io(),Ro));await S(u,g)});let s=t.command("prompt").description("Manage prompt dependencies");s.command("init").description("Initialize a new prompts project").action(async()=>{try{await CR()}catch(u){let{reportCommandError:g}=await Promise.resolve().then(()=>(q(),ne));g({error:u}),process.exit(1)}}),P(s.command("create <name>").description("Create a new prompt YAML file with default content").option("-f, --format <format>","Output format: text (default) or json","text"),async u=>{try{let{createCommand:g}=await Promise.resolve().then(()=>(ph(),lh));return await g(u)}catch(g){let{reportCommandError:S}=await Promise.resolve().then(()=>(q(),ne));S({error:g}),process.exit(1)}}),s.command("add <spec> [localFile]").description("Add a prompt dependency (e.g., 'agent/foo', 'agent/bar@5') or local file").action(async(u,g)=>{try{if(g)await Ax(u,{localFile:g});else{let{name:S,version:G}=Xp(u);await Ax(S,{version:G})}}catch(S){let{reportCommandError:G}=await Promise.resolve().then(()=>(q(),ne));G({error:S}),process.exit(1)}}),s.command("remove <name>").description("Remove a prompt dependency").action(async u=>{try{await ER(u)}catch(g){let{reportCommandError:S}=await Promise.resolve().then(()=>(q(),ne));S({error:g}),process.exit(1)}}),P(s.command("list").description("List all available prompts on the server").option("-f, --format <format>","Output format: table (default) or json","table"),async()=>{try{let{listCommand:u}=await Promise.resolve().then(()=>(dl(),Xs));return await u()}catch(u){let{reportCommandError:g}=await Promise.resolve().then(()=>(q(),ne));g({error:u}),process.exit(1)}}),s.command("sync").description("Sync prompts - fetch remote and push local").action(async()=>{try{await IR()}catch(u){let{reportCommandError:g}=await Promise.resolve().then(()=>(q(),ne));g({error:u}),process.exit(1)}}),s.command("pull").description("Pull remote prompts and materialize locally").option("--tag <name>","Pull the version pointed to by this tag instead of the configured version").action(async u=>{try{await PR(u)}catch(g){let{reportCommandError:S}=await Promise.resolve().then(()=>(q(),ne));S({error:g}),process.exit(1)}}),s.command("push").description("Push local prompts to the server").option("--force-local","Auto-resolve conflicts by keeping local version").option("--force-remote","Auto-resolve conflicts by keeping remote version").action(async u=>{try{await LR({forceLocal:u.forceLocal,forceRemote:u.forceRemote})}catch(g){let{reportCommandError:S}=await Promise.resolve().then(()=>(q(),ne));S({error:g}),process.exit(1)}}),P(s.command("versions <handle>").description("List all versions of a prompt").option("-f, --format <format>","Output format: table (default) or json","table"),async u=>{let{promptVersionsCommand:g}=await Promise.resolve().then(()=>(mh(),uh));return g(u)}),P(s.command("restore <handle> <versionId>").description("Restore a prompt to a previous version (creates a new version with that config)").option("-f, --format <format>","Output format: table (default) or json","table"),async(u,g)=>{let{promptRestoreCommand:S}=await Promise.resolve().then(()=>(hh(),gh));return S(u,g)});let i=s.command("tag").description("Manage prompt tags");P(i.command("list").description("List all tag definitions for the organization").option("-f, --format <format>","Output format: table (default) or json","table"),async()=>{try{let{tagListCommand:u}=await Promise.resolve().then(()=>(yh(),fh));return await u()}catch(u){let{reportCommandError:g}=await Promise.resolve().then(()=>(q(),ne));g({error:u}),process.exit(1)}}),P(i.command("create <name>").description("Create a custom tag"),async u=>{try{let{tagCreateCommand:g}=await Promise.resolve().then(()=>(bh(),vh));return await g(u)}catch(g){let{reportCommandError:S}=await Promise.resolve().then(()=>(q(),ne));S({error:g}),process.exit(1)}}),P(i.command("rename <oldName> <newName>").description("Rename a tag"),async(u,g)=>{try{let{tagRenameCommand:S}=await Promise.resolve().then(()=>(Ah(),Sh));return await S(u,g)}catch(S){let{reportCommandError:G}=await Promise.resolve().then(()=>(q(),ne));G({error:S}),process.exit(1)}}),P(i.command("assign <prompt> <tag>").description("Assign a tag to a prompt version").option("--version <number>","Version number to assign (defaults to latest)"),async(u,g,S)=>{try{let{tagAssignCommand:G}=await Promise.resolve().then(()=>(Th(),kh));return await G(u,g,S)}catch(G){let{reportCommandError:he}=await Promise.resolve().then(()=>(q(),ne));he({error:G}),process.exit(1)}}),P(i.command("delete <name>").description("Delete a tag and remove all its assignments").option("--force","Skip confirmation prompt"),async(u,g)=>{try{let{tagDeleteCommand:S}=await Promise.resolve().then(()=>(Ch(),Eh));return await S(u,g)}catch(S){let{reportCommandError:G}=await Promise.resolve().then(()=>(q(),ne));G({error:S}),process.exit(1)}}),Rn(t.command("status").description("Show project resource counts and available commands").option("-f, --format <format>","Output format: table (default) or json","table")).action(async(u,g)=>{let{statusCommand:S}=await Promise.resolve().then(()=>(vl(),ri));await S(g.optsWithGlobals())}),P(t.command("commands").description("Machine-readable catalog of every CLI command: path, args, flags, hints, skill annotations, token costs").option("--flat","Flatten the command tree to a single list"),async u=>{let{commandsCommand:g}=await Promise.resolve().then(()=>(Uh(),Mh));return g(u)}),P(t.command("help-tree").description("Compact indented tree of all commands with # hint:/# skill: annotations (for agent context injection)"),async(u,g)=>{let{helpTreeCommand:S}=await Promise.resolve().then(()=>(Gh(),Fh));return S(g.optsWithGlobals())}),t.command("help [topic...]").description("Show help for a command or a help topic (`langwatch help agent-mode` is the agent-mode guide)").action(async(u=[])=>{let{helpCommand:g}=await Promise.resolve().then(()=>(Kh(),Hh));g(t,u)});let c=t.command("skills").description("List, inspect, and install LangWatch's bundled agent skills (default install root: ~/.agents/skills)");Rn(c.command("list").description("List every bundled skill with its installed state").option("--dir <root>","Install root to check (default ~/.agents)")).action(async(u,g)=>{try{let{skillsListCommand:S}=await Promise.resolve().then(()=>(rf(),of));await S(g.optsWithGlobals())}catch(S){let{reportCommandError:G}=await Promise.resolve().then(()=>(q(),ne));G({error:S}),process.exit(1)}}),Rn(c.command("get <name>").description("Print a skill's full body on stdout (raw markdown, for piping into agent context)")).action(async(u,g,S)=>{try{let{skillsGetCommand:G}=await Promise.resolve().then(()=>(sf(),af));await G(u,S.optsWithGlobals())}catch(G){let{reportCommandError:he}=await Promise.resolve().then(()=>(q(),ne));he({error:G}),process.exit(1)}}),Rn(c.command("install [names...]").description("Install skills into <dir>/skills/<slug>/SKILL.md (recipes nest under recipes/<slug>/)").option("--all","Install every skill in the bundle").option("--dir <root>","Install root (default ~/.agents)").option("--dry-run","Report what would happen without writing anything").option("--force","Overwrite files that differ from the bundle").option("-y, --yes","Confirm overwriting files the bundle does not manage (required in non-TTY/agent contexts)")).action(async(u,g,S)=>{try{let{skillsInstallCommand:G}=await Promise.resolve().then(()=>(df(),pf));await G(u,S.optsWithGlobals())}catch(G){let{reportCommandError:he}=await Promise.resolve().then(()=>(q(),ne));he({error:G}),process.exit(1)}}),Rn(c.command("uninstall [names...]").description("Remove installed skills (only files the bundle manages; never prompts non-interactively)").option("--all","Uninstall every skill in the bundle").option("--dir <root>","Install root (default ~/.agents)").option("--dry-run","Report what would happen without removing anything").option("-y, --yes","Skip the confirmation prompt (required in non-TTY/agent contexts)")).action(async(u,g,S)=>{try{let{skillsUninstallCommand:G}=await Promise.resolve().then(()=>(mf(),uf));await G(u,S.optsWithGlobals())}catch(G){let{reportCommandError:he}=await Promise.resolve().then(()=>(q(),ne));he({error:G}),process.exit(1)}}),Rn(c.command("update [names...]").description("Refresh installed skills whose content differs from the bundle (no names: all installed)").option("--dir <root>","Install root (default ~/.agents)").option("--dry-run","Report what would happen without writing anything").option("--force","Overwrite managed files that carry local edits").option("-y, --yes","Confirm overwriting files the bundle does not manage (required in non-TTY/agent contexts)")).action(async(u,g,S)=>{try{let{skillsUpdateCommand:G}=await Promise.resolve().then(()=>(ff(),hf));await G(u,S.optsWithGlobals())}catch(G){let{reportCommandError:he}=await Promise.resolve().then(()=>(q(),ne));he({error:G}),process.exit(1)}}),t.command("docs [url]").description("Fetch LangWatch documentation as markdown. Pass no argument for the index (llms.txt), a path like 'integration/python/guide', or a full URL. Missing extensions default to .md.").action(async u=>{try{let{docsCommand:g}=await Promise.resolve().then(()=>(Rl(),Cl));await g(u)}catch(g){let{reportCommandError:S}=await Promise.resolve().then(()=>(q(),ne));S({error:g}),process.exit(1)}}),t.command("scenario-docs [url]").description("Fetch LangWatch Scenario documentation as markdown. Pass no argument for the index, a path like 'advanced/red-teaming', or a full URL. Missing extensions default to .md.").action(async u=>{try{let{scenarioDocsCommand:g}=await Promise.resolve().then(()=>(Rl(),Cl));await g(u)}catch(g){let{reportCommandError:S}=await Promise.resolve().then(()=>(q(),ne));S({error:g}),process.exit(1)}});let l=t.command("evaluator").description("Manage evaluator definitions");P(l.command("list").description("List all evaluators in the project").option("-f, --format <format>","Output format: table (default) or json","table"),async()=>{try{let{listEvaluatorsCommand:u}=await Promise.resolve().then(()=>(bf(),vf));return await u()}catch(u){let{reportCommandError:g}=await Promise.resolve().then(()=>(q(),ne));g({error:u}),process.exit(1)}}),P(l.command("get <idOrSlug>").description("Get evaluator details by ID or slug").option("-f, --format <format>","Output format: table (default) or json","table"),async u=>{try{let{getEvaluatorCommand:g}=await Promise.resolve().then(()=>(Sf(),xf));return await g(u)}catch(g){let{reportCommandError:S}=await Promise.resolve().then(()=>(q(),ne));S({error:g}),process.exit(1)}}),P(l.command("types").description("List every evaluator type that `evaluator create --type` accepts").option("-f, --format <format>","Output format: table (default) or json","table"),async()=>{try{let{listEvaluatorTypesCommand:u}=await Promise.resolve().then(()=>(Pf(),If));return u()}catch(u){let{reportCommandError:g}=await Promise.resolve().then(()=>(q(),ne));g({error:u}),process.exit(1)}}),P(l.command("create <name>").description("Create a new evaluator").requiredOption("--type <evaluatorType>","Evaluator type (e.g. langevals/llm_boolean; see `langwatch evaluator types`)").option("-f, --format <format>","Output format: table (default) or json","table"),async(u,g)=>{try{let{createEvaluatorCommand:S}=await Promise.resolve().then(()=>(Of(),Lf));return await S(u,g)}catch(S){let{reportCommandError:G}=await Promise.resolve().then(()=>(q(),ne));G({error:S}),process.exit(1)}}),P(l.command("update <idOrSlug>").description("Update an evaluator name or settings").option("--name <name>","New evaluator name").option("--settings <json>","Evaluator config settings as JSON").option("-f, --format <format>","Output format: table (default) or json","table"),async(u,g)=>{try{let{updateEvaluatorCommand:S}=await Promise.resolve().then(()=>(Nf(),$f));return await S(u,g)}catch(S){let{reportCommandError:G}=await Promise.resolve().then(()=>(q(),ne));G({error:S}),process.exit(1)}}),P(l.command("delete <idOrSlug>").description("Archive (soft-delete) an evaluator").option("-f, --format <format>","Output format: table (default) or json","table"),async u=>{try{let{deleteEvaluatorCommand:g}=await Promise.resolve().then(()=>(Mf(),jf));return await g(u)}catch(g){let{reportCommandError:S}=await Promise.resolve().then(()=>(q(),ne));S({error:g}),process.exit(1)}});let m=t.command("experiment").description("Run, monitor, list, and inspect experiments");P(m.command("list").description("List experiments in the project").option("-f, --format <format>","Output format: table (default) or json","table").option("--limit <n>","Maximum experiments to fetch (default 50, max 200)","50"),async u=>{let{experimentListCommand:g}=await Promise.resolve().then(()=>(Gf(),Ff));return g(u)}),P(m.command("run <slug>").description("Start an experiment run by slug").option("--wait","Wait for the experiment to complete before returning").option("-f, --format <format>","Output format: table (default) or json","table"),async(u,g)=>{let{runExperimentCommand:S}=await Promise.resolve().then(()=>(Hf(),Wf));return S(u,g)}),P(m.command("status <experiment>").description("Check the status of an experiment run (defaults to the latest run)").option("-f, --format <format>","Output format: table (default) or json","table").option("--run-id <id>","Specific run id to check (defaults to the latest run)"),async(u,g)=>{let{experimentStatusCommand:S}=await Promise.resolve().then(()=>(Xf(),Jf));return S(u,g)}),P(m.command("list-runs <experiment>").description("List experiment runs for an experiment by slug").option("-f, --format <format>","Output format: table (default) or json","table").option("--limit <n>","Maximum runs to fetch (default 50, max 200)","50"),async(u,g)=>{let{experimentListRunsCommand:S}=await Promise.resolve().then(()=>(ty(),ey));return S(x({experiment:u},g))}),P(m.command("results <experiment>").description("Fetch per-row results for an experiment run, defaulting to the latest run (debug evaluator scores and missed rows)").option("--run-id <id>","Specific run id to fetch (defaults to the latest run)").option("--filter <filter>","Filter rows: failed | all (default)","all").option("--evaluator <name>","Show only this evaluator's column").option("-f, --format <format>","Output format: table (default) or json","table").option("--limit <n>","Maximum rows to print in table mode (default 20)","20"),async(u,g)=>{let{experimentResultsCommand:S}=await Promise.resolve().then(()=>(sy(),ay));return S({experimentSlug:u,options:g})});let f=t.command("workflow").description("Manage workflows");P(f.command("list").description("List all workflows in the project").option("-f, --format <format>","Output format: table (default) or json","table"),async()=>{let{listWorkflowsCommand:u}=await Promise.resolve().then(()=>(py(),ly));return u()}),P(f.command("get <id>").description("Get workflow details by ID").option("-f, --format <format>","Output format: table (default) or json","table"),async u=>{let{getWorkflowCommand:g}=await Promise.resolve().then(()=>(uy(),dy));return g(u)}),P(f.command("update <id>").description("Update a workflow's metadata (name, icon, description)").option("--name <name>","New workflow name").option("--icon <icon>","New workflow icon").option("--description <desc>","New workflow description").option("-f, --format <format>","Output format: table (default) or json","table"),async(u,g)=>{let{updateWorkflowCommand:S}=await Promise.resolve().then(()=>(gy(),my));return S(u,g)}),P(f.command("run <id>").description("Execute a workflow with JSON input").option("--input <json>","Input data as JSON string").option("-f, --format <format>","Output format: table (default) or json","table"),async(u,g)=>{let{runWorkflowCommand:S}=await Promise.resolve().then(()=>(fy(),hy));return S(u,g)}),P(f.command("delete <id>").description("Archive (soft-delete) a workflow").option("-f, --format <format>","Output format: table (default) or json","table"),async u=>{let{deleteWorkflowCommand:g}=await Promise.resolve().then(()=>(vy(),wy));return g(u)});let A=t.command("agent").description("Manage agent definitions");P(A.command("list").description("List all agents in the project").option("-f, --format <format>","Output format: table (default) or json","table"),async()=>{let{listAgentsCommand:u}=await Promise.resolve().then(()=>(xy(),by));return u()}),P(A.command("get <id>").description("Get agent details by ID").option("-f, --format <format>","Output format: table (default) or json","table"),async u=>{let{getAgentCommand:g}=await Promise.resolve().then(()=>(Ay(),Sy));return g(u)}),P(A.command("create <name>").description("Create a new agent").requiredOption("--type <type>","Agent type: signature, code, workflow, or http").option("--config <json>","Agent config as JSON").option("-f, --format <format>","Output format: table (default) or json","table"),async(u,g)=>{let{createAgentCommand:S}=await Promise.resolve().then(()=>(Ty(),ky));return S(u,g)}),P(A.command("run <id>").description("Execute an agent with JSON input (HTTP agents call URL directly, others use workflow engine)").option("--input <json>","Input data as JSON string").option("-f, --format <format>","Output format: table (default) or json","table"),async(u,g)=>{let{runAgentCommand:S}=await Promise.resolve().then(()=>(Ey(),_y));return S(u,g)}),P(A.command("update <id>").description("Update an agent name, type, or configuration").option("--name <name>","New agent name").option("--type <type>","New agent type: signature, code, workflow, or http").option("--config <json>","Updated configuration as JSON").option("-f, --format <format>","Output format: table (default) or json","table"),async(u,g)=>{let{updateAgentCommand:S}=await Promise.resolve().then(()=>(Ry(),Cy));return S(u,g)}),P(A.command("delete <id>").description("Archive (soft-delete) an agent").option("-f, --format <format>","Output format: table (default) or json","table"),async u=>{let{deleteAgentCommand:g}=await Promise.resolve().then(()=>(Py(),Iy));return g(u)});let T=t.command("dashboard").description("Manage analytics dashboards");P(T.command("list").description("List all dashboards in the project").option("-f, --format <format>","Output format: table (default) or json","table"),async()=>{let{listDashboardsCommand:u}=await Promise.resolve().then(()=>(Oy(),Ly));return u()}),P(T.command("get <id>").description("Get dashboard details by ID").option("-f, --format <format>","Output format: table (default) or json","table"),async u=>{let{getDashboardCommand:g}=await Promise.resolve().then(()=>(Ny(),$y));return g(u)}),P(T.command("update <id>").description("Rename a dashboard").requiredOption("--name <name>","New dashboard name").option("-f, --format <format>","Output format: table (default) or json","table"),async(u,g)=>{let{updateDashboardCommand:S}=await Promise.resolve().then(()=>(jy(),Dy));return S(u,g)}),P(T.command("create <name>").description("Create a new dashboard").option("-f, --format <format>","Output format: table (default) or json","table"),async u=>{let{createDashboardCommand:g}=await Promise.resolve().then(()=>(Uy(),My));return g(u)}),P(T.command("delete <id>").description("Delete a dashboard and its graphs").option("-f, --format <format>","Output format: table (default) or json","table"),async u=>{let{deleteDashboardCommand:g}=await Promise.resolve().then(()=>(Gy(),Fy));return g(u)});let C=t.command("model-provider").description("Manage LLM model provider configurations");P(C.command("list").description("List all configured model providers").option("-f, --format <format>","Output format: table (default) or json","table"),async()=>{let{listModelProvidersCommand:u}=await Promise.resolve().then(()=>(Hy(),Wy));return u()}),P(C.command("set <provider>").description("Configure a model provider (e.g. openai, anthropic)").option("--enabled <boolean>","Enable or disable the provider",u=>u==="true").option("--api-key <key>","API key for the provider").option("--default-model <model>","Default model to use (e.g. gpt-5-mini)").option("-f, --format <format>","Output format: table (default) or json","table"),async(u,g)=>{let{setModelProviderCommand:S}=await Promise.resolve().then(()=>(Vy(),qy));return S(u,g)});let E=t.command("model-default").description("Manage cascading default models (per role/feature, per scope: project/team/organization)");P(E.command("list").description("Show the effective resolution + every config you can read").option("-f, --format <format>","Output format: table (default) or json","table"),async()=>{let{listModelDefaultsCommand:u}=await Promise.resolve().then(()=>(zy(),By));return u()}),P(E.command("set <key> <model>").description("Set a default model for a role (DEFAULT|FAST|EMBEDDINGS) or registered feature key. Defaults to project scope; pass --scope team|organization for higher tiers.").option("--scope <scope>","Scope tier: project (default), team, or organization","project").option("--scope-id <id>","Explicit scope id. Defaults to the API key's project / its team / its organization.").option("-f, --format <format>","Output format: text (default) or json","text"),async(u,g,S)=>{let{setModelDefaultCommand:G}=await Promise.resolve().then(()=>(Jy(),Yy));return G(u,g,S)}),P(E.command("unset <key>").description("Remove a default model for a role or feature key at the chosen scope").option("--scope <scope>","Scope tier: project (default), team, or organization","project").option("--scope-id <id>","Explicit scope id. Defaults to the API key's project / its team / its organization.").option("-f, --format <format>","Output format: text (default) or json","text"),async(u,g)=>{let{unsetModelDefaultCommand:S}=await Promise.resolve().then(()=>(Zy(),Xy));return S(u,g)});let M=t.command("virtual-keys").alias("vk").description("Manage AI Gateway virtual keys (list, create, rotate, revoke)");P(M.command("list").description("List all virtual keys for the current project").option("-f, --format <format>","Output format: table (default) or json","table"),async()=>{let{listVirtualKeysCommand:u}=await Promise.resolve().then(()=>(ew(),Qy));return u()}),P(M.command("get <id>").description("Show details for a single virtual key").option("-f, --format <format>","Output format: text (default) or json","text"),async u=>{let{getVirtualKeyCommand:g}=await Promise.resolve().then(()=>(nw(),tw));return g(u)}),P(M.command("create").description("Create a new virtual key (secret is shown once)").requiredOption("--name <name>","Human-readable name for the key").option("--description <desc>","Optional description").option("--env <env>","Environment: live or test","live").option("--scope <typeAndId...>","Scope row in TYPE:id form (repeatable). Types: ORG | TEAM | PROJECT. Example: --scope ORG:acme --scope TEAM:platform").option("--routing-policy <id>","RoutingPolicy id to pin (otherwise uses the org's default policy)").option("--principal-user <userId>","Mark this VK as personal and attribute spend to the named principal user").option("-f, --format <format>","Output format: text (default) or json","text"),async u=>{let{createVirtualKeyCommand:g}=await Promise.resolve().then(()=>(rw(),ow));return g(u)}),P(M.command("update <id>").description("Update a virtual key's name/description/scopes/routing-policy/config").option("--name <name>","New display name").option("--description <desc>","New description").option("--clear-description","Clear the description").option("--scope <typeAndId...>","Replace the scope set (repeatable; supplies the full set). Same TYPE:id form as create.").option("--routing-policy <id>","Switch to a different RoutingPolicy (pass id)").option("--clear-routing-policy","Unpin the routing policy; VK falls back to the org default ordering").option("--config-json <json>","Inline partial config JSON (model_aliases/cache/fallback/rate_limits/policy_rules). Merges with existing config").option("--config-file <path>","Read partial config JSON from a file").option("-f, --format <format>","Output format: text (default) or json","text"),async(u,g)=>{let{updateVirtualKeyCommand:S}=await Promise.resolve().then(()=>(sw(),aw));return S(u,g)}),P(M.command("rotate <id>").description("Rotate a virtual key's secret (old secret stops working immediately)").option("-f, --format <format>","Output format: text (default) or json","text"),async u=>{let{rotateVirtualKeyCommand:g}=await Promise.resolve().then(()=>(cw(),iw));return g(u)}),P(M.command("revoke <id>").description("Revoke a virtual key (cannot be reactivated)").option("-f, --format <format>","Output format: text (default) or json","text"),async u=>{let{revokeVirtualKeyCommand:g}=await Promise.resolve().then(()=>(pw(),lw));return g(u)});let N=t.command("gateway-budgets").description("Manage AI Gateway spend budgets (hierarchical scopes)");P(N.command("list").description("List all budgets across scopes").option("-f, --format <format>","Output format: table (default) or json","table"),async()=>{let{listGatewayBudgetsCommand:u}=await Promise.resolve().then(()=>(uw(),dw));return u()}),P(N.command("create").description("Create a new budget (scope + window + limit)").requiredOption("--name <name>","Human-readable budget name").option("--description <desc>","Optional description").requiredOption("--scope <kind>","Budget scope: organization|team|project|virtual-key|principal").option("--organization <id>","Organization id (for scope=organization)").option("--team <id>","Team id (for scope=team)").option("--project <id>","Project id (for scope=project)").option("--virtual-key <id>","Virtual key id (for scope=virtual-key)").option("--principal <id>","Principal user id (for scope=principal)").requiredOption("--window <w>","Budget window: minute|hour|day|week|month|total").requiredOption("--limit <usd>","Hard cap in USD (e.g. 100 or 49.99)").option("--on-breach <action>","block (default) or warn","block").option("--timezone <tz>","IANA timezone for window boundaries (e.g. Europe/Amsterdam)").option("-f, --format <format>","Output format: text (default) or json","text"),async u=>{let{createGatewayBudgetCommand:g}=await Promise.resolve().then(()=>(hw(),gw));return g(u)}),P(N.command("update <id>").description("Update a budget's name/description/limit/on-breach/timezone").option("--name <name>","New display name").option("--description <desc>","New description").option("--clear-description","Clear the description").option("--limit <usd>","New hard-cap in USD").option("--on-breach <action>","block or warn").option("--timezone <tz>","New IANA timezone").option("--clear-timezone","Clear the timezone override").option("-f, --format <format>","Output format: text (default) or json","text"),async(u,g)=>{let{updateGatewayBudgetCommand:S}=await Promise.resolve().then(()=>(yw(),fw));return S(u,g)}),P(N.command("archive <id>").description("Archive a budget (stops enforcement; does not delete history)").option("-f, --format <format>","Output format: text (default) or json","text"),async u=>{let{archiveGatewayBudgetCommand:g}=await Promise.resolve().then(()=>(vw(),ww));return g(u)});let _=t.command("annotation").description("Manage trace annotations");P(_.command("list").description("List all annotations (optionally filtered by trace)").option("--trace-id <traceId>","Filter by trace ID").option("-f, --format <format>","Output format: table (default) or json","table"),async u=>{let{listAnnotationsCommand:g}=await Promise.resolve().then(()=>(xw(),bw));return g(u)}),P(_.command("get <id>").description("Get annotation details by ID").option("-f, --format <format>","Output format: table (default) or json","table"),async u=>{let{getAnnotationCommand:g}=await Promise.resolve().then(()=>(Aw(),Sw));return g(u)}),P(_.command("create <traceId>").description("Create an annotation for a trace").option("--comment <comment>","Annotation comment").option("--thumbs-up","Mark as thumbs up").option("--thumbs-down","Mark as thumbs down").option("--email <email>","Email of the annotator").option("-f, --format <format>","Output format: table (default) or json","table"),async(u,g)=>{let{createAnnotationCommand:S}=await Promise.resolve().then(()=>(_w(),Tw));return S(u,g)}),P(_.command("delete <id>").description("Delete an annotation").option("-f, --format <format>","Output format: table (default) or json","table"),async u=>{let{deleteAnnotationCommand:g}=await Promise.resolve().then(()=>(Rw(),Cw));return g(u)});let L=t.command("analytics").description("Query analytics and metrics");P(L.command("query").description("Query timeseries analytics (costs, latency, token usage, etc.)").option("-m, --metric <metric>","Metric to query (preset name or raw metric path, default: trace-count)").option("-a, --aggregation <aggregation>","Aggregation type: cardinality, avg, sum, min, max, p95, p99").option("--start-date <date>","Start date (ISO string, default: 7 days ago)").option("--end-date <date>","End date (ISO string, default: now)").option("--group-by <field>","Group by field (e.g. metadata.model)").option("--time-scale <scale>","Time scale: 'full' for aggregate, or interval in seconds").option("-f, --format <format>","Output format: table (default) or json","table"),async u=>{let{queryAnalyticsCommand:g}=await Promise.resolve().then(()=>(Zl(),ki));return g(u)});let O=t.command("trace").description("Search and inspect traces");Rn(O.command("search").description("Search traces with optional text query and date range").option("-q, --query <query>","Text search query").option("--start-date <date>","Start date (ISO string or epoch ms, default: 24h ago)").option("--end-date <date>","End date (ISO string or epoch ms, default: now)").option("--limit <n>","Max results to return (default: 25)").option("-f, --format <format>","Output format: table (default) or json","table")).action(async(u,g)=>{let{searchTracesCommand:S}=await Promise.resolve().then(()=>(Ql(),Ti));await S(g.optsWithGlobals())}),O.command("export").description("Export traces as CSV, JSONL, or JSON").option("--start-date <date>","Start date (ISO string, default: 7 days ago)").option("--end-date <date>","End date (ISO string, default: now)").option("-q, --query <query>","Text search query to filter traces").option("-f, --format <format>","Output format: jsonl (default), csv, or json","jsonl").option("-o, --output <file>","Write output to file instead of stdout").option("--limit <n>","Max traces to export (default: 1000)").action(async u=>{let{exportTracesCommand:g}=await Promise.resolve().then(()=>(Ww(),Gw));await g(u)}),Rn(O.command("get <traceId>").description("Get full trace details by ID").option("-f, --format <format>","Output format: digest (default, human-readable) or json","digest")).action(async(u,g,S)=>{let{getTraceCommand:G}=await Promise.resolve().then(()=>(op(),_i));await G(u,S.optsWithGlobals())});let F=t.command("scenario").description("Manage scenarios");P(F.command("list").description("List all scenarios in the project").option("-f, --format <format>","Output format: table (default) or json","table"),async()=>{let{listScenariosCommand:u}=await Promise.resolve().then(()=>(qw(),Kw));return u()}),P(F.command("get <id>").description("Get scenario details by ID").option("-f, --format <format>","Output format: table (default) or json","table"),async u=>{let{getScenarioCommand:g}=await Promise.resolve().then(()=>(Bw(),Vw));return g(u)}),P(F.command("create <name>").description("Create a new scenario").requiredOption("--situation <situation>","The situation/context for the scenario").option("--criteria <criteria>","Comma-separated list of evaluation criteria").option("--labels <labels>","Comma-separated list of labels").option("-f, --format <format>","Output format: table (default) or json","table"),async(u,g)=>{let{createScenarioCommand:S}=await Promise.resolve().then(()=>(Yw(),zw));return S(u,g)}),P(F.command("update <id>").description("Update an existing scenario").option("--name <name>","New scenario name").option("--situation <situation>","New situation/context").option("--criteria <criteria>","New comma-separated list of criteria (replaces existing)").option("--labels <labels>","New comma-separated list of labels (replaces existing)").option("-f, --format <format>","Output format: table (default) or json","table"),async(u,g)=>{let{updateScenarioCommand:S}=await Promise.resolve().then(()=>(Xw(),Jw));return S(u,g)}),F.command("run <id>").description("Run a scenario against a target (agent or prompt)").requiredOption("--target <target>","Target to run against, as <type>:<referenceId> (e.g., http:agent_abc123)").option("--wait","Wait for the scenario run to complete").option("-f, --format <format>","Output format: table (default) or json","table").action(async(u,g)=>{let{runScenarioCommand:S}=await Promise.resolve().then(()=>(ev(),Qw));await S(u,g)}),P(F.command("delete <id>").description("Archive (soft-delete) a scenario").option("-f, --format <format>","Output format: table (default) or json","table"),async u=>{let{deleteScenarioCommand:g}=await Promise.resolve().then(()=>(ov(),nv));return g(u)});let H=t.command("suite").description("Manage suites (run plans) \u2014 scenario \xD7 target execution plans");P(H.command("list").description("List all suites in the project").option("-f, --format <format>","Output format: table (default) or json","table"),async()=>{let{listSuitesCommand:u}=await Promise.resolve().then(()=>(av(),rv));return u()}),P(H.command("get <id>").description("Get suite details by ID").option("-f, --format <format>","Output format: table (default) or json","table"),async u=>{let{getSuiteCommand:g}=await Promise.resolve().then(()=>(iv(),sv));return g(u)}),P(H.command("create <name>").description("Create a new suite (run plan)").requiredOption("--scenarios <ids>","Comma-separated scenario IDs").requiredOption("--targets <targets...>","Targets as <type>:<referenceId> (e.g., http:agent_abc)").option("--repeat-count <n>","Number of times to repeat each scenario-target pair","1").option("--labels <labels>","Comma-separated labels").option("--description <desc>","Suite description").option("-f, --format <format>","Output format: table (default) or json","table"),async(u,g)=>{let{createSuiteCommand:S}=await Promise.resolve().then(()=>(lv(),cv));return S(u,g)}),P(H.command("update <id>").description("Update a suite (run plan)").option("--name <name>","New suite name").option("--scenarios <ids>","New comma-separated scenario IDs").option("--targets <targets...>","New targets as <type>:<referenceId>").option("--repeat-count <n>","New repeat count").option("--labels <labels>","New comma-separated labels").option("--description <desc>","New description").option("-f, --format <format>","Output format: table (default) or json","table"),async(u,g)=>{let{updateSuiteCommand:S}=await Promise.resolve().then(()=>(dv(),pv));return S(u,g)}),P(H.command("duplicate <id>").description("Duplicate a suite").option("-f, --format <format>","Output format: table (default) or json","table"),async u=>{let{duplicateSuiteCommand:g}=await Promise.resolve().then(()=>(mv(),uv));return g(u)}),H.command("run <id>").description("Execute a suite run \u2014 schedules all scenario \xD7 target \xD7 repeat jobs").option("--wait","Wait for the suite run to complete before returning").option("-f, --format <format>","Output format: table (default) or json","table").action(async(u,g)=>{let{runSuiteCommand:S}=await Promise.resolve().then(()=>(hv(),gv));await S(u,g)}),P(H.command("delete <id>").description("Archive (soft-delete) a suite").option("-f, --format <format>","Output format: table (default) or json","table"),async u=>{let{deleteSuiteCommand:g}=await Promise.resolve().then(()=>(yv(),fv));return g(u)});let D=t.command("graph").description("Manage custom graphs on dashboards");P(D.command("list").description("List all custom graphs (optionally filter by dashboard)").option("--dashboard-id <id>","Filter by dashboard ID").option("-f, --format <format>","Output format: table (default) or json","table"),async u=>{let{listGraphsCommand:g}=await Promise.resolve().then(()=>(vv(),wv));return g(u)}),P(D.command("get <id>").description("Get a custom graph by ID").option("-f, --format <format>","Output format: table (default) or json","table"),async u=>{let{getGraphCommand:g}=await Promise.resolve().then(()=>(xv(),bv));return g(u)}),P(D.command("create <name>").description("Create a custom graph").option("--dashboard-id <id>","Dashboard to add the graph to").option("--graph <json>","Graph definition as JSON").option("--filters <json>","Filter conditions as JSON").option("--col-span <n>","Column span (1-2)").option("--row-span <n>","Row span (1-2)").option("-f, --format <format>","Output format: table (default) or json","table"),async(u,g)=>{let{createGraphCommand:S}=await Promise.resolve().then(()=>(Av(),Sv));return S(u,g)}),P(D.command("update <id>").description("Update a custom graph").option("--name <name>","New graph name").option("--graph <json>","New graph definition as JSON").option("--filters <json>","New filter conditions as JSON").option("-f, --format <format>","Output format: table (default) or json","table"),async(u,g)=>{let{updateGraphCommand:S}=await Promise.resolve().then(()=>(Tv(),kv));return S(u,g)}),P(D.command("delete <id>").description("Delete a custom graph").option("-f, --format <format>","Output format: table (default) or json","table"),async u=>{let{deleteGraphCommand:g}=await Promise.resolve().then(()=>(Ev(),_v));return g(u)});let U=t.command("trigger").description("Manage triggers (automations) \u2014 alerts, webhooks, and dataset actions");P(U.command("list").description("List all triggers in the project").option("-f, --format <format>","Output format: table (default) or json","table"),async()=>{let{listTriggersCommand:u}=await Promise.resolve().then(()=>(Iv(),Rv));return u()}),P(U.command("get <id>").description("Get trigger details by ID").option("-f, --format <format>","Output format: table (default) or json","table"),async u=>{let{getTriggerCommand:g}=await Promise.resolve().then(()=>(Lv(),Pv));return g(u)}),P(U.command("create <name>").description("Create a new trigger (automation)").requiredOption("--action <action>","Trigger action: SEND_EMAIL, ADD_TO_DATASET, ADD_TO_ANNOTATION_QUEUE, SEND_SLACK_MESSAGE").option("--filters <json>","Trigger filter conditions as JSON").option("--message <text>","Custom alert message").option("--alert-type <type>","Alert severity: CRITICAL, WARNING, INFO").option("--slack-webhook <url>","Slack webhook URL (for SEND_SLACK_MESSAGE action)").option("-f, --format <format>","Output format: table (default) or json","table"),async(u,g)=>{let{createTriggerCommand:S}=await Promise.resolve().then(()=>($v(),Ov));return S(u,g)}),P(U.command("update <id>").description("Update a trigger").option("--name <name>","New trigger name").option("--active <boolean>","Enable or disable the trigger (true/false)").option("--message <text>","New alert message").option("--alert-type <type>","New alert severity").option("-f, --format <format>","Output format: table (default) or json","table"),async(u,g)=>{let{updateTriggerCommand:S}=await Promise.resolve().then(()=>(Dv(),Nv));return S(u,g)}),P(U.command("delete <id>").description("Delete a trigger").option("-f, --format <format>","Output format: table (default) or json","table"),async u=>{let{deleteTriggerCommand:g}=await Promise.resolve().then(()=>(Mv(),jv));return g(u)});let J=t.command("secret").description("Manage project secrets \u2014 encrypted environment variables for agents");P(J.command("list").description("List all secrets in the project (values are never shown)").option("-f, --format <format>","Output format: table (default) or json","table"),async()=>{let{listSecretsCommand:u}=await Promise.resolve().then(()=>(Fv(),Uv));return u()}),P(J.command("get <id>").description("Get secret metadata by ID (value is never shown)").option("-f, --format <format>","Output format: table (default) or json","table"),async u=>{let{getSecretCommand:g}=await Promise.resolve().then(()=>(Wv(),Gv));return g(u)}),P(J.command("create <name>").description("Create a new secret (name must be UPPER_SNAKE_CASE)").requiredOption("--value <value>","The secret value (will be encrypted)").option("-f, --format <format>","Output format: table (default) or json","table"),async(u,g)=>{let{createSecretCommand:S}=await Promise.resolve().then(()=>(Kv(),Hv));return S(u,g)}),P(J.command("update <id>").description("Update a secret's value").requiredOption("--value <value>","The new secret value (will be encrypted)").option("-f, --format <format>","Output format: table (default) or json","table"),async(u,g)=>{let{updateSecretCommand:S}=await Promise.resolve().then(()=>(Vv(),qv));return S(u,g)}),P(J.command("delete <id>").description("Delete a secret").option("-f, --format <format>","Output format: table (default) or json","table"),async u=>{let{deleteSecretCommand:g}=await Promise.resolve().then(()=>(zv(),Bv));return g(u)});let z=t.command("monitor").description("Manage online evaluation monitors \u2014 evaluators running on incoming traces");P(z.command("list").description("List all monitors in the project").option("-f, --format <format>","Output format: table (default) or json","table"),async()=>{let{listMonitorsCommand:u}=await Promise.resolve().then(()=>(Jv(),Yv));return u()}),P(z.command("get <id>").description("Get monitor details by ID").option("-f, --format <format>","Output format: table (default) or json","table"),async u=>{let{getMonitorCommand:g}=await Promise.resolve().then(()=>(Zv(),Xv));return g(u)}),P(z.command("create <name>").description("Create a new online evaluation monitor").requiredOption("--check-type <type>","Evaluator check type (e.g. ragas/toxicity, custom/my-eval)").option("--execution-mode <mode>","Execution mode: ON_MESSAGE (default), AS_GUARDRAIL, MANUALLY","ON_MESSAGE").option("--sample <rate>","Sampling rate 0.0-1.0 (default: 1.0)").option("--evaluator-id <id>","Link to a saved evaluator").option("--level <level>","Evaluation level: trace (default) or thread").option("--parameters <json>","Evaluator settings as JSON").option("-f, --format <format>","Output format: table (default) or json","table"),async(u,g)=>{let{createMonitorCommand:S}=await Promise.resolve().then(()=>(eb(),Qv));return S(u,g)}),P(z.command("update <id>").description("Update a monitor").option("--name <name>","New monitor name").option("--enabled <boolean>","Enable or disable the monitor (true/false)").option("--execution-mode <mode>","Execution mode: ON_MESSAGE, AS_GUARDRAIL, MANUALLY").option("--sample <rate>","Sampling rate 0.0-1.0").option("--parameters <json>","Updated evaluator settings as JSON").option("-f, --format <format>","Output format: table (default) or json","table"),async(u,g)=>{let{updateMonitorCommand:S}=await Promise.resolve().then(()=>(nb(),tb));return S(u,g)}),P(z.command("delete <id>").description("Delete a monitor").option("-f, --format <format>","Output format: table (default) or json","table"),async u=>{let{deleteMonitorCommand:g}=await Promise.resolve().then(()=>(rb(),ob));return g(u)});let K=t.command("simulation-run").description("View simulation run results");P(K.command("list").description("List simulation runs (optionally filter by scenario set or batch)").option("--scenario-set-id <id>","Filter by scenario set ID").option("--batch-run-id <id>","Filter by batch run ID (requires --scenario-set-id)").option("--status <status>","Filter by status (e.g. SUCCESS, FAILED, ERROR, IN_PROGRESS)").option("--name <substring>","Filter by run name substring (case-insensitive)").option("--limit <n>","Max results (default: 20)").option("-f, --format <format>","Output format: table (default) or json","table"),async u=>{let{listSimulationRunsCommand:g}=await Promise.resolve().then(()=>(sb(),ab));return g(u)}),P(K.command("get <runId>").description("Get full details of a simulation run (messages, results, costs)").option("--full","Show full message content instead of truncating long lines").option("-f, --format <format>","Output format: table (default) or json","table"),async(u,g)=>{let{getSimulationRunCommand:S}=await Promise.resolve().then(()=>(cb(),ib));return S(u,g)});let W=t.command("dataset").description("Manage datasets");P(W.command("list").description("List all datasets").option("-f, --format <format>","Output format: table (default) or json","table"),async()=>{let{listCommand:u}=await Promise.resolve().then(()=>(fb(),hb));return u()}),P(W.command("create <name>").description("Create a new dataset").option("-c, --columns <columns>","Column definitions (e.g. input:string,output:string)").option("-f, --format <format>","Output format: table (default) or json","table"),async(u,g)=>{let{createCommand:S}=await Promise.resolve().then(()=>(ip(),yb));return S(u,g)}),P(W.command("get <slugOrId>").description("Get dataset details and preview records").option("-f, --format <format>","Output format: table (default) or json","table"),async u=>{let{getCommand:g}=await Promise.resolve().then(()=>(vb(),wb));return g(u)}),P(W.command("delete <slugOrId>").description("Delete (archive) a dataset").option("-f, --format <format>","Output format: table (default) or json","table"),async u=>{let{deleteCommand:g}=await Promise.resolve().then(()=>(Sb(),xb));return g(u)}),P(W.command("upload <slug> <file>").description("Upload a file to a dataset (creates if not found)").option("--if-exists <strategy>","Strategy when dataset exists: append (default), replace, error"),async(u,g,S)=>{let{uploadCommand:G}=await Promise.resolve().then(()=>(_b(),Tb));return G(u,g,S)}),W.command("download <slugOrId>").description("Download dataset records as CSV or JSONL").option("-f, --format <format>","Output format: csv or jsonl","csv").action(async(u,g)=>{let{downloadCommand:S}=await Promise.resolve().then(()=>(Ib(),Rb));await S(u,g)}),P(W.command("update <slugOrId>").description("Update a dataset name or columns").option("--name <name>","New dataset name").option("--columns <columns>","New column definitions (e.g. input:string,output:string)").option("-f, --format <format>","Output format: table (default) or json","table"),async(u,g)=>{let{updateCommand:S}=await Promise.resolve().then(()=>(Lb(),Pb));return S(u,g)});let oe=W.command("records").description("Manage dataset records");P(oe.command("list <slugOrId>").description("List records in a dataset").option("--page <n>","Page number (default: 1)").option("--limit <n>","Records per page (default: 20)").option("-f, --format <format>","Output format: table (default) or json","table"),async(u,g)=>{let{recordsListCommand:S}=await Promise.resolve().then(()=>($b(),Ob));return S(u,g)}),P(oe.command("add <slugOrId>").description("Add records to a dataset").option("--json <json>","JSON array of records (inline)").option("--file <path>","Read JSON array of records from a file").option("--stdin","Read JSON array from stdin").option("-f, --format <format>","Output format: text (default) or json","text"),async(u,g)=>{let{recordsAddCommand:S}=await Promise.resolve().then(()=>(jb(),Db));return S(u,g)}),P(oe.command("update <slugOrId> <recordId>").description("Update a single record in a dataset").requiredOption("--json <json>","JSON object with updated fields").option("-f, --format <format>","Output format: text (default) or json","text"),async(u,g,S)=>{let{recordsUpdateCommand:G}=await Promise.resolve().then(()=>(Fb(),Ub));return G(u,g,S)}),P(oe.command("delete <slugOrId> <recordIds...>").description("Delete records from a dataset").option("-f, --format <format>","Output format: text (default) or json","text"),async(u,g)=>{let{recordsDeleteCommand:S}=await Promise.resolve().then(()=>(Hb(),Wb));return S(u,g)});let te=t.command("projects").description("Manage organization projects");P(te.command("list").description("List all projects in the organization").option("--page <page>","Page number","1").option("--limit <limit>","Items per page","50").option("-f, --format <format>","Output format: table (default) or json","table"),async u=>{let{listProjectsCommand:g}=await Promise.resolve().then(()=>(qb(),Kb));return g({page:u.page?Number(u.page):void 0,limit:u.limit?Number(u.limit):void 0})}),P(te.command("get <id>").description("Show details for a project").option("-f, --format <format>","Output format: text (default) or json","text"),async u=>{let{getProjectCommand:g}=await Promise.resolve().then(()=>(Bb(),Vb));return g(u)}),P(te.command("create").description("Create a new project (returns a one-time service API key)").requiredOption("--name <name>","Project name").requiredOption("--language <lang>","Programming language (e.g. python, typescript)").requiredOption("--framework <fw>","Framework (e.g. langchain, openai, vercel-ai)").option("--team-id <id>","Existing team ID to assign the project to").option("--new-team-name <name>","Create a new team with this name").option("-f, --format <format>","Output format: text (default) or json","text"),async u=>{let{createProjectCommand:g}=await Promise.resolve().then(()=>(Yb(),zb));return g(u)}),P(te.command("update <id>").description("Update a project's metadata").option("--name <name>","New project name").option("--language <lang>","New language").option("--framework <fw>","New framework").option("--pii-redaction-level <level>","PII redaction: STRICT, ESSENTIAL, or DISABLED").option("-f, --format <format>","Output format: text (default) or json","text"),async(u,g)=>{let{updateProjectCommand:S}=await Promise.resolve().then(()=>(Xb(),Jb));return S(u,g)}),P(te.command("delete <id>").description("Archive a project (soft-delete)").option("-f, --format <format>","Output format: text (default) or json","text"),async u=>{let{deleteProjectCommand:g}=await Promise.resolve().then(()=>(Qb(),Zb));return g(u)});let ce=t.command("api-keys").description("Manage organization API keys");P(ce.command("list").description("List all API keys in the organization").option("-f, --format <format>","Output format: table (default) or json","table"),async()=>{let{listApiKeysCommand:u}=await Promise.resolve().then(()=>(tx(),ex));return u()}),P(ce.command("create").description("Create a new API key (token is shown once)").requiredOption("--name <name>","Human-readable name for the key").option("--key-type <type>","Key type: personal or service","service").option("--description <desc>","Optional description").option("--expires-at <date>","Expiration date (ISO 8601)").option("--project-id <id...>","Project IDs to scope the key to (service keys only, repeatable)").option("-f, --format <format>","Output format: text (default) or json","text"),async u=>{let{createApiKeyCommand:g}=await Promise.resolve().then(()=>(ox(),nx));return g(u)}),P(ce.command("revoke <id>").description("Revoke an API key (cannot be reactivated)").option("-f, --format <format>","Output format: text (default) or json","text"),async u=>{let{revokeApiKeyCommand:g}=await Promise.resolve().then(()=>(sx(),ax));return g(u)});let Q=t.command("daemon").description("Manage the background daemon that serves CLI commands from a warm process (auto-spawned; set LANGWATCH_NO_DAEMON=1 to disable).");return Q.command("start").description("Start the daemon (backgrounded unless --foreground)").option("--foreground","Run the daemon in this process instead of backgrounding it").option("--idle-timeout <ms>","Exit after this many ms with no requests (default 600000)").action(async u=>{let{daemonStartCommand:g}=await Promise.resolve().then(()=>(Ui(),Mi));await g(u)}),Q.command("stop").description("Stop the running daemon and remove its socket").action(async()=>{let{daemonStopCommand:u}=await Promise.resolve().then(()=>(Ui(),Mi));await u()}),Q.command("status").description("Show the running daemon's pid, uptime, and request counts").option("--json","emit machine-readable JSON").action(async u=>{let{daemonStatusCommand:g}=await Promise.resolve().then(()=>(Ui(),Mi));await g(u)}),Sd(t),t}var kx,Ax,ER,CR,RR,IR,PR,LR,xr=h(()=>{"use strict";kx=require("commander");Zp();ht();Ax=async(t,e)=>{let{addCommand:n}=await Promise.resolve().then(()=>(Qu(),Zu));return n(t,e)},ER=async t=>{let{removeCommand:e}=await Promise.resolve().then(()=>(tm(),em));return e(t)},CR=async()=>{let{initCommand:t}=await Promise.resolve().then(()=>(om(),nm));return t()},RR=async t=>{let{loginCommand:e}=await Promise.resolve().then(()=>(Tm(),km));return e(t)},IR=async()=>{let{syncCommand:t}=await Promise.resolve().then(()=>(Om(),Lm));return t()},PR=async t=>{let{pullCommand:e}=await Promise.resolve().then(()=>(Gc(),Em));return e(t)},LR=async t=>{let{pushCommand:e}=await Promise.resolve().then(()=>(Wc(),Pm));return e(t)}});var Cp=b(require("module")),_p,Ep;try{(Ep=(_p=Cp.default).enableCompileCache)==null||Ep.call(_p)}catch(t){}var Ex=require("dotenv");Vi();Bi();fo();zi();var Ko=b(require("fs")),Yp=b(require("path"));fo();var zx=6e4,zp=2;function Yx(t){return Yp.join(t.socketDir,`${t.fingerprint.slice(0,16)}.hint`)}function Jp(t){let e=Yx(t),n=Date.now();try{Va(t.socketDir)}catch(o){return!1}try{let o=[];try{let r=JSON.parse(Ko.readFileSync(e,"utf8"));Array.isArray(r)&&(o=r.filter(a=>typeof a=="number"&&n-a<zx))}catch(r){}if(o.push(n),o.length>=zp){try{Ko.unlinkSync(e)}catch(r){}return!0}return Ko.writeFileSync(e,JSON.stringify(o.slice(-zp)),{mode:384}),!1}catch(o){return!1}}function Sp(t){var e;(e=process.env.DEBUG)!=null&&e.includes("langwatch")&&process.stderr.write(`langwatch:daemon ${t}
|
|
3766
|
-
`)}async function _x(t){var s;let e=t.slice(2),n=Wp({args:e,env:process.env,daemonDisabledByConfig:Kp(process.env),stdoutIsTty:!!process.stdout.isTTY,stderrIsTty:!!process.stderr.isTTY,stdinIsTty:!!process.stdin.isTTY,platform:process.platform});if(!n.eligible){Sp(`in-process (${n.reason})`),await Ap(t);return}let o=Ho(process.env);if(!qa(o.socketPath)){Sp("in-process (socket path too long for this platform)"),await Ap(t);return}let r=Ya(process.env),a=await Mp({socketPath:o.socketPath,fingerprint:o.fingerprint,cliVersion:"0.
|
|
3766
|
+
`)}async function _x(t){var s;let e=t.slice(2),n=Wp({args:e,env:process.env,daemonDisabledByConfig:Kp(process.env),stdoutIsTty:!!process.stdout.isTTY,stderrIsTty:!!process.stderr.isTTY,stdinIsTty:!!process.stdin.isTTY,platform:process.platform});if(!n.eligible){Sp(`in-process (${n.reason})`),await Ap(t);return}let o=Ho(process.env);if(!qa(o.socketPath)){Sp("in-process (socket path too long for this platform)"),await Ap(t);return}let r=Ya(process.env),a=await Mp({socketPath:o.socketPath,fingerprint:o.fingerprint,cliVersion:"0.36.0",build:Ka("0.36.0",(s=t[1])!=null?s:""),args:e,cwd:process.cwd(),env:r,colorLevel:qp(r)});if(a.served){process.exitCode=a.exitCode;return}Sp(`in-process (${a.reason})`),a.evict?await za(o.socketPath):Hp(process.env)&&t[1]&&Jp(o)&&Ja({cliPath:t[1],env:r,identity:o}),await Ap(t)}async function Ap(t){let{buildProgram:e}=await Promise.resolve().then(()=>(xr(),Tx));await e().parseAsync(t)}var OR=process.argv[2]==="daemon"&&process.argv[3]==="start"&&process.argv.includes("--foreground");OR||(0,Ex.config)({quiet:!0});_x(process.argv).catch(t=>{let e=t instanceof Error?t.message:String(t);process.stderr.write(`Error: ${e}
|
|
3767
3767
|
`),process.exitCode=1});
|
|
3768
3768
|
//# sourceMappingURL=bundle.js.map
|