@ciandt-flow/flow-ai-obs 0.9.2 → 0.9.3-beta.750
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/cli.js +194 -186
- package/dist/index.js +15 -14
- package/dist/setup.js +5 -5
- package/package.json +4 -2
package/dist/cli.js
CHANGED
|
@@ -1,245 +1,253 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
'use strict';var
|
|
3
|
-
`);}catch(
|
|
4
|
-
\u256D${
|
|
5
|
-
\u2502${
|
|
6
|
-
\u2502${
|
|
7
|
-
\u2570${
|
|
8
|
-
|
|
9
|
-
`);}function
|
|
2
|
+
'use strict';var Ue=require('readline/promises'),fs=require('https'),A=require('fs'),gt=require('os'),Rt=require('path'),child_process=require('child_process'),Ps=require('http'),util=require('util'),crypto=require('crypto');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var Ue__namespace=/*#__PURE__*/_interopNamespace(Ue);var fs__default=/*#__PURE__*/_interopDefault(fs);var A__namespace=/*#__PURE__*/_interopNamespace(A);var gt__namespace=/*#__PURE__*/_interopNamespace(gt);var Rt__namespace=/*#__PURE__*/_interopNamespace(Rt);var Ps__default=/*#__PURE__*/_interopDefault(Ps);var be=Object.defineProperty;var is=Object.getOwnPropertyDescriptor;var as=Object.getOwnPropertyNames;var cs=Object.prototype.hasOwnProperty;var Dt=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var E=(t,e,r)=>()=>{if(r)throw r[0];try{return t&&(e=t(t=0)),e}catch(n){throw r=[n],n}};var ls=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(r){throw e=0,r}},N=(t,e)=>{for(var r in e)be(t,r,{get:e[r],enumerable:true});},us=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of as(e))!cs.call(t,s)&&s!==r&&be(t,s,{get:()=>e[s],enumerable:!(n=is(e,s))||n.enumerable});return t};var P=t=>us(be({},"__esModule",{value:true}),t);var Ie={};N(Ie,{bold:()=>b,cyan:()=>U,dim:()=>g,green:()=>k,red:()=>I,yellow:()=>R});function yt(t,e){return ds?r=>`\x1B[${t}m${r}\x1B[${e}m`:r=>r}var ds,k,I,R,U,b,g,ut=E(()=>{"use strict";ds=!process.env.NO_COLOR&&process.stdout.isTTY;k=yt("32","39"),I=yt("31","39"),R=yt("33","39"),U=yt("36","39"),b=yt("1","22"),g=yt("2","22");});var Mt=ls((di,ps)=>{ps.exports={name:"@ciandt-flow/flow-ai-obs",version:"0.9.3-beta.750",description:"Claude Code hooks for Langfuse OTLP tracing \u2014 cross-platform",main:"dist/index.js",bin:{"flow-ai-obs":"dist/cli.js","flow-ai-obs-setup":"dist/setup.js"},scripts:{build:"tsup",test:"jest",typecheck:"tsc --noEmit",lint:"eslint src bin scripts",format:'prettier --write "src/**/*.ts" "bin/**/*.ts" "scripts/**/*.ts"',"format:check":'prettier --check "src/**/*.ts" "bin/**/*.ts" "scripts/**/*.ts"',"security-scan":"trufflehog filesystem src/ --fail --no-update --exclude-paths .trufflehogignore",postinstall:`node -e "require('fs').existsSync('dist/setup.js') && require('child_process').execFileSync(process.execPath, ['dist/setup.js'], {stdio:'inherit'})"`,prepublishOnly:"npm run security-scan && npm run build","release:npm":"changeset publish",changeset:"changeset","version-packages":"changeset version","install:hooks":"node dist/cli.js install","auth:login":"node dist/cli.js auth login","auth:logout":"node dist/cli.js auth logout","auth:status":"node dist/cli.js auth status",smoke:"bash scripts/smoke-test.sh","smoke:debug":"bash scripts/smoke-test.sh --debug","smoke:send":"bash scripts/smoke-test.sh --send --allow-http --debug",regression:"jest --config jest.regression.config.js --forceExit","regression:update":"UPDATE_GOLDEN=1 jest --config jest.regression.config.js --forceExit"},files:["dist/","README.md","LICENSE.md"],keywords:["claude-code","langfuse","observability","otlp","hooks","flow","ciandt"],author:"CI&T Flow Team",license:"SEE LICENSE IN LICENSE.md",private:!1,dependencies:{},optionalDependencies:{keytar:"7.9.0"},devDependencies:{"@changesets/changelog-github":"^0.6.0","@changesets/cli":"^2.30.0","@types/jest":"^30.0.0","@types/node":"^25.8.0",jest:"^30.4.2","ts-jest":"^29.4.9",tsup:"^8.5.1","eslint-config-prettier":"^10.1.5",prettier:"^3.5.3",typescript:"^6.0.3","typescript-eslint":"^8.33.0"},engines:{node:">=18.0.0"},overrides:{esbuild:"^0.28.1"},publishConfig:{registry:"https://registry.npmjs.org",access:"public"},repository:{type:"git",url:"git+https://github.com/CI-T-HyperX/flow-codeassistant-observability.git"}};});function Z(){return process.stdout.isTTY===true&&process.stdin.isTTY===true&&!process.argv.includes("--no-interactive")}async function Bt(t,e){let r=Ue__namespace.createInterface({input:process.stdin,output:process.stdout}),s=`${t} ${e===true?"(Y/n)":e===false?"(y/N)":"(y/n)"}: `;for(let i=1;i<=3;i++)try{let o=(await r.question(s)).trim().toLowerCase();if(o===""&&e!==void 0)return r.close(),e;if(o==="y"||o==="yes")return r.close(),!0;if(o==="n"||o==="no")return r.close(),!1;i<3&&process.stdout.write(` Invalid input. Please answer "y" or "n".
|
|
3
|
+
`);}catch(o){throw r.close(),o}if(r.close(),e!==void 0)return e;throw new Error("Too many invalid attempts for yes/no prompt")}async function Pe(t,e){let r=Ue__namespace.createInterface({input:process.stdin,output:process.stdout});try{let n=(await r.question(`${t}: `)).trim();if(e);return n}catch(n){throw n}finally{r.close();}}var Ne=E(()=>{"use strict";});var At={};N(At,{checkForUpdate:()=>Ss,checkForUpdateInteractive:()=>Ts,fetchLatestVersionAsync:()=>vr,isNewer:()=>Ot,primeUpdateCache:()=>_s,runUpdate:()=>kr});function C(){return Ce||(Ce=Mt()),Ce}function Ot(t,e){let r=i=>{let o=String(i).replace(/^v/,"").match(/^(\d+)\.(\d+)\.(\d+)/);return o?[+o[1],+o[2],+o[3]]:null},n=r(t),s=r(e);return !n||!s?false:s[0]!==n[0]?s[0]>n[0]:s[1]!==n[1]?s[1]>n[1]:s[2]>n[2]}function xe(){try{let t=JSON.parse(A__namespace.default.readFileSync(Lr,"utf8"));return typeof t.latestVersion!="string"||Date.now()-t.checkedAt>=hs?null:t}catch{return null}}function De(t,e,r=Date.now()){try{A__namespace.default.writeFileSync(Lr,JSON.stringify({latestVersion:t,updatePriority:e??null,checkedAt:r}),{mode:384});}catch{}}function Me(t){let e=C().name,r=fs__default.default.get(`https://registry.npmjs.org/${encodeURIComponent(e)}/latest`,{timeout:Es},n=>{if(n.statusCode!==200)return n.resume(),t(new Error(`HTTP ${n.statusCode}`));let s="";n.setEncoding("utf8"),n.on("data",i=>{s+=i;}),n.on("end",()=>{try{let i=JSON.parse(s);if(typeof i.version!="string")throw new Error("no version field");t(null,{version:i.version,updatePriority:typeof i.updatePriority=="string"?i.updatePriority:null});}catch(i){t(i);}});});r.on("error",t),r.on("timeout",()=>{r.destroy(new Error("timeout"));});}function $e(t){let e=C().name,n=` Update available: ${C().version} \u2192 ${t}`,s=` Run: npm install -g ${e}`,i=Math.max(n.length,s.length)+2,o="\u2500".repeat(i);process.stderr.write(`
|
|
4
|
+
\u256D${o}\u256E
|
|
5
|
+
\u2502${n.padEnd(i)}\u2502
|
|
6
|
+
\u2502${s.padEnd(i)}\u2502
|
|
7
|
+
\u2570${o}\u256F
|
|
8
|
+
|
|
9
|
+
`);}function Fe(t){let e=C().name;process.stderr.write(`
|
|
10
10
|
[${e}] Critical update detected \u2014 auto-updating to ${t}...
|
|
11
11
|
|
|
12
|
-
`);let
|
|
13
|
-
\u256D${
|
|
14
|
-
\u2502${i.padEnd(
|
|
15
|
-
\u2502${
|
|
16
|
-
\u2502${
|
|
17
|
-
\u2570${
|
|
18
|
-
`),new Promise(
|
|
19
|
-
`),
|
|
20
|
-
`),new Promise(
|
|
21
|
-
|
|
22
|
-
`);else {let c
|
|
23
|
-
|
|
24
|
-
`);}
|
|
25
|
-
`;try{
|
|
26
|
-
`);}}var
|
|
12
|
+
`);let r=child_process.spawn("npm",["install","-g",`${e}@${t}`],{detached:true,stdio:"ignore",shell:process.platform==="win32",windowsHide:true});r.on("error",()=>{}),r.unref();}async function ws(t,e=1e4){let r=Dt("readline"),n=C().name,i=` Update available: ${C().version} \u2192 ${t}`,o=` Run: npm install -g ${n}`,c=" Install now? [y/N]: ",l=Math.max(i.length,o.length,c.length-2)+2,a="\u2500".repeat(l);return process.stderr.write(`
|
|
13
|
+
\u256D${a}\u256E
|
|
14
|
+
\u2502${i.padEnd(l)}\u2502
|
|
15
|
+
\u2502${o.padEnd(l)}\u2502
|
|
16
|
+
\u2502${c.padEnd(l)}\u2502
|
|
17
|
+
\u2570${a}\u256F
|
|
18
|
+
`),new Promise(d=>{let m=r.createInterface({input:process.stdin,output:void 0,terminal:false}),T=false;function S(w){T||(T=true,clearTimeout(p),m.close(),process.stderr.write(`
|
|
19
|
+
`),d(w));}let p=setTimeout(()=>S(false),e);m.once("line",w=>S(w.trim().toLowerCase()==="y")),m.once("close",()=>S(false));})}async function kr(t){let e=C().name;return process.stderr.write(` Installing ${e}@${t}...
|
|
20
|
+
`),new Promise(r=>{let n=child_process.spawn("npm",["install","-g",`${e}@${t}`],{stdio:"inherit",shell:process.platform==="win32"}),s=false;function i(o,c){if(!s){if(s=true,o)process.stderr.write(` \u2713 Updated to ${t}. Please restart the command.
|
|
21
|
+
|
|
22
|
+
`);else {let l=c?` (${c})`:"";process.stderr.write(` \u2717 Update failed${l} \u2014 continuing with current version.
|
|
23
|
+
|
|
24
|
+
`);}r();}}n.on("close",(o,c)=>i(o===0,c??void 0)),n.on("error",o=>i(false,o.code));})}function vr(){return new Promise(t=>{Me((e,r)=>t(e||!r?null:r));})}function Ss(){try{let t=xe();if(t){Ot(C().version,t.latestVersion)&&(t.updatePriority==="auto"?Fe(t.latestVersion):$e(t.latestVersion));return}setImmediate(()=>{Me((e,r)=>{e||!r||(De(r.version,r.updatePriority),Ot(C().version,r.version)&&(r.updatePriority==="auto"?Fe(r.version):$e(r.version)));});});}catch{}}async function Ts(t={}){try{let e=xe();if(e){if(!Ot(C().version,e.latestVersion))return}else {let n=await vr();if(!n||(De(n.version,n.updatePriority),!Ot(C().version,n.version)))return;e={latestVersion:n.version,updatePriority:n.updatePriority,checkedAt:Date.now()};}if(e.updatePriority==="auto"){Fe(e.latestVersion);return}if(!Z()){$e(e.latestVersion);return}await ws(e.latestVersion,t.timeoutMs)&&await kr(e.latestVersion);}catch{}}function _s(){try{if(xe())return;setImmediate(()=>{Me((t,e)=>{t||!e||Ot(C().version,e.version)&&De(e.version,e.updatePriority,0);});});}catch{}}var Ce,Lr,hs,Es,Lt=E(()=>{"use strict";Ne();Lr=Rt__namespace.default.join(gt__namespace.default.tmpdir(),"flow-obs-update-cache.json"),hs=1440*60*1e3,Es=3e3;});var Rr={};N(Rr,{BUFFER:()=>$,CONFIG_DIR_NAME:()=>Wt,CONFIG_FILE_NAME:()=>jt,DEBUG_LOG_FILENAME:()=>Be,ENV:()=>f,FEATURES:()=>Ls,FLOW_URLS:()=>Os,HOOK_TIMEOUTS:()=>pt,INSTALLER:()=>Vt,NATIVE_OTEL:()=>tt,OTLP:()=>ce,STATE_FILE_PREFIX:()=>ks,TRACE_LIMITS:()=>B,VAULT:()=>Ht,getFlowBaseUrl:()=>Q,getFlowUrls:()=>dt,getLlmProxy:()=>As,getMetrics:()=>le});function Q(){let t=process.env.FLOW_BASE_URL;return t&&t.trim()?t.trim():ys}function dt(){let t=Q();return {AUTH_ENGINE:process.env.FLOW_AUTH_ENGINE_URL||`${t}/auth-engine-api/v2/api-key/token`,GATEWAY_TRACES:process.env.FLOW_GATEWAY_TRACES_URL||`${t}/flow-langfuse-gateway/v1/traces`,GATEWAY_HEALTH:process.env.FLOW_GATEWAY_HEALTH_URL||`${t}/flow-langfuse-gateway/v1/health`,OTEL_ENDPOINT:process.env.FLOW_OTEL_ENDPOINT_URL||`${t}/otel`}}function As(){let t=Q();return {ANTHROPIC_BASE_URL:process.env.FLOW_LLM_PROXY_URL??`${t}/flow-llm-proxy/`,ANTHROPIC_MODEL:process.env.FLOW_LLM_PROXY_MODEL??"anthropic.claude-4-6-sonnet",ANTHROPIC_SMALL_FAST_MODEL:process.env.FLOW_LLM_PROXY_SMALL_MODEL??"anthropic.claude-4-6-haiku",CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS:"1"}}function le(){let t=Q();return {API_URL:process.env.FLOW_METRICS_URL||`${t}/metrics-collector-api/log-event`,BOOSTER:"flow-ai-obs"}}var ys,Os,Ht,Wt,jt,ce,tt,f,Ls,Vt,pt,$,Be,B,ks,v=E(()=>{"use strict";ys="https://flow.ciandt.com";Os=dt(),Ht={SERVICE:"flow-plugins-cli",ACCOUNT_CREDS:"credentials",ACCOUNT_TOKEN:"token-cache"},Wt="FLOW-nodejs",jt="config.json",ce={SCOPE_NAME:"flow-ai-obs",SCOPE_VERSION:"0.1.0"};tt={CLAUDE_CODE_ENABLE_TELEMETRY:"1",OTEL_EXPORTER_OTLP_PROTOCOL:"http/json",OTEL_METRICS_EXPORTER:"otlp",OTEL_LOGS_EXPORTER:"otlp",OTEL_LOG_TOOL_DETAILS:"1",OTEL_LOG_USER_PROMPTS:"1"},f={FLOW_TELEMETRY:"FLOW_TELEMETRY",FLOW_TELEMETRY_GATEWAY:"FLOW_TELEMETRY_GATEWAY_URL",LANGFUSE_BASE_URL:"LANGFUSE_BASE_URL",LANGFUSE_PUBLIC_KEY:"LANGFUSE_PUBLIC_KEY",LANGFUSE_SECRET_KEY:"LANGFUSE_SECRET_KEY",ANTHROPIC_MODEL:"ANTHROPIC_MODEL",ANTHROPIC_AUTH_TOKEN:"ANTHROPIC_AUTH_TOKEN",FLOW_OBS_DEBUG:"FLOW_TELEMETRY_DEBUG",FLOW_OBS_ALLOW_HTTP:"FLOW_TELEMETRY_ALLOW_HTTP",FLOW_OBS_USE_JSON_VAULT:"FLOW_TELEMETRY_USE_JSON_VAULT",BUFFER_TTL_DAYS:"FLOW_TELEMETRY_BUFFER_TTL_DAYS",BUFFER_MAX_FILES:"FLOW_TELEMETRY_BUFFER_MAX_FILES",FLOW_USER_EMAIL:"FLOW_USER_EMAIL",OTEL_EXPORTER_OTLP_HEADERS:"OTEL_EXPORTER_OTLP_HEADERS"},Ls={KEYCHAIN_ENABLED:!1},Vt={LOCK_STALE_MS:3e4,CONNECTIVITY_MAX_RETRY:3,CONNECTIVITY_RETRY_MS:2e3,CLI:"flow-ai-obs "},pt={UserPromptSubmit:30,PreToolUse:3,PostToolUse:10,Stop:15},$={FILE_PREFIX:"flow-obs-buffer-",DEFAULT_TTL_DAYS:4,MIN_TTL_DAYS:1,MAX_TTL_DAYS:30,DEFAULT_MAX_FILES:50,MIN_MAX_FILES:1,MAX_MAX_FILES:500,REPLAY_BATCH_SIZE:10},Be="flow-ai-obs-debug.log",B={TOOL_INPUT:2e4,TOOL_OUTPUT:2e4,TRACE_OUTPUT:2e4,USER_INSTRUCTION:1e4,TRACE_INPUT:5e4,TOOL_BRIEF:60};ks="flow-obs-";});function u(...t){if(process.env[f.FLOW_OBS_DEBUG]!=="1")return;let e=`[${new Date().toISOString()}] ${t.join(" ")}
|
|
25
|
+
`;try{A.writeFileSync(Is,e,{flag:"a"});}catch(r){process.stderr.write(`[flow-obs debug ERROR] ${r.message}
|
|
26
|
+
`);}}var Is,H=E(()=>{"use strict";v();Is=Rt.join(gt.tmpdir(),Be);});function Cs(t){if(!Ns.test(t))throw new Error(`Invalid tenant value: "${t}". Tenant must be lowercase alphanumeric and hyphens (1-64 chars).`)}function $s(t,e){let r=e.length>400?e.slice(0,400)+"\u2026":e;u("toAuthError",`status=${t} body=${r}`);try{let n=JSON.parse(e);if(typeof n.error=="string"&&(u("toAuthError",`api_error_code=${n.error}`+(n.message?` api_message=${n.message}`:"")),br[n.error]))return new ft(br[n.error])}catch{}return t===401||t===403||t===500?new ft("Invalid credentials"):t>=400&&t<500?new ft("Authentication request was rejected"):new Error("Authentication service unavailable, please try again later")}function F(t){return new Promise((e,r)=>{try{Cs(t.tenant);}catch(a){return r(a)}let n=JSON.stringify({clientSecret:t.clientSecret}),s=new URL(dt().AUTH_ENGINE),i=s.protocol==="https:",o={hostname:s.hostname,port:s.port||(i?443:80),path:s.pathname+s.search,method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(n),FlowTenant:t.tenant}};u("getToken",`requesting token tenant=${t.tenant} host=${o.hostname} path=${o.path}`);let l=(i?fs__default.default:Ps__default.default).request(o,a=>{let d=[];a.on("data",m=>d.push(m)),a.on("end",()=>{let m=d.join("");if((a.statusCode??0)>=400)return r($s(a.statusCode??0,m));let T;try{T=JSON.parse(m);}catch{return r(new Error("Invalid response from auth engine"))}let S=T.expires_at??new Date(Date.now()+(T.expires_in??3600)*1e3).toISOString();e({accessToken:T.access_token??"",expiresAt:S});});});l.on("error",a=>r(new Error(`Network error: ${a.message}`))),l.write(n),l.end();})}var ft,Ns,br,mt=E(()=>{"use strict";v();H();ft=class extends Error{constructor(e){super(e),this.name="AuthError";}},Ns=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$|^[a-z0-9]$/;br={INVALID_CLIENT_SECRET:"Invalid Client Secret \u2014 check the value and try again",INVALID_CLIENT_ID:"Invalid Client ID \u2014 check the value and try again",INVALID_TENANT:"Invalid Tenant \u2014 check the value and try again",TENANT_NOT_FOUND:"Tenant not found \u2014 verify the tenant identifier"};});function Ir(){return process.platform==="win32"?false:process.getuid?.()===0}function ue(){if(Ir())return process.stderr.write(`
|
|
27
27
|
`+I(` \u2717 flow-ai-obs is not supported in a sudo context.
|
|
28
28
|
|
|
29
|
-
`)+
|
|
29
|
+
`)+U(` npm install -g @ciandt-flow/flow-ai-obs
|
|
30
30
|
`)+`
|
|
31
|
-
`),1}var
|
|
32
|
-
`,{encoding:"utf8",mode:384});try{
|
|
33
|
-
`,{encoding:"utf8",mode:384});try{O__namespace.chmodSync(e,384);}catch{}}finally{xn(n);}}var Fs,jt=g(()=>{"use strict";L();ft();ie();He();Fs=Mt.LOCK_STALE_MS;});function Wt(){let t=mt__namespace.default.homedir();if(process.platform==="darwin")return Lt__namespace.default.join(t,"Library","Preferences",Dt,Bt);if(process.platform==="win32"){let n=process.env.APPDATA??Lt__namespace.default.join(t,"AppData","Roaming");return Lt__namespace.default.join(n,Dt,Bt)}let e=process.env.XDG_CONFIG_HOME??Lt__namespace.default.join(t,".config");return Lt__namespace.default.join(e,Dt,Bt)}function Ye(){try{let t=O__namespace.default.readFileSync(Wt(),"utf8");return JSON.parse(t)}catch{return {}}}function Bn(t){let e=Wt();O__namespace.default.mkdirSync(Lt__namespace.default.dirname(e),{recursive:true}),O__namespace.default.writeFileSync(e,JSON.stringify(t,null,2),{encoding:"utf8",mode:384});}var Ve,le,Mn=g(()=>{"use strict";L();Ve={credentials:"credentials","token-cache":"tokenCache"};le=class{static isAvailable(){return !0}static hasExistingData(){try{if(!O__namespace.default.existsSync(Wt()))return !1;let e=JSON.parse(O__namespace.default.readFileSync(Wt(),"utf8"));return !!(e&&e.credentials)}catch{return !1}}async getSecret(e,n){let r=Ye(),o=Ve[n]??n,i=r[o];return i?typeof i=="string"?i:JSON.stringify(i):null}async setSecret(e,n,r){let o=Ye(),i=Ve[n]??n;if(n==="token-cache")try{o[i]=JSON.parse(r);}catch{o[i]=r;}else o[i]=r;Bn(o);}async deleteSecret(e,n){let r=Ye(),o=Ve[n]??n;return o in r?(delete r[o],Bn(r),!0):!1}getStoragePath(){return `config.json (unencrypted) \u2014 ${Wt()}`}};});var Hn={};C(Hn,{MacOsKeyVaultProvider:()=>Je});var Ge,Je,jn=g(()=>{"use strict";Ge=util.promisify(child_process.execFile),Je=class{static async isAvailable(){try{return O.accessSync("/usr/bin/security",O.constants.X_OK),!0}catch{return !1}}async getSecret(e,n){try{let{stdout:r}=await Ge("security",["find-generic-password","-w","-a",n,"-s",e]);return r.trim()||null}catch{return null}}async setSecret(e,n,r){await Ge("security",["add-generic-password","-U","-a",n,"-s",e,"-w",r]);}async deleteSecret(e,n){try{return await Ge("security",["delete-generic-password","-a",n,"-s",e]),!0}catch{return !1}}getStoragePath(){return "macOS Keychain"}};});var Vn={};C(Vn,{LinuxKeyVaultProvider:()=>Ke});var Wn,Ke,Yn=g(()=>{"use strict";Wn=util.promisify(child_process.execFile),Ke=class{static async isAvailable(){let e=["/usr/bin/secret-tool","/bin/secret-tool","/usr/local/bin/secret-tool"];for(let n of e)try{return O.accessSync(n,O.constants.X_OK),!0}catch{}return !1}async getSecret(e,n){try{let{stdout:r}=await Wn("secret-tool",["lookup","service",e,"account",n]);return r.trim()||null}catch{return null}}async setSecret(e,n,r){await new Promise((o,i)=>{let s=child_process.spawn("secret-tool",["store","--label",e,"service",e,"account",n]);s.on("error",i),s.on("close",a=>{a===0?o():i(new Error(`secret-tool exited with code ${a}`));}),s.stdin.write(r),s.stdin.end();});}async deleteSecret(e,n){try{return await Wn("secret-tool",["clear","service",e,"account",n]),!0}catch{return !1}}getStoragePath(){return "Linux Secret Service (libsecret)"}};});var Gn={};C(Gn,{WindowsKeyVaultProvider:()=>qe});var qe,Jn=g(()=>{"use strict";qe=class{static async isAvailable(){try{return await $t("keytar").getPassword("__flow_probe__","__flow_probe__"),!0}catch{return !1}}async getSecret(e,n){return $t("keytar").getPassword(e,n)}async setSecret(e,n,r){await $t("keytar").setPassword(e,n,r);}async deleteSecret(e,n){return $t("keytar").deletePassword(e,n)}getStoragePath(){return "Windows Credential Manager"}};});async function Kn(){return await Ks()??new le}async function Ks(){switch(process.platform){case "darwin":{let{MacOsKeyVaultProvider:t}=await Promise.resolve().then(()=>(jn(),Hn));return await t.isAvailable()?new t:null}case "linux":{let{LinuxKeyVaultProvider:t}=await Promise.resolve().then(()=>(Yn(),Vn));return await t.isAvailable()?new t:null}case "win32":{let{WindowsKeyVaultProvider:t}=await Promise.resolve().then(()=>(Jn(),Gn));return await t.isAvailable()?new t:null}default:return null}}var qn=g(()=>{"use strict";Mn();});var zn={};C(zn,{clearFlowCredentials:()=>Xs,getConfigPath:()=>Zs,getEmailFromToken:()=>ue,getFlowCredentials:()=>Xn,getTokenCache:()=>Yt,hasCredentials:()=>Qs,isTokenValid:()=>zs,saveFlowCredentials:()=>qs,saveTokenCache:()=>tt});function vt(){return Xe||(Xe=Kn()),Xe}async function Xn(){let e=await(await vt()).getSecret(Rt,ze);if(!e)return null;try{return JSON.parse(e)}catch{return null}}async function qs(t){if(!t.clientId||!t.clientSecret||!t.tenant)throw new Error("clientId, clientSecret and tenant are required");await(await vt()).setSecret(Rt,ze,JSON.stringify(t));}async function Xs(){let t=await vt();await t.deleteSecret(Rt,ze),await t.deleteSecret(Rt,Ze);}async function tt(t){await(await vt()).setSecret(Rt,Ze,JSON.stringify({accessToken:t.accessToken,expiresAt:t.expiresAt,lastAuthCheckAt:t.lastAuthCheckAt}));}async function Yt(){let e=await(await vt()).getSecret(Rt,Ze);if(!e)return null;try{let n=JSON.parse(e);return {accessToken:n.accessToken,expiresAt:n.expiresAt,lastAuthCheckAt:n.lastAuthCheckAt}}catch{return null}}async function zs(){let t=await Yt();return t?new Date(t.expiresAt)>new Date:false}async function ue(){let t=await Yt();if(!t||!t.accessToken)return null;try{let e=t.accessToken.split(".");if(e.length<2)return null;let n=JSON.parse(Buffer.from(e[1].replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf8"));return n.email??n.preferred_username??n.upn??n.sub??null}catch{return null}}async function Zs(){let t=await vt();if(typeof t.getStoragePath=="function")return t.getStoragePath();let e=process.platform;return e==="darwin"?"macOS Keychain":e==="win32"?"Windows Credential Manager":"Linux Secret Service (libsecret)"}async function Qs(){let t=await Xn();return !!(t&&t.clientId&&t.clientSecret&&t.tenant)}var Rt,ze,Ze,Xe,Gt=g(()=>{"use strict";qn();L();Rt=xt.SERVICE,ze=xt.ACCOUNT_CREDS,Ze=xt.ACCOUNT_TOKEN,Xe=null;});function eo(t){return to.some(e=>e.test(t))}function no(t){if(!t)return null;try{let e=t.split(".");if(e.length<2)return null;let n=JSON.parse(Buffer.from(e[1].replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf8"));return n.email||n.preferred_username||n.upn||n.sub||null}catch{return null}}function et(t){if(!t)return null;try{let e=t.split(".");if(e.length<2)return null;let n=JSON.parse(Buffer.from(e[1].replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf8")),{clientId:r,clientSecret:o,tenant:i}=n;return !r||!o||!i?null:{clientId:r,clientSecret:o,tenant:i}}catch{return null}}function Zn(t){let e=Buffer.from(JSON.stringify({alg:"none",typ:"JWT"})).toString("base64url"),n=Buffer.from(JSON.stringify({clientId:t.clientId,clientSecret:t.clientSecret,tenant:t.tenant})).toString("base64url");return `${e}.${n}.`}function gt(t){let e;try{e=new URL(t);}catch{throw new Error(`Invalid URL: ${t}`)}let n=process.env[m.FLOW_OBS_ALLOW_HTTP]==="true";if(!n&&e.protocol!=="https:")throw new Error(`URL must use HTTPS: ${t}`);if(e.username||e.password)throw new Error(`URL must not contain embedded credentials: ${t}`);if(!n&&eo(e.hostname))throw new Error(`SSRF: private/loopback host not allowed: ${e.hostname}`);return t}async function Qn(){let t=et(process.env[m.ANTHROPIC_AUTH_TOKEN]);return t?{user:await ue().catch(()=>null)??t.clientId,tenant:t.tenant}:{user:"",tenant:""}}function ro(){return new Date().toISOString().slice(0,10)}async function so(t){let e=ro(),n=await Yt();if(n?.lastAuthCheckAt!==e){l("getOrRefreshToken",`daily auth check (last: ${n?.lastAuthCheckAt??"never"})`);try{let i=await x(t);try{await tt({...i,lastAuthCheckAt:e});}catch{}return l("getOrRefreshToken",`daily check passed, expires=${i.expiresAt}`),i.accessToken}catch(i){if(i instanceof pt)throw i;l("getOrRefreshToken",`daily check network error \u2014 using cache: ${i.message}`);}}let r=n!=null&&new Date(n.expiresAt)>new Date;if(l("getOrRefreshToken",`cacheValid=${r}`),r)return l("getOrRefreshToken",`using cached token, expires=${n.expiresAt}`),n.accessToken;l("getOrRefreshToken",`token expired \u2014 refreshing via auth-engine (tenant=${t.tenant} clientId=${t.clientId})`);let o=await x(t);try{await tt({...o,lastAuthCheckAt:e});}catch(i){l("getOrRefreshToken",`token cache save failed (non-fatal): ${i.message}`);}return l("getOrRefreshToken",`token refreshed, expires=${o.expiresAt}`),o.accessToken}function oo(t,e){let n=e&&e.accessToken?e.accessToken:"";return {endpoint:t.replace(/\/$/,"")+"/flow-langfuse-gateway/v1/traces",authHeader:`Bearer ${n}`}}function io(t,e,n){let r=Buffer.from(`${e}:${n}`).toString("base64");return {endpoint:t.replace(/\/$/,"")+"/api/public/otel/v1/traces",authHeader:`Basic ${r}`}}async function G(){let t=[],e=process.env[m.ANTHROPIC_MODEL]??"",n=et(process.env[m.ANTHROPIC_AUTH_TOKEN]);l("resolveCredentials",n?"credentials resolved from ANTHROPIC_AUTH_TOKEN":"ANTHROPIC_AUTH_TOKEN absent or invalid"),n&&l("resolveCredentials",`clientId=${n.clientId}`,`tenant=${n.tenant}`);let r=n?n.tenant:"",o=process.env[m.FLOW_TELEMETRY]==="true",i=process.env[m.LANGFUSE_BASE_URL],s=process.env[m.LANGFUSE_PUBLIC_KEY],a=process.env[m.LANGFUSE_SECRET_KEY];if(o&&i&&s&&a){let S="",w=r;n&&(S=await ue().catch(()=>null)??n.clientId);let u={user:S??"",tenant:w??"",team:"",project:"",model:e};t.push({mode:"direct",...io(gt(i),s,a),...u}),l("resolveCredentials","direct mode active",`user=${u.user}`,`tenant=${u.tenant}`);}if(!n){if(t.length===0){let S=[];return S.authError=false,S}return t}let c;try{c=await so(n);}catch(S){if(l("resolveCredentials",`token refresh failed: ${S.message}`,`(tenant=${n.tenant} clientId=${n.clientId})`),t.length>0)return t.authError=true,t;let w=[];return w.authError=true,w}let h={user:no(c)??n.clientId,tenant:r,team:"",project:"",model:e},A=process.env[m.FLOW_TELEMETRY_GATEWAY]??Z();return t.push({mode:"gateway",...oo(gt(A),{accessToken:c}),...h}),t}async function de(){return (await G()).length>0}var to,W=g(()=>{"use strict";Gt();ft();L();j();to=[/^localhost\.?$/i,/^127\./,/^10\./,/^172\.(1[6-9]|2\d|3[01])\./,/^192\.168\./,/^169\.254\./,/^0\.0\.0\.0$/,/^::1$/,/^\[::1\]$/,/^\[::ffff:/i,/^\[f[cd]/i,/^\[fe80:/i,/^metadata\.google\.internal\.?$/i,/^metadata\.azure\.internal\.?$/i,/(?:^|\.)localtest\.me\.?$/i,/(?:^|\.)lvh\.me\.?$/i,/(?:^|\.)vcap\.me\.?$/i];});function tr(){if(process.env.WSL_DISTRO_NAME&&process.platform==="linux")return child_process.spawnSync("cmd.exe",["/c","where","claude"],{encoding:"utf8",timeout:5e3}).status===0;let t=process.platform==="win32"?"where":"which";return child_process.spawnSync(t,["claude"],{encoding:"utf8",timeout:5e3}).status===0}function er(){try{if(process.env.WSL_DISTRO_NAME&&process.platform==="linux"){let e=child_process.spawnSync("cmd.exe",["/c","claude","--version"],{encoding:"utf8",timeout:5e3});return e.status===0?e.stdout.trim():null}let t=child_process.spawnSync("claude",["--version"],{encoding:"utf8",timeout:5e3});return t.status===0?t.stdout.trim():null}catch{return null}}var nr=g(()=>{"use strict";});var sr={};C(sr,{clearLoggedOutMarker:()=>tn,isLoggedOut:()=>lo,markLoggedOut:()=>co});function Qe(){return Lt__namespace.default.join(mt__namespace.default.homedir(),".claude","flow-obs",".logged-out")}function co(){try{let t=Qe();O__namespace.default.mkdirSync(Lt__namespace.default.dirname(t),{recursive:!0}),O__namespace.default.writeFileSync(t,"",{mode:384});}catch{}}function tn(){try{O__namespace.default.unlinkSync(Qe());}catch{}}function lo(){try{return O__namespace.default.existsSync(Qe())}catch{return false}}var en=g(()=>{"use strict";});function nn(){let t=process.env.FLOW_BASE_URL;return t&&t.trim()?t.trim():We("FLOW_BASE_URL")}function uo(){return We(m.ANTHROPIC_AUTH_TOKEN)??void 0}async function me(){let t=nn();if(!t)return {ok:false,baseUrl:"",user:"",tenant:"",notConfigured:true,error:"NOT_CONFIGURED"};try{let o=new URL(t);if(o.protocol!=="https:"&&o.protocol!=="http:")throw new Error}catch{return {ok:false,baseUrl:t,user:"",tenant:"",notConfigured:true,error:"NOT_CONFIGURED"}}let e=uo(),n=et(e);if(!n)return {ok:false,baseUrl:t,user:"",tenant:"",error:"No credentials found"};let r=process.env.FLOW_BASE_URL;process.env.FLOW_BASE_URL=t;try{let o=await x({clientId:n.clientId,clientSecret:n.clientSecret,tenant:n.tenant});await tt({accessToken:o.accessToken,expiresAt:o.expiresAt});let i=n.clientId;try{let s=o.accessToken.split(".");if(s.length>=2){let a=JSON.parse(Buffer.from(s[1].replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf8"));i=a.email??a.preferred_username??a.upn??a.sub??i;}}catch{}return {ok:!0,baseUrl:t,user:i,tenant:n.tenant}}catch(o){return {ok:false,baseUrl:t,user:n.clientId,tenant:n.tenant,error:o.message}}finally{r===void 0?delete process.env.FLOW_BASE_URL:process.env.FLOW_BASE_URL=r;}}var rn=g(()=>{"use strict";Gt();W();jt();L();ft();});var he={};C(he,{promptRaw:()=>Jt,runLogin:()=>mo});function V(t){return typeof t=="string"?t.replace(po,""):t}function Jt(t,e={}){return new Promise((n,r)=>{if(typeof process.stdin.setRawMode!="function"){r(new Error("NOT_A_TTY"));return}let{masked:o=false,defaultValue:i=""}=e;process.stdout.write(t+i);let s=i;function a(){try{process.stdin.setRawMode(!1);}catch{}}process.once("uncaughtException",a),process.once("unhandledRejection",a);let c=h=>{if(h===""){d(),r(new Error("SIGINT"));return}if(h==="\r"||h===`
|
|
34
|
-
`){
|
|
35
|
-
`),
|
|
36
|
-
`)),1;if(process.stdout.write(
|
|
37
|
-
`)),t){let
|
|
38
|
-
${
|
|
39
|
-
`+
|
|
40
|
-
`)+
|
|
41
|
-
|
|
42
|
-
`)),{code:0,result:
|
|
43
|
-
${
|
|
44
|
-
`+
|
|
45
|
-
`)+
|
|
31
|
+
`),1}var de=E(()=>{"use strict";ut();});function Ur(){if(process.platform==="linux"&&process.getuid?.()===0&&process.env.SUDO_USER){let e=child_process.spawnSync("getent",["passwd",process.env.SUDO_USER],{encoding:"utf8",timeout:5e3}).stdout?.split(":")[5]?.trim();if(e)return {home:e,username:process.env.SUDO_USER}}return {home:gt__namespace.homedir(),username:process.env.SUDO_USER||process.env.USER||gt__namespace.userInfo().username}}function x(){if(process.env.WSL_DISTRO_NAME&&process.platform==="linux"){let t=process.env.USERPROFILE;if(!t){let r=child_process.spawnSync("cmd.exe",["/c","echo","%USERPROFILE%"],{encoding:"utf8",timeout:5e3}).stdout?.trim();r&&/^[A-Za-z]:\\/.test(r)&&(t=r);}if(t){let e=t.replace(/^([A-Za-z]):/,(r,n)=>`/mnt/${n.toLowerCase()}`).replace(/\\/g,"/");return Rt__namespace.join(e,".claude","settings.json")}return Rt__namespace.join(gt__namespace.homedir(),".claude","settings.json")}if(process.platform==="win32"){let t=process.env.USERPROFILE||gt__namespace.homedir();return Rt__namespace.join(t,".claude","settings.json")}if(process.platform==="linux"&&process.getuid?.()===0&&process.env.SUDO_USER){let e=child_process.spawnSync("getent",["passwd",process.env.SUDO_USER],{encoding:"utf8",timeout:5e3}).stdout?.split(":")[5]?.trim();if(e)return Rt__namespace.join(e,".claude","settings.json")}return Rt__namespace.join(gt__namespace.homedir(),".claude","settings.json")}var pe=E(()=>{"use strict";de();});function fe(){if(process.platform==="win32"){let r=process.env.APPDATA||Rt__namespace.join(gt__namespace.homedir(),"AppData","Roaming");return Rt__namespace.join(r,Pr,Nr)}let t=Ur(),e=process.env.XDG_CONFIG_HOME||Rt__namespace.join(t.home,".config");return Rt__namespace.join(e,Pr,Nr)}function We(){try{let t=A__namespace.readFileSync(x(),"utf8"),r=JSON.parse(t).env?.FLOW_BASE_URL;return typeof r=="string"&&r.trim()?r.trim():null}catch{return null}}var Pr,Nr,je=E(()=>{"use strict";pe();Pr="flow-ai-obs",Nr="config.json";});function Fr(t){try{let e=A__namespace.statSync(t);Date.now()-e.mtimeMs>Fs&&A__namespace.unlinkSync(t);}catch{}try{A__namespace.writeFileSync(t,String(process.pid),{flag:"wx"});}catch(e){throw e.code==="EEXIST"?new Error("Another install is already in progress. If this is stale, remove: "+t):e}}function xr(t){try{A__namespace.unlinkSync(t);}catch{}}function xs(t,e){let n=(Array.isArray(t)?t:[]).map(s=>{if(!Array.isArray(s?.hooks))return null;let i=s.hooks.filter(o=>!o.command?.startsWith?.("flow-ai-obs "));return i.length>0?{...s,hooks:i}:null}).filter(s=>s!=null);return [e,...n]}function Dr(t,e){let r=x(),n=r+".lock",s=[];A__namespace.mkdirSync(Rt__namespace.dirname(r),{recursive:true}),Fr(n);try{if(A__namespace.existsSync(r)){A__namespace.copyFileSync(r,r+".bkp");try{A__namespace.chmodSync(r+".bkp",384);}catch{}}let i=fe();if(A__namespace.existsSync(i)){let p=i+".bkp";A__namespace.copyFileSync(i,p);try{A__namespace.chmodSync(p,384);}catch{}}let o={};try{o=JSON.parse(A__namespace.readFileSync(r,"utf8"));}catch{}let c=o.env&&typeof o.env=="object"?o.env:{};delete c.OTEL_EXPORTER_OTLP_HEADERS;let{getFlowUrls:l}=(v(),P(Rr)),a=l().OTEL_ENDPOINT,d={...tt,OTEL_EXPORTER_OTLP_ENDPOINT:t??a};o.env={...c,...d,...e??{}},o.otelHeadersHelper="flow-ai-obs otel-headers",(!o.hooks||typeof o.hooks!="object"||Array.isArray(o.hooks))&&(o.hooks={});let m=(p,w)=>({matcher:"",hooks:[{type:"command",command:`flow-ai-obs ${p}`,timeout:w}]}),T=["UserPromptSubmit","PreToolUse","PostToolUse","Stop"],S=o.hooks;for(let p of T){let w=xs(S[p],m(p,pt[p]));w.length>1&&s.push(p),S[p]=w;}A__namespace.writeFileSync(r,JSON.stringify(o,null,2)+`
|
|
32
|
+
`,{encoding:"utf8",mode:384});try{A__namespace.chmodSync(r,384);}catch{}}finally{xr(n);}return {settingsPath:r,preserved:s}}function Gt(t){try{let e=A__namespace.readFileSync(x(),"utf8"),n=JSON.parse(e).env?.[t];return typeof n=="string"?n:null}catch{return null}}function J(t){let e=x(),r=e+".lock";A__namespace.mkdirSync(Rt__namespace.dirname(e),{recursive:true}),Fr(r);try{let n={};try{n=JSON.parse(A__namespace.readFileSync(e,"utf8"));}catch{}(!n.env||typeof n.env!="object")&&(n.env={}),Object.assign(n.env,t),A__namespace.writeFileSync(e,JSON.stringify(n,null,2)+`
|
|
33
|
+
`,{encoding:"utf8",mode:384});try{A__namespace.chmodSync(e,384);}catch{}}finally{xr(r);}}var Fs,vt=E(()=>{"use strict";v();mt();pe();je();Fs=Vt.LOCK_STALE_MS;});function Jt(){let t=gt__namespace.default.homedir();if(process.platform==="darwin")return Rt__namespace.default.join(t,"Library","Preferences",Wt,jt);if(process.platform==="win32"){let r=process.env.APPDATA??Rt__namespace.default.join(t,"AppData","Roaming");return Rt__namespace.default.join(r,Wt,jt)}let e=process.env.XDG_CONFIG_HOME??Rt__namespace.default.join(t,".config");return Rt__namespace.default.join(e,Wt,jt)}function Ge(){try{let t=A__namespace.default.readFileSync(Jt(),"utf8");return JSON.parse(t)}catch{return {}}}function Mr(t){let e=Jt();A__namespace.default.mkdirSync(Rt__namespace.default.dirname(e),{recursive:true}),A__namespace.default.writeFileSync(e,JSON.stringify(t,null,2),{encoding:"utf8",mode:384});}var Ye,qt,Br=E(()=>{"use strict";v();Ye={credentials:"credentials","token-cache":"tokenCache"};qt=class{static isAvailable(){return !0}static hasExistingData(){try{if(!A__namespace.default.existsSync(Jt()))return !1;let e=JSON.parse(A__namespace.default.readFileSync(Jt(),"utf8"));return !!(e&&e.credentials)}catch{return !1}}async getSecret(e,r){let n=Ge(),s=Ye[r]??r,i=n[s];return i?typeof i=="string"?i:JSON.stringify(i):null}async setSecret(e,r,n){let s=Ge(),i=Ye[r]??r;if(r==="token-cache")try{s[i]=JSON.parse(n);}catch{s[i]=n;}else s[i]=n;Mr(s);}async deleteSecret(e,r){let n=Ge(),s=Ye[r]??r;return s in n?(delete n[s],Mr(n),!0):!1}getStoragePath(){return `config.json (unencrypted) \u2014 ${Jt()}`}};});var Hr={};N(Hr,{MacOsKeyVaultProvider:()=>Ke});var Je,Ke,Wr=E(()=>{"use strict";Je=util.promisify(child_process.execFile),Ke=class{static async isAvailable(){try{return A.accessSync("/usr/bin/security",A.constants.X_OK),!0}catch{return !1}}async getSecret(e,r){try{let{stdout:n}=await Je("security",["find-generic-password","-w","-a",r,"-s",e]);return n.trim()||null}catch{return null}}async setSecret(e,r,n){await Je("security",["add-generic-password","-U","-a",r,"-s",e,"-w",n]);}async deleteSecret(e,r){try{return await Je("security",["delete-generic-password","-a",r,"-s",e]),!0}catch{return !1}}getStoragePath(){return "macOS Keychain"}};});var Vr={};N(Vr,{LinuxKeyVaultProvider:()=>qe});var jr,qe,Yr=E(()=>{"use strict";jr=util.promisify(child_process.execFile),qe=class{static async isAvailable(){let e=["/usr/bin/secret-tool","/bin/secret-tool","/usr/local/bin/secret-tool"];for(let r of e)try{return A.accessSync(r,A.constants.X_OK),!0}catch{}return !1}async getSecret(e,r){try{let{stdout:n}=await jr("secret-tool",["lookup","service",e,"account",r]);return n.trim()||null}catch{return null}}async setSecret(e,r,n){await new Promise((s,i)=>{let o=child_process.spawn("secret-tool",["store","--label",e,"service",e,"account",r]);o.on("error",i),o.on("close",c=>{c===0?s():i(new Error(`secret-tool exited with code ${c}`));}),o.stdin.write(n),o.stdin.end();});}async deleteSecret(e,r){try{return await jr("secret-tool",["clear","service",e,"account",r]),!0}catch{return !1}}getStoragePath(){return "Linux Secret Service (libsecret)"}};});var Gr={};N(Gr,{WindowsKeyVaultProvider:()=>Xe});var Xe,Jr=E(()=>{"use strict";Xe=class{static async isAvailable(){try{return await Dt("keytar").getPassword("__flow_probe__","__flow_probe__"),!0}catch{return !1}}async getSecret(e,r){return Dt("keytar").getPassword(e,r)}async setSecret(e,r,n){await Dt("keytar").setPassword(e,r,n);}async deleteSecret(e,r){return Dt("keytar").deletePassword(e,r)}getStoragePath(){return "Windows Credential Manager"}};});async function Kr(){return process.env[f.FLOW_OBS_USE_JSON_VAULT]==="1"?new qt:await Ks()??new qt}async function Ks(){switch(process.platform){case "darwin":{let{MacOsKeyVaultProvider:t}=await Promise.resolve().then(()=>(Wr(),Hr));return await t.isAvailable()?new t:null}case "linux":{let{LinuxKeyVaultProvider:t}=await Promise.resolve().then(()=>(Yr(),Vr));return await t.isAvailable()?new t:null}case "win32":{let{WindowsKeyVaultProvider:t}=await Promise.resolve().then(()=>(Jr(),Gr));return await t.isAvailable()?new t:null}default:return null}}var qr=E(()=>{"use strict";v();Br();});var zr={};N(zr,{clearFlowCredentials:()=>Xs,getConfigPath:()=>Zs,getEmailFromToken:()=>Ut,getFlowCredentials:()=>Xr,getTokenCache:()=>Xt,hasCredentials:()=>Qs,isTokenValid:()=>zs,saveFlowCredentials:()=>qs,saveTokenCache:()=>et});function It(){return ze||(ze=Kr()),ze}async function Xr(){let e=await(await It()).getSecret(bt,Ze);if(!e)return null;try{return JSON.parse(e)}catch{return null}}async function qs(t){if(!t.clientId||!t.clientSecret||!t.tenant)throw new Error("clientId, clientSecret and tenant are required");await(await It()).setSecret(bt,Ze,JSON.stringify(t));}async function Xs(){let t=await It();await t.deleteSecret(bt,Ze),await t.deleteSecret(bt,Qe);}async function et(t){await(await It()).setSecret(bt,Qe,JSON.stringify({accessToken:t.accessToken,expiresAt:t.expiresAt,lastAuthCheckAt:t.lastAuthCheckAt}));}async function Xt(){let e=await(await It()).getSecret(bt,Qe);if(!e)return null;try{let r=JSON.parse(e);return {accessToken:r.accessToken,expiresAt:r.expiresAt,lastAuthCheckAt:r.lastAuthCheckAt}}catch{return null}}async function zs(){let t=await Xt();return t?new Date(t.expiresAt)>new Date:false}async function Ut(){let t=await Xt();if(!t||!t.accessToken)return null;try{let e=t.accessToken.split(".");if(e.length<2)return null;let r=JSON.parse(Buffer.from(e[1].replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf8"));return r.email??r.preferred_username??r.upn??r.sub??null}catch{return null}}async function Zs(){let t=await It();if(typeof t.getStoragePath=="function")return t.getStoragePath();let e=process.platform;return e==="darwin"?"macOS Keychain":e==="win32"?"Windows Credential Manager":"Linux Secret Service (libsecret)"}async function Qs(){let t=await Xr();return !!(t&&t.clientId&&t.clientSecret&&t.tenant)}var bt,Ze,Qe,ze,zt=E(()=>{"use strict";qr();v();bt=Ht.SERVICE,Ze=Ht.ACCOUNT_CREDS,Qe=Ht.ACCOUNT_TOKEN,ze=null;});function ro(t){return eo.some(e=>e.test(t))}function no(t){if(!t)return null;try{let e=t.split(".");if(e.length<2)return null;let r=JSON.parse(Buffer.from(e[1].replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf8"));return r.email||r.preferred_username||r.upn||r.sub||null}catch{return null}}function rt(t){if(!t)return null;try{let e=t.split(".");if(e.length<2)return null;let r=JSON.parse(Buffer.from(e[1].replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf8")),{clientId:n,clientSecret:s,tenant:i}=r;return !n||!s||!i?null:{clientId:n,clientSecret:s,tenant:i}}catch{return null}}function tn(t){let e=Buffer.from(JSON.stringify({alg:"none",typ:"JWT"})).toString("base64url"),r=Buffer.from(JSON.stringify({clientId:t.clientId,clientSecret:t.clientSecret,tenant:t.tenant})).toString("base64url");return `${e}.${r}.`}function ht(t){let e;try{e=new URL(t);}catch{throw new Error(`Invalid URL: ${t}`)}let r=process.env[f.FLOW_OBS_ALLOW_HTTP]==="true";if(!r&&e.protocol!=="https:")throw new Error(`URL must use HTTPS: ${t}`);if(e.username||e.password)throw new Error(`URL must not contain embedded credentials: ${t}`);if(!r&&ro(e.hostname))throw new Error(`SSRF: private/loopback host not allowed: ${e.hostname}`);return t}async function en(){let t=rt(process.env[f.ANTHROPIC_AUTH_TOKEN]);return t?{user:await Ut().catch(()=>null)??t.clientId,tenant:t.tenant}:{user:"",tenant:""}}function so(){return new Date().toISOString().slice(0,10)}async function oo(t){let e=so(),r=await Xt();if(r?.lastAuthCheckAt!==e){u("getOrRefreshToken",`daily auth check (last: ${r?.lastAuthCheckAt??"never"})`);try{let i=await F(t);try{await et({...i,lastAuthCheckAt:e});}catch{}return u("getOrRefreshToken",`daily check passed, expires=${i.expiresAt}`),i.accessToken}catch(i){if(i instanceof ft)throw i;u("getOrRefreshToken",`daily check network error \u2014 using cache: ${i.message}`);}}let n=r!=null&&new Date(r.expiresAt)>new Date;if(u("getOrRefreshToken",`cacheValid=${n}`),n)return u("getOrRefreshToken",`using cached token, expires=${r.expiresAt}`),r.accessToken;u("getOrRefreshToken",`token expired \u2014 refreshing via auth-engine (tenant=${t.tenant} clientId=${t.clientId})`);let s=await F(t);try{await et({...s,lastAuthCheckAt:e});}catch(i){u("getOrRefreshToken",`token cache save failed (non-fatal): ${i.message}`);}return u("getOrRefreshToken",`token refreshed, expires=${s.expiresAt}`),s.accessToken}function io(t,e){let r=e&&e.accessToken?e.accessToken:"";return {endpoint:t.replace(/\/$/,"")+"/flow-langfuse-gateway/v1/traces",authHeader:`Bearer ${r}`}}function ao(t,e,r){let n=Buffer.from(`${e}:${r}`).toString("base64");return {endpoint:t.replace(/\/$/,"")+"/api/public/otel/v1/traces",authHeader:`Basic ${n}`}}async function K(){let t=[],e=process.env[f.ANTHROPIC_MODEL]??"",r=rt(process.env[f.ANTHROPIC_AUTH_TOKEN]);u("resolveCredentials",r?"credentials resolved from ANTHROPIC_AUTH_TOKEN":"ANTHROPIC_AUTH_TOKEN absent or invalid"),r&&u("resolveCredentials",`clientId=${r.clientId}`,`tenant=${r.tenant}`);let n=r?r.tenant:"",s=process.env[f.FLOW_TELEMETRY]==="true",i=process.env[f.LANGFUSE_BASE_URL],o=process.env[f.LANGFUSE_PUBLIC_KEY],c=process.env[f.LANGFUSE_SECRET_KEY];if(s&&i&&o&&c){let T="",S=n;r&&(T=await Ut().catch(()=>null)??r.clientId);let p={user:T??"",tenant:S??"",team:"",project:"",model:e};t.push({mode:"direct",...ao(ht(i),o,c),...p}),u("resolveCredentials","direct mode active",`user=${p.user}`,`tenant=${p.tenant}`);}if(!r){if(t.length===0){let T=[];return T.authError=false,T}return t}let l;try{l=await oo(r);}catch(T){if(u("resolveCredentials",`token refresh failed: ${T.message}`,`(tenant=${r.tenant} clientId=${r.clientId})`),t.length>0)return t.authError=true,t;let S=[];return S.authError=true,S}let d={user:no(l)??r.clientId,tenant:n,team:"",project:"",model:e},m=process.env[f.FLOW_TELEMETRY_GATEWAY]??Q();return t.push({mode:"gateway",...io(ht(m),{accessToken:l}),...d}),t}async function me(){return (await K()).length>0}function ge(){let t=process.env[f.FLOW_USER_EMAIL];if(t){let e=t.replace(/[\r\n]/g,"").trim();return e?(u("resolveUserEmail","using FLOW_USER_EMAIL override: [REDACTED]"),e):null}try{let e=gt__namespace.default.userInfo().username||process.env.USERNAME||process.env.USER||"",r=e.lastIndexOf("\\");if(r!==-1&&(e=e.slice(r+1)),e=e.trim().replace(/[^a-zA-Z0-9._%+\-]/g,""),!e)return u("resolveUserEmail","username empty after sanitisation \u2014 omitting x-flow-user"),Zr||(Zr=!0,console.warn("[flow-ai-obs] Could not derive x-flow-user: username is empty. Set FLOW_USER_EMAIL to fix this.")),null;let n=`${e}@ciandt.com`;return u("resolveUserEmail","derived email: [REDACTED]"),n}catch(e){return u("resolveUserEmail",`os.userInfo() threw: ${e.message} \u2014 omitting x-flow-user`),Qr||(Qr=true,console.warn("[flow-ai-obs] Could not derive x-flow-user from OS username. Set FLOW_USER_EMAIL to fix this.")),null}}function co(t){let e=process.env.OTEL_EXPORTER_OTLP_HEADERS;if(!e)return null;for(let r of e.split(",")){let n=r.indexOf("=");if(!(n<=0)&&r.slice(0,n).trim().toLowerCase()===t.toLowerCase())return r.slice(n+1).replace(/[\r\n]/g,"").trim()||null}return null}function rn(){return co("x-flow-api-key")}var eo,Zr,Qr,W=E(()=>{"use strict";zt();mt();v();H();eo=[/^localhost\.?$/i,/^127\./,/^10\./,/^172\.(1[6-9]|2\d|3[01])\./,/^192\.168\./,/^169\.254\./,/^0\.0\.0\.0$/,/^::1$/,/^\[::1\]$/,/^\[::ffff:/i,/^\[f[cd]/i,/^\[fe80:/i,/^metadata\.google\.internal\.?$/i,/^metadata\.azure\.internal\.?$/i,/(?:^|\.)localtest\.me\.?$/i,/(?:^|\.)lvh\.me\.?$/i,/(?:^|\.)vcap\.me\.?$/i];Zr=!1,Qr=!1;});var sn={};N(sn,{clearLoggedOutMarker:()=>er,isLoggedOut:()=>po,markLoggedOut:()=>uo});function tr(){return Rt__namespace.default.join(gt__namespace.default.homedir(),".claude","flow-obs",".logged-out")}function uo(){try{let t=tr();A__namespace.default.mkdirSync(Rt__namespace.default.dirname(t),{recursive:!0}),A__namespace.default.writeFileSync(t,"",{mode:384});}catch{}}function er(){try{A__namespace.default.unlinkSync(tr());}catch{}}function po(){try{return A__namespace.default.existsSync(tr())}catch{return false}}var rr=E(()=>{"use strict";});function nr(){let t=process.env.FLOW_BASE_URL;return t&&t.trim()?t.trim():Gt("FLOW_BASE_URL")}function fo(){return Gt(f.ANTHROPIC_AUTH_TOKEN)??void 0}async function Ee(){let t=nr();if(!t)return {ok:false,baseUrl:"",user:"",tenant:"",notConfigured:true,error:"NOT_CONFIGURED"};try{let s=new URL(t);if(s.protocol!=="https:"&&s.protocol!=="http:")throw new Error}catch{return {ok:false,baseUrl:t,user:"",tenant:"",notConfigured:true,error:"NOT_CONFIGURED"}}let e=fo(),r=rt(e);if(!r)return {ok:false,baseUrl:t,user:"",tenant:"",error:"No credentials found"};let n=process.env.FLOW_BASE_URL;process.env.FLOW_BASE_URL=t;try{let s=await F({clientId:r.clientId,clientSecret:r.clientSecret,tenant:r.tenant});await et({accessToken:s.accessToken,expiresAt:s.expiresAt});let i=r.clientId;try{let o=s.accessToken.split(".");if(o.length>=2){let c=JSON.parse(Buffer.from(o[1].replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf8"));i=c.email??c.preferred_username??c.upn??c.sub??i;}}catch{}return {ok:!0,baseUrl:t,user:i,tenant:r.tenant}}catch(s){return {ok:false,baseUrl:t,user:r.clientId,tenant:r.tenant,error:s.message}}finally{n===void 0?delete process.env.FLOW_BASE_URL:process.env.FLOW_BASE_URL=n;}}var sr=E(()=>{"use strict";zt();W();vt();v();mt();});var Se={};N(Se,{promptRaw:()=>Zt,runLogin:()=>ho});function j(t){return typeof t=="string"?t.replace(mo,""):t}function Zt(t,e={}){return new Promise((r,n)=>{if(typeof process.stdin.setRawMode!="function"){n(new Error("NOT_A_TTY"));return}let{masked:s=false,defaultValue:i=""}=e;process.stdout.write(t+i);let o=i;function c(){try{process.stdin.setRawMode(!1);}catch{}}process.once("uncaughtException",c),process.once("unhandledRejection",c);let l=d=>{if(d===""){a(),n(new Error("SIGINT"));return}if(d==="\r"||d===`
|
|
34
|
+
`){a(),process.stdout.write(`
|
|
35
|
+
`),r(o);return}if(d==="\x7F"){o.length>0&&(o=o.slice(0,-1),process.stdout.write("\b \b"));return}d.startsWith("\x1B")||(o+=d,process.stdout.write(s?"*".repeat(d.length):d));};function a(){process.stdin.setRawMode(false),process.stdin.removeListener("data",l),process.removeListener("uncaughtException",c),process.removeListener("unhandledRejection",c);}process.stdin.setRawMode(true),process.stdin.resume(),process.stdin.setEncoding("utf8"),process.stdin.on("data",l);})}async function we(t,e=false){let r=nr(),n=process.env.FLOW_BASE_URL;r&&(process.env.FLOW_BASE_URL=r);try{let{accessToken:s,expiresAt:i}=await F(t),o=tn(t);if(e)return {jwt:o,accessToken:s,expiresAt:i};J({[f.ANTHROPIC_AUTH_TOKEN]:o}),er(),await et({accessToken:s,expiresAt:i});}finally{n===void 0?delete process.env.FLOW_BASE_URL:process.env.FLOW_BASE_URL=n;}}async function go(t=false){try{let e=(await Zt(U(" ? ")+"Client ID: ")).trim(),r=(await Zt(U(" ? ")+"Client Secret: ",{masked:!0})).trim(),n=(await Zt(U(" ? ")+"Tenant: ")).trim();if(!e||!r||!n)return process.stderr.write(I(` \u2717 All fields are required
|
|
36
|
+
`)),1;if(process.stdout.write(g(` Authenticating...
|
|
37
|
+
`)),t){let s=await we({clientId:e,clientSecret:r,tenant:n},!0);return process.stdout.write(`
|
|
38
|
+
${k("\u2713")} ${b("Authenticated")}
|
|
39
|
+
`+g(` Tenant: ${j(n)}
|
|
40
|
+
`)+g(` Storage: pending (will be written at end of init)
|
|
41
|
+
|
|
42
|
+
`)),{code:0,result:s}}return await we({clientId:e,clientSecret:r,tenant:n}),process.stdout.write(`
|
|
43
|
+
${k("\u2713")} ${b("Authenticated")}
|
|
44
|
+
`+g(` Tenant: ${j(n)}
|
|
45
|
+
`)+g(` Storage: ANTHROPIC_AUTH_TOKEN (settings.json)
|
|
46
46
|
|
|
47
47
|
`)),0}catch(e){if(e.message==="SIGINT"||e.message==="NOT_A_TTY")throw e;return process.stderr.write(`
|
|
48
|
-
${I("\u2717")} ${
|
|
49
|
-
${
|
|
50
|
-
|
|
51
|
-
`),1}}async function
|
|
52
|
-
|
|
53
|
-
`)),{code:0,result:i}}return await
|
|
54
|
-
|
|
55
|
-
`)),0}catch(i){return process.stderr.write(I(` \u2717 Authentication failed: ${
|
|
56
|
-
`)),1}let
|
|
57
|
-
`),process.stdout.write(
|
|
58
|
-
`)),
|
|
59
|
-
`),process.stdout.write(
|
|
60
|
-
`),1;if(
|
|
61
|
-
`),process.stdout.write(
|
|
62
|
-
`),process.stdout.write(
|
|
63
|
-
`),process.stdout.write(
|
|
48
|
+
${I("\u2717")} ${b("Authentication failed:")}
|
|
49
|
+
${j(e.message)}
|
|
50
|
+
|
|
51
|
+
`),1}}async function ho(t={}){let e=ue();if(e)return e;let{deferPersist:r=false,skipAuthCheck:n=false}=t;if(t.clientId&&t.clientSecret&&t.tenant)try{if(r){let i=await we({clientId:t.clientId,clientSecret:t.clientSecret,tenant:t.tenant},!0);return process.stdout.write(k(` \u2713 Authenticated. Tenant: ${j(t.tenant)}
|
|
52
|
+
|
|
53
|
+
`)),{code:0,result:i}}return await we({clientId:t.clientId,clientSecret:t.clientSecret,tenant:t.tenant}),process.stdout.write(k(` \u2713 Authenticated. Tenant: ${j(t.tenant)}
|
|
54
|
+
|
|
55
|
+
`)),0}catch(i){return process.stderr.write(I(` \u2717 Authentication failed: ${j(i.message)}
|
|
56
|
+
`)),1}let s=await Ee();if(!n){if(process.stdout.write(`
|
|
57
|
+
`),process.stdout.write(b(` Auth
|
|
58
|
+
`)),s.notConfigured)return process.stdout.write(` ${R("\u26A0")} Not configured
|
|
59
|
+
`),process.stdout.write(g(" Run `flow-ai-obs init` to set up the environment first.\n")),process.stdout.write(`
|
|
60
|
+
`),1;if(s.ok){process.stdout.write(` ${k("\u2713")} Authenticated
|
|
61
|
+
`),process.stdout.write(g(" URL: ")+j(s.baseUrl)+`
|
|
62
|
+
`),process.stdout.write(g(" Tenant: ")+j(s.tenant)+`
|
|
63
|
+
`),process.stdout.write(g(" User: ")+j(s.user)+`
|
|
64
64
|
`),process.stdout.write(`
|
|
65
|
-
`);let i;try{i=await
|
|
66
|
-
`),130;if(
|
|
65
|
+
`);let i;try{i=await Zt(U(" ? ")+"Re-authenticate? (y/N): ");}catch(o){if(o.message==="SIGINT")return process.stdout.write(`
|
|
66
|
+
`),130;if(o.message==="NOT_A_TTY")return process.stdout.write(k(` \u2713 Using existing credentials.
|
|
67
67
|
|
|
68
|
-
`)),0;throw
|
|
68
|
+
`)),0;throw o}if(i.trim().toLowerCase()!=="y")return process.stdout.write(k(` \u2713 Using existing credentials.
|
|
69
69
|
|
|
70
|
-
`)),0}else
|
|
71
|
-
`),process.stdout.write(
|
|
70
|
+
`)),0}else s.error==="No credentials found"?(process.stdout.write(` ${R("\u26A0")} Not authenticated
|
|
71
|
+
`),process.stdout.write(g(` URL: ${s.baseUrl}
|
|
72
72
|
`)),process.stdout.write(`
|
|
73
73
|
`)):(process.stdout.write(` ${R("\u26A0")} Session not valid for current endpoint
|
|
74
|
-
`),process.stdout.write(
|
|
75
|
-
`),process.stdout.write(
|
|
76
|
-
`),process.stdout.write(
|
|
74
|
+
`),process.stdout.write(g(" URL: ")+j(s.baseUrl)+`
|
|
75
|
+
`),process.stdout.write(g(" Tenant: ")+j(s.tenant)+`
|
|
76
|
+
`),process.stdout.write(g(" User: ")+g("(not authenticated)")+`
|
|
77
77
|
`),process.stdout.write(`
|
|
78
|
-
`));}try{return await
|
|
78
|
+
`));}try{return await go(r)}catch(i){if(i.message==="SIGINT")return process.stdout.write(`
|
|
79
79
|
`),130;if(i.message==="NOT_A_TTY")return process.stderr.write(I(` \u2717 No TTY available for interactive login.
|
|
80
80
|
`)+` Pass --client-id, --client-secret and --tenant for non-interactive use.
|
|
81
81
|
|
|
82
|
-
`),1;throw i}}var
|
|
83
|
-
[${t}/${e}] ${
|
|
84
|
-
`)));}function
|
|
85
|
-
`);}function
|
|
86
|
-
`);}function
|
|
87
|
-
`);}function
|
|
88
|
-
|
|
89
|
-
`,{encoding:"utf8",mode:384});}catch{}return t}function cr(t){let e=t.trim().replace(/\\/g,"/");/^https?:\/\//i.test(e)||(e=`https://${e}`);try{let n=new URL(e);return `${n.protocol}//${n.host}`}catch{return e}}function on(t,e=false){if(e){let i=/^https?:\/\//i.test(t.trim())?t.trim().replace(/\\/g,"/"):`https://${t.trim().replace(/\\/g,"/")}`,s;try{s=new URL(i);}catch{throw new Error(`Invalid URL: ${t}`)}if(s.protocol!=="https:")throw new Error(`Custom URL must use HTTPS: ${t}`);if(s.pathname!=="/"&&s.pathname!=="")throw new Error(`Custom URL must be a base URL with no path beyond the root.
|
|
82
|
+
`),1;throw i}}var mo,Te=E(()=>{"use strict";zt();rr();mt();W();vt();v();ut();de();sr();mo=/[\x00-\x08\x0B-\x1F\x7F]|\x1b\[[0-9;]*[a-zA-Z]/g;});var ln={};N(ln,{normalizeCustomUrl:()=>cn,runInit:()=>To,validateCustomUrl:()=>cr});function _e(t,e,r){process.stdout.write(b(U(`
|
|
83
|
+
[${t}/${e}] ${r}
|
|
84
|
+
`)));}function or(t){process.stdout.write(` ${k("\u2713")} ${t}
|
|
85
|
+
`);}function Eo(t){process.stdout.write(` ${R("\u26A0")} ${t}
|
|
86
|
+
`);}function on(t){process.stdout.write(` ${g(t)}
|
|
87
|
+
`);}function ar(){try{let t=A__namespace.readFileSync(x(),"utf8");return JSON.parse(t).env||{}}catch{return {}}}function an(){try{let t=A__namespace.readFileSync(x(),"utf8"),e=JSON.parse(t);return !!(e.env&&e.env[f.ANTHROPIC_AUTH_TOKEN])}catch{return false}}function wo(){let t=We();if(!t)return null;J({FLOW_BASE_URL:t});try{let e=fe(),r={};try{r=JSON.parse(A__namespace.readFileSync(e,"utf8"));}catch{return t}delete r.baseUrl,Object.keys(r).length===0?A__namespace.unlinkSync(e):A__namespace.writeFileSync(e,JSON.stringify(r,null,2)+`
|
|
88
|
+
`,{encoding:"utf8",mode:384});}catch{}return t}function cn(t){let e=t.trim().replace(/\\/g,"/");/^https?:\/\//i.test(e)||(e=`https://${e}`);try{let r=new URL(e);return `${r.protocol}//${r.host}`}catch{return e}}function cr(t,e=false){if(e){let i=/^https?:\/\//i.test(t.trim())?t.trim().replace(/\\/g,"/"):`https://${t.trim().replace(/\\/g,"/")}`,o;try{o=new URL(i);}catch{throw new Error(`Invalid URL: ${t}`)}if(o.protocol!=="https:")throw new Error(`Custom URL must use HTTPS: ${t}`);if(o.pathname!=="/"&&o.pathname!=="")throw new Error(`Custom URL must be a base URL with no path beyond the root.
|
|
90
89
|
Received: ${t}
|
|
91
|
-
Expected: https://tenant.example.com`);if(
|
|
90
|
+
Expected: https://tenant.example.com`);if(o.search)throw new Error(`Custom URL must not contain query parameters.
|
|
92
91
|
Received: ${t}
|
|
93
|
-
Expected: https://tenant.example.com`);if(
|
|
92
|
+
Expected: https://tenant.example.com`);if(o.hash)throw new Error(`Custom URL must not contain a fragment.
|
|
94
93
|
Received: ${t}
|
|
95
|
-
Expected: https://tenant.example.com`);if(
|
|
94
|
+
Expected: https://tenant.example.com`);if(o.username||o.password)throw new Error(`Custom URL must not contain embedded credentials.
|
|
96
95
|
Received: ${t}
|
|
97
|
-
Expected: https://tenant.example.com`);if(!
|
|
96
|
+
Expected: https://tenant.example.com`);if(!o.hostname.includes("."))throw new Error(`Invalid domain: ${o.hostname}. Expected format: tenant.example.com`);let c=`${o.protocol}//${o.host}`,l=process.env[f.FLOW_OBS_ALLOW_HTTP];try{delete process.env[f.FLOW_OBS_ALLOW_HTTP],ht(c);}finally{l!==void 0&&(process.env[f.FLOW_OBS_ALLOW_HTTP]=l);}return c}let r=cn(t),n;try{n=new URL(r);}catch{throw new Error(`Invalid URL: ${t}`)}if(n.protocol!=="https:")throw new Error(`Custom URL must use HTTPS: ${t}`);if(!n.hostname.includes("."))throw new Error(`Invalid domain: ${n.hostname}. Expected format: tenant.example.com`);let s=process.env[f.FLOW_OBS_ALLOW_HTTP];try{delete process.env[f.FLOW_OBS_ALLOW_HTTP],ht(r);}finally{s!==void 0&&(process.env[f.FLOW_OBS_ALLOW_HTTP]=s);}return r.replace(/\/$/,"")}async function ir(){for(let t=1;t<=3;t++)try{let e=await Pe(" Enter your Flow domain (e.g., tenant.ciandt.com)");return cr(e)}catch(e){if(process.stderr.write(R(` \u2717 ${e.message}
|
|
98
97
|
|
|
99
98
|
`)),t===3)throw process.stderr.write(I(` Too many invalid attempts.
|
|
100
99
|
|
|
101
|
-
`)),new Error("Too many invalid URL attempts")}throw new Error("Too many invalid URL attempts")}function
|
|
102
|
-
|
|
103
|
-
`)))
|
|
100
|
+
`)),new Error("Too many invalid URL attempts")}throw new Error("Too many invalid URL attempts")}async function So(t,e,r){let n=ar()[f.FLOW_USER_EMAIL]??null,s=ge(),i=s??"(could not be derived)";if(!t||!Z()){if(r){let a=r.replace(/[\r\n]/g,"").trim();if(a)return J({[f.FLOW_USER_EMAIL]:a}),a}return n??s}function o(a){return a.trim()}function c(a){if(/\s/.test(a))return "Email must not contain spaces";if((a.match(/@/g)??[]).length!==1)return "Email must contain exactly one @";let d=a.indexOf("@");if(d<=0)return "Email must contain a local part before @";let m=a.slice(d+1);if(!m)return "Email must contain a domain after @";if(m.startsWith("."))return `Invalid email domain: ${m}`;try{if(!new URL(`https://${m}`).hostname.includes("."))return "Email domain must contain at least one dot"}catch{return `Invalid email domain: ${m}`}return null}async function l(){for(let a=1;a<=3;a++)try{let d=await Pe(" Enter your corporate email (e.g., user@company.com)"),m=o(d),T=c(m);if(T)throw new Error(T);return m}catch(d){if(process.stderr.write(R(` \u2717 ${d.message}
|
|
101
|
+
|
|
102
|
+
`)),a===3)throw process.stderr.write(I(` Too many invalid attempts.
|
|
104
103
|
|
|
105
|
-
`)),process.stdout.write(
|
|
106
|
-
`)),process.stdout.write(p(` [2/4] Flow Environment Setup Configure Flow URLs and LLM routing
|
|
107
|
-
`)),process.stdout.write(p(` [3/4] Authentication Authenticate with Flow
|
|
108
|
-
`)),process.stdout.write(p(` [4/4] Observability OpenTelemetry metrics, logs and trace hooks
|
|
109
|
-
`)),we(1,r,"Claude Code Installation"),!tr())return ho("Claude Code is not installed or not found in PATH."),process.stdout.write(`
|
|
110
|
-
`),process.stdout.write(P(` Cannot continue \u2014 Claude Code is required.
|
|
104
|
+
`)),new Error("Too many invalid email attempts")}throw new Error("Too many invalid email attempts")}if(n){if(await Bt(` Registered email: ${b(n)} \u2014 still correct?`,true))return process.stdout.write(k(` \u2713 Email: ${b(n)}
|
|
111
105
|
|
|
112
|
-
`)),process.stdout.write(`
|
|
106
|
+
`)),n;let d=await l();return J({[f.FLOW_USER_EMAIL]:d}),process.stdout.write(k(` \u2713 Email updated: ${d}
|
|
113
107
|
|
|
114
|
-
`),process.stdout.write(
|
|
108
|
+
`)),d}if(!s){process.stdout.write(R(`
|
|
109
|
+
\u26A0 Could not derive email from OS username.
|
|
110
|
+
`));let a=await l();return J({[f.FLOW_USER_EMAIL]:a}),process.stdout.write(k(` \u2713 Email saved: ${a}
|
|
115
111
|
|
|
116
|
-
`)),process.stdout.write(`
|
|
112
|
+
`)),a}if(e){if(await Bt(" Is your corporate email domain @ciandt.com?",true))return process.stdout.write(k(` \u2713 Email: ${b(i)}
|
|
117
113
|
|
|
118
|
-
`)
|
|
119
|
-
`)+R(" on Windows too: ")+v(`npm install -g @ciandt-flow/flow-ai-obs
|
|
120
|
-
`)+R(` Running Claude (Windows) + flow-ai-obs (WSL) is not a supported configuration.
|
|
114
|
+
`)),s;{let d=await l();return J({[f.FLOW_USER_EMAIL]:d}),process.stdout.write(k(` \u2713 Email saved: ${d}
|
|
121
115
|
|
|
122
|
-
`)),
|
|
123
|
-
|
|
124
|
-
`),
|
|
125
|
-
|
|
126
|
-
`)
|
|
127
|
-
|
|
116
|
+
`)),d}}else return process.stdout.write(k(` \u2713 Email: ${b(i)}
|
|
117
|
+
|
|
118
|
+
`)),s}function Qt(){try{let t=A__namespace.readFileSync(x(),"utf8"),r=JSON.parse(t).env?.FLOW_BASE_URL;return typeof r=="string"&&r.trim()?r.trim():null}catch{return null}}async function To(t={}){let e=ue();if(e)return e;let r=t.url,n=4;process.stdout.write(b(U(`
|
|
119
|
+
flow-ai-obs init
|
|
120
|
+
`))),process.stdout.write(g(` Configuring your development environment:
|
|
121
|
+
|
|
122
|
+
`)),process.stdout.write(g(` [1/4] Flow Environment Setup Configure Flow URLs and LLM routing
|
|
123
|
+
`)),process.stdout.write(g(` [2/4] User Identity Capture user email for telemetry
|
|
124
|
+
`)),process.stdout.write(g(` [3/4] Authentication Authenticate with Flow
|
|
125
|
+
`)),process.stdout.write(g(` [4/4] Observability OpenTelemetry metrics, logs and trace hooks
|
|
126
|
+
`)),_e(1,n,"Flow Environment Setup");let s=false;{let _=ar().FLOW_BASE_URL;if(_&&(Eo(`Base URL already configured (FLOW_BASE_URL=${_})`),!t.noInteractive&&Z()))try{let{promptRaw:L}=await Promise.resolve().then(()=>(Te(),Se));s=(await L(U(" ? ")+"Replace existing base URL configuration? [y/N]: ")).trim().toLowerCase()==="y",s||on("Keeping existing base URL configuration.");}catch{}}if(process.env.WSL_DISTRO_NAME&&process.platform==="linux"&&process.stdout.write(R(` \u26A0 WSL detected. If your code assistant is installed on Windows, install flow-ai-obs
|
|
127
|
+
`)+R(" on Windows too: ")+U(`npm install -g @ciandt-flow/flow-ai-obs
|
|
128
|
+
`)+R(` Running a Windows code assistant + flow-ai-obs (WSL) is not a supported configuration.
|
|
129
|
+
|
|
130
|
+
`)),wo(),!r&&!t.noInteractive&&Z()){let _=Qt();try{s?r=await ir():_?(process.stdout.write(`
|
|
131
|
+
Current base URL: ${b(_)}
|
|
132
|
+
`),await Bt(" Keep this URL?",!0)||(r=await ir())):(process.stdout.write(`
|
|
133
|
+
`),await Bt(" Does your organization use a custom Flow URL?",!1)?r=await ir():or("Using default Flow Base URL: https://flow.ciandt.com"));}catch{return 1}process.stdout.write(`
|
|
134
|
+
`);}if(!r&&!t.noInteractive&&!Z()){let _=Qt();if(_)process.stdout.write(R(` \u26A0 Non-interactive environment detected.
|
|
135
|
+
`)+g(` Using URL: ${_}
|
|
128
136
|
|
|
129
137
|
`));else return process.stderr.write(` \u2717 No URL configured and no TTY available.
|
|
130
138
|
Run: flow-ai-obs init --custom-url <URL>
|
|
131
139
|
|
|
132
|
-
`),1}let
|
|
133
|
-
\u2717 Invalid --custom-url: ${
|
|
140
|
+
`),1}let i,o=false;if(r){let _;try{_=cr(r,!0);}catch(at){return process.stderr.write(`
|
|
141
|
+
\u2717 Invalid --custom-url: ${at.message}
|
|
134
142
|
|
|
135
|
-
`),1}let
|
|
136
|
-
`)+
|
|
137
|
-
`)+
|
|
143
|
+
`),1}let L=Qt();i=_,o=!!L&&L!==_,o?process.stdout.write(R(` \u26A0 Base URL changed \u2014 re-authentication required.
|
|
144
|
+
`)+g(` Previous: ${L}
|
|
145
|
+
`)+g(` New: ${_}
|
|
138
146
|
|
|
139
|
-
`)):process.stdout.write(
|
|
147
|
+
`)):process.stdout.write(k(` \u2713 Base URL configured: ${_}
|
|
140
148
|
|
|
141
|
-
`));}else
|
|
149
|
+
`));}else i=Qt()??"https://flow.ciandt.com";let c={FLOW_BASE_URL:i,OTEL_EXPORTER_OTLP_ENDPOINT:`${i}/otel`,ANTHROPIC_BASE_URL:`${i}/flow-llm-proxy/`,ANTHROPIC_MODEL:"anthropic.claude-4-6-sonnet",ANTHROPIC_SMALL_FAST_MODEL:"anthropic.claude-4-6-haiku",CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS:"1"};process.env.FLOW_BASE_URL=i,process.stdout.write(k(`
|
|
142
150
|
\u2713 Flow environment ready.
|
|
143
|
-
`));let
|
|
144
|
-
`);
|
|
151
|
+
`));let l=36;for(let[_,L]of Object.entries(c))process.stdout.write(g(` ${_.padEnd(l)}`)+L+`
|
|
152
|
+
`);_e(2,n,"User Identity"),await So(!t.noInteractive,!!(r??We()),t.email),_e(3,n,"Authentication");let a=null,d=Qt(),m=!!d&&d!==i;if(!an()||o||m){if(t.noInteractive||!Z())return process.stderr.write(`
|
|
145
153
|
${I("\u2717")} Authentication required.
|
|
146
154
|
Run: flow-ai-obs login
|
|
147
155
|
|
|
148
156
|
`),1;{process.stdout.write(`
|
|
149
157
|
${R("\u26A0")} Authentication required for the new endpoint.
|
|
150
158
|
|
|
151
|
-
`);let{runLogin:
|
|
152
|
-
${
|
|
153
|
-
`);let
|
|
159
|
+
`);let{runLogin:_}=await Promise.resolve().then(()=>(Te(),Se)),L=await _({deferPersist:true,skipAuthCheck:o});if(typeof L=="number")return L;a=L.result;}}else or("Already authenticated \u2014 skipping."),on("ANTHROPIC_AUTH_TOKEN will be preserved in settings.json");let S=an()?ar()[f.ANTHROPIC_AUTH_TOKEN]:null,p={...c,...a?{[f.ANTHROPIC_AUTH_TOKEN]:a.jwt}:{},...S&&!a?{[f.ANTHROPIC_AUTH_TOKEN]:S}:{}},w,Y;_e(4,n,"Observability (OpenTelemetry)"),process.stdout.write(`
|
|
160
|
+
${b("Metrics and Logs")}
|
|
161
|
+
`);let G={...tt,OTEL_EXPORTER_OTLP_ENDPOINT:c.OTEL_EXPORTER_OTLP_ENDPOINT};for(let[_,L]of Object.entries(G))process.stdout.write(g(` ${_.padEnd(36)}`)+L+`
|
|
154
162
|
`);process.stdout.write(`
|
|
155
|
-
`),process.stdout.write(` ${
|
|
156
|
-
`);let
|
|
163
|
+
`),process.stdout.write(` ${b("Trace (Hook)")}
|
|
164
|
+
`);let z=["UserPromptSubmit","PreToolUse","PostToolUse","Stop"];for(let _ of z){let L=pt[_];process.stdout.write(g(` ${_.padEnd(18)}`)+`\u2192 flow-ai-obs ${_} (timeout: ${L}s)
|
|
157
165
|
`);}process.stdout.write(`
|
|
158
|
-
`);try{({settingsPath:
|
|
159
|
-
`),1}if(
|
|
160
|
-
`),process.stdout.write(R(` \u26A0 Third-party hooks preserved on: ${
|
|
161
|
-
`)),process.stdout.write(
|
|
166
|
+
`);try{({settingsPath:w,preserved:Y}=Dr(c.OTEL_EXPORTER_OTLP_ENDPOINT,p));}catch(_){return process.stderr.write(` \u2717 Failed to write settings: ${_.message}
|
|
167
|
+
`),1}if(a){let{saveTokenCache:_}=await Promise.resolve().then(()=>(zt(),zr));await _({accessToken:a.accessToken,expiresAt:a.expiresAt});let{clearLoggedOutMarker:L}=await Promise.resolve().then(()=>(rr(),sn));L();}return or(`Settings written: ${w}`),Y.length>0&&(process.stdout.write(`
|
|
168
|
+
`),process.stdout.write(R(` \u26A0 Third-party hooks preserved on: ${Y.join(", ")}
|
|
169
|
+
`)),process.stdout.write(g(` flow-ai-obs was prepended \u2014 it executes first.
|
|
162
170
|
`))),process.stdout.write(`
|
|
163
171
|
`),t.skipHint||(process.stdout.write(`
|
|
164
|
-
`),process.stdout.write(
|
|
172
|
+
`),process.stdout.write(k(` \u2713 Setup complete.
|
|
165
173
|
|
|
166
|
-
`)),process.stdout.write(
|
|
167
|
-
`)+
|
|
174
|
+
`)),process.stdout.write(g(` Verify your configuration:
|
|
175
|
+
`)+U(` flow-ai-obs status
|
|
168
176
|
|
|
169
|
-
`)+
|
|
170
|
-
`)+v(` claude
|
|
177
|
+
`)+g(` Start your code assistant and begin working.
|
|
171
178
|
|
|
172
|
-
`))),0}var
|
|
173
|
-
`);}function
|
|
174
|
-
`);}function
|
|
175
|
-
`);}function
|
|
176
|
-
`);}function
|
|
177
|
-
`);}function nt(t){process.stdout.write(` ${
|
|
178
|
-
`);}function
|
|
179
|
+
`))),0}var un=E(()=>{"use strict";vt();v();ut();pe();de();je();W();Ne();});var fn={};N(fn,{runStatus:()=>yo});function dn(t){return !t||t.length<=8?"****":t.slice(0,4)+"****...****"+t.slice(-4)}function _o(t){process.stdout.write(` ${k("\u2713")} ${t}
|
|
180
|
+
`);}function lr(t){process.stdout.write(` ${R("\u26A0")} ${t}
|
|
181
|
+
`);}function Pt(t){process.stdout.write(` ${k("\u2713")} ${t}
|
|
182
|
+
`);}function te(t){process.stdout.write(` ${R("\u26A0")} ${t}
|
|
183
|
+
`);}function ee(t){process.stdout.write(` ${I("\u2717")} ${t}
|
|
184
|
+
`);}function nt(t){process.stdout.write(` ${g(t)}
|
|
185
|
+
`);}function ur(t){process.stdout.write(b(U(`
|
|
179
186
|
${t}
|
|
180
|
-
`)));}function
|
|
181
|
-
${
|
|
182
|
-
`);}function
|
|
183
|
-
`);}async function
|
|
184
|
-
`),process.stdout.write(` ${
|
|
185
|
-
`)):!t.ok&&t.error==="No credentials found"?
|
|
186
|
-
`),process.stdout.write(` ${
|
|
187
|
-
`),process.stdout.write(` ${
|
|
188
|
-
`),process.stdout.write(` ${
|
|
189
|
-
`)):
|
|
190
|
-
`),process.stdout.write(` ${
|
|
187
|
+
`)));}function dr(t,e=false){let r=e?`${R("\u26A0")} ${b(R(t))}`:b(t);process.stdout.write(`
|
|
188
|
+
${r}
|
|
189
|
+
`);}function ye(){process.stdout.write(`
|
|
190
|
+
`);}async function yo(){ur("Auth");let t=await Ee();t.notConfigured?(lr("Not configured."),process.stdout.write(`
|
|
191
|
+
`),process.stdout.write(` ${g("Run `flow-ai-obs init` to set up.")}
|
|
192
|
+
`)):!t.ok&&t.error==="No credentials found"?lr("Not authenticated. Run `flow-ai-obs login` to set up."):t.ok?(_o("Authenticated"),process.stdout.write(` ${g("URL: ")}${t.baseUrl}
|
|
193
|
+
`),process.stdout.write(` ${g("Tenant: ")}${t.tenant}
|
|
194
|
+
`),process.stdout.write(` ${g("User: ")}${t.user}
|
|
195
|
+
`),process.stdout.write(` ${g("Storage: ANTHROPIC_AUTH_TOKEN (settings.json)")}
|
|
196
|
+
`)):lr(`Session rejected by ${t.baseUrl}. Run \`flow-ai-obs login\` to re-authenticate.`),ur("Flow Provider Configuration");let e=["ANTHROPIC_BASE_URL","ANTHROPIC_MODEL","ANTHROPIC_SMALL_FAST_MODEL","CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS"],r={},n={};try{let p=A__namespace.readFileSync(x(),"utf8");n=JSON.parse(p),r=n.env||{};}catch{}let s=e.filter(p=>!r[p]),i=s.length===0;dr("LLM Proxy",!i),i?(Pt("Flow LLM Proxy configured"),nt(`Endpoint: ${r.ANTHROPIC_BASE_URL}`),nt(`Model: ${r.ANTHROPIC_MODEL}`)):(process.stdout.write(`
|
|
197
|
+
`),process.stdout.write(` ${g("Run: flow-ai-obs init (configures the Flow LLM proxy)")}
|
|
191
198
|
`),process.stdout.write(`
|
|
192
|
-
`),
|
|
193
|
-
`);}
|
|
194
|
-
`),process.stdout.write(` ${
|
|
199
|
+
`),te(`${s.length} proxy var(s) missing from settings.json`),s.forEach(p=>ee(`Missing: ${p}`))),ye();for(let p of e){let w=r[p]??I("(missing)");process.stdout.write(g(` ${p.padEnd(36)}`)+w+`
|
|
200
|
+
`);}ur("Observability configuration (OpenTelemetry)");let o=Object.keys(tt).filter(p=>!r[p]);dr("Metrics and Logs",o.length>0),o.length===0?(Pt("All OTEL env vars present in settings.json"),nt(`Endpoint: ${r.OTEL_EXPORTER_OTLP_ENDPOINT}`)):(process.stdout.write(`
|
|
201
|
+
`),process.stdout.write(` ${g("Run: flow-ai-obs init (restores missing vars automatically)")}
|
|
195
202
|
`),process.stdout.write(`
|
|
196
|
-
`),
|
|
197
|
-
`);}let
|
|
198
|
-
`),process.stdout.write(` ${
|
|
203
|
+
`),te(`${o.length} OTEL var(s) missing from settings.json`),o.forEach(p=>ee(`Missing: ${p}`))),ye();for(let p of Object.keys(tt)){let w=r[p]??I("(missing)");process.stdout.write(g(` ${p.padEnd(36)}`)+w+`
|
|
204
|
+
`);}let c=n.hooks??{},l=["UserPromptSubmit","PreToolUse","PostToolUse","Stop"],a=l.every(p=>{let w=c[p];return Array.isArray(w)?w.some(Y=>{let G=Y;return Array.isArray(G?.hooks)&&G.hooks.some(z=>z?.command?.startsWith(Vt.CLI))}):false});dr("Tracing",!a),a?Pt("Hooks registered (trace capture)"):(process.stdout.write(`
|
|
205
|
+
`),process.stdout.write(` ${g("Run `flow-ai-obs init` to configure.")}
|
|
199
206
|
`),process.stdout.write(`
|
|
200
|
-
`),
|
|
201
|
-
`);}
|
|
202
|
-
`),1;let e;try{e=(await
|
|
207
|
+
`),te("Hooks NOT registered."));for(let p of l){let w=pt[p];process.stdout.write(g(` ${p.padEnd(18)}`)+`\u2192 flow-ai-obs ${p} (timeout: ${w}s)
|
|
208
|
+
`);}ye();let d=process.env[f.FLOW_TELEMETRY]==="true",m=process.env[f.LANGFUSE_BASE_URL],T=process.env[f.LANGFUSE_PUBLIC_KEY],S=process.env[f.LANGFUSE_SECRET_KEY];if(d)if(m&&T&&S){let p=await K();for(let w of p)w.mode==="direct"&&(Pt("FLOW_TELEMETRY=true (direct mode enabled)"),Pt("Mode: direct"),nt(`Endpoint: ${w.endpoint}`),nt(`PK: ${dn(T)}`),nt(`SK: ${dn(S)}`));}else te("FLOW_TELEMETRY=true but missing LANGFUSE vars:"),m||ee("LANGFUSE_BASE_URL not set"),T||ee("LANGFUSE_PUBLIC_KEY not set"),S||ee("LANGFUSE_SECRET_KEY not set");else {let p=await K();if(p.length>0)for(let w of p)w.mode==="gateway"&&(Pt("Mode: gateway"),nt(`Endpoint: ${w.endpoint}`));else p.authError?te("Gateway mode: token refresh failed. Run `flow-ai-obs login`."):nt("No active tracing destination configured.");}return ye(),0}var mn=E(()=>{"use strict";W();vt();v();ut();sr();});var gn={};N(gn,{runOtelHeaders:()=>Oo});async function Oo(){let t=rt(process.env[f.ANTHROPIC_AUTH_TOKEN]);if(!t)return process.stderr.write(`[flow-ai-obs otel-headers] Not authenticated \u2014 run: flow-ai-obs auth login
|
|
209
|
+
`),1;let e;try{e=(await F(t)).accessToken;}catch(r){return process.stderr.write(`[flow-ai-obs otel-headers] Token fetch failed: ${r.message}
|
|
203
210
|
`),1}return e?(process.stdout.write(`{"Authorization": "Bearer ${e}"}
|
|
204
211
|
`),0):(process.stderr.write(`[flow-ai-obs otel-headers] Empty token received
|
|
205
|
-
`),1)}var
|
|
206
|
-
`)[0].slice(0,e).trim()}function
|
|
207
|
-
`);for(let
|
|
208
|
-
`),
|
|
209
|
-
|
|
210
|
-
`),inputTokens:
|
|
211
|
-
`)[0].match(/^\/([a-z][a-z0-9-]*(?::[a-z][a-z0-9-]*)?)(?:\s.*)?$/i)?.[1]??null}function
|
|
212
|
-
`);return}let
|
|
213
|
-
`,{flag:"a",encoding:"utf8",mode:384}),
|
|
214
|
-
${
|
|
215
|
-
${
|
|
216
|
-
`)),
|
|
217
|
-
`),process.stdin.on("data",e=>process.stdout.write(e));}}var ts=
|
|
218
|
-
`),process.exit(0);});});var
|
|
219
|
-
`+t(" flow-ai-obs")+
|
|
220
|
-
|
|
221
|
-
`),process.stdout.write(e(" init")+
|
|
222
|
-
`)),process.stdout.write(
|
|
223
|
-
`)),process.stdout.write(
|
|
224
|
-
`)),process.stdout.write(
|
|
225
|
-
`)),process.stdout.write(e("
|
|
226
|
-
`)),process.stdout.write(
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
`)),process.stdout.write(
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
`);
|
|
235
|
-
|
|
236
|
-
|
|
212
|
+
`),1)}var hn=E(()=>{"use strict";mt();W();v();});function q(t,e){let r=typeof t=="object"?JSON.stringify(t):String(t??"");return r.length>e?r.slice(0,e)+" \u2026[truncated]":r}function Oe(t,e=100){return String(t??"").split(`
|
|
213
|
+
`)[0].slice(0,e).trim()}function re(){return new Promise(t=>{let e="";process.stdin.setEncoding("utf8"),process.stdin.on("data",r=>{e+=r;}),process.stdin.on("end",()=>{try{t(JSON.parse(e));}catch{t({});}});})}function V(t){process.stdout.write(JSON.stringify(t));}var Nt=E(()=>{"use strict";});function st(){return String(BigInt(Date.now())*1000000n)}var pr,Et,ne=E(()=>{"use strict";pr=()=>crypto.randomBytes(16).toString("hex"),Et=()=>crypto.randomBytes(8).toString("hex");});function Co(t,e){let r=Rt.resolve(t);if(!r.startsWith(e))throw new Error(`Path traversal detected: ${t}`);return r}function fr(t){if(!Po.test(t))throw new Error(`Invalid session ID: ${t}`);return Co(Rt.join(gt.tmpdir(),`flow-obs-${t}.json`),No)}function Ct(t){let e=fr(t);if(!A.existsSync(e))return null;try{return JSON.parse(A.readFileSync(e,"utf8"))}catch{return null}}function $t(t,e){A.writeFileSync(fr(t),JSON.stringify(e),{encoding:"utf8",mode:384});}function mr(t){try{A.unlinkSync(fr(t));}catch{}}var Po,No,se=E(()=>{"use strict";Po=/^[0-9a-f-]{1,64}$/i,No=Rt.normalize(gt.tmpdir())+Rt.sep;});function _n(t){if(!t||!A.existsSync(t))return null;try{let e=A.readFileSync(t,"utf8").trimEnd().split(`
|
|
214
|
+
`);for(let r=e.length-1;r>=0;r--)try{let n=JSON.parse(e[r]);if(n.type==="user"&&n.uuid)return n.uuid}catch{}}catch{}return null}function gr(t){if(!t||!A.existsSync(t))return null;try{let e=A.readFileSync(t,"utf8").trimEnd().split(`
|
|
215
|
+
`),r=[],n=0,s=0;for(let i=e.length-1;i>=0;i--)try{let o=JSON.parse(e[i]);if(o.type==="user")break;if(o.type==="assistant"){let l=(o.message?.content??[]).filter(d=>d.type==="text").map(d=>d.text??"").join("");l&&r.unshift(l);let a=o.message?.usage??{};n+=(a.input_tokens??0)+(a.cache_read_input_tokens??0)+(a.cache_creation_input_tokens??0),s+=a.output_tokens??0;}}catch{}return !r.length&&n===0?null:{text:r.join(`
|
|
216
|
+
|
|
217
|
+
`),inputTokens:n,outputTokens:s}}catch{}return null}var hr=E(()=>{"use strict";});function An(t){return t.replace(":","/")}function Ae(t,e){if(!t)return null;let r=An(t),n=[Rt.join(gt.homedir(),".claude","skills",r,"SKILL.md"),Rt.join(e??"",".claude","skills",r,"SKILL.md")];for(let s of n)if(A.existsSync(s))try{return A.readFileSync(s,"utf8")}catch{}return null}function Ln(t){return t.split(`
|
|
218
|
+
`)[0].match(/^\/([a-z][a-z0-9-]*(?::[a-z][a-z0-9-]*)?)(?:\s.*)?$/i)?.[1]??null}function kn(t){return !!t.slashSkill||t.toolCalls.some(n=>n.tool==="Skill")?t.toolCalls.some(n=>n.tool==="Skill"&&!n.synthetic||Ho.has(n.tool))?"complete":"prerequisite_required":null}function Le(t,e){if(!t)return null;let r=An(t),n=[Rt.join(gt.homedir(),".claude","skills",r),Rt.join(e??"",".claude","skills",r)],s=null;for(let c of n)if(A.existsSync(Rt.join(c,"SKILL.md"))){s=c;break}if(!s)return null;let i=[];function o(c,l){for(let a of A.readdirSync(c,{withFileTypes:true})){if(Do.has(a.name)||Bo.has(a.name)||Mo.has(Rt.extname(a.name)))continue;let d=l?`${l}/${a.name}`:a.name;a.isDirectory()?o(Rt.join(c,a.name),d):i.push(d);}}return o(s,""),i.length>0?i:null}var Do,Mo,Bo,Ho,ke=E(()=>{"use strict";Do=new Set([".venv","__pycache__",".git","node_modules"]),Mo=new Set([".pyc",".pyo"]),Bo=new Set(["SKILL.md",".DS_Store",".gitignore"]);Ho=new Set(["Read","Write","Edit","MultiEdit","Bash","Glob","Grep","TodoWrite","WebFetch","WebSearch","Agent","Task"]);});function Vo(t){try{let e=t.split(".")[1].replace(/-/g,"+").replace(/_/g,"/");return JSON.parse(Buffer.from(e,"base64").toString())}catch{return null}}function Yo(t,e,r,n,s,i){return new Promise(o=>{let c=new URL(t),l=c.protocol==="https:",a=m=>m.replace(/[\r\n]/g,""),d=(l?fs__default.default:Ps__default.default).request({hostname:c.hostname,port:c.port||(l?443:80),path:c.pathname+c.search,method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(e),...i?{}:{Authorization:`Bearer ${a(String(r))}`},FlowTenant:a(String(n)),...s?{"x-flow-user":a(s)}:{},...i?{"x-flow-api-key":a(i)}:{}}},m=>{m.resume(),o(m.statusCode??0);});d.on("error",()=>o(0)),d.setTimeout(5e3,()=>{d.destroy(),o(0);}),d.write(e),d.end();})}async function wt(t,e={}){try{let r=rt(process.env[f.ANTHROPIC_AUTH_TOKEN]);if(!r)return;let n,s=new Promise((S,p)=>{n=setTimeout(()=>p(new Error("getToken timeout")),4e3),n.unref();}),{accessToken:i}=await Promise.race([F(r),s]);clearTimeout(n);let o=Vo(i);if(!o)return;let c=o.tenant||r.tenant,l=JSON.stringify({action:t,booster:le().BOOSTER,metadata:e,success:!0,tenant:c,timestamp:new Date().toISOString(),os:process.platform,user:{email:o.email||"",id:o.sub||"",name:o.name||o.email||""}}),a=ge(),d=rn(),m=ht(le().API_URL),T=await Yo(m,l,i,c,a,d);u("metrics.logEvent",`action=${t} status=${T} x-flow-user=${a?"[REDACTED]":"omitted"} x-flow-api-key=${d?"[REDACTED]":"omitted"}`);}catch(r){u("metrics.logEvent",`silenced error: ${r.message}`);}}var ve=E(()=>{"use strict";v();mt();W();H();});async function Er(t,e=false){if(e){process.stdout.write(JSON.stringify({decision:"block",reason:Go})+`
|
|
219
|
+
`);return}let n=!!(await K()).authError;!process.env[f.FLOW_USER_EMAIL]&&!Gt(f.FLOW_USER_EMAIL)&&Ut().then(m=>{m&&(J({[f.FLOW_USER_EMAIL]:m}),u("UserPromptSubmit","auto-persisted FLOW_USER_EMAIL from access token"));}).catch(()=>{});let s=t.session_id||"unknown",i=t.prompt||"",o=t.cwd||"",c=_n(t.transcript_path)||pr(),l=Ln(i),a=l?Ae(l,o):null,d=l?Le(l,o):null;$t(s,{traceId:pr(),spanId:Et(),startNs:st(),sessionId:s,prompt:i,cwd:o,traceName:c,transcriptPath:t.transcript_path||"",model:process.env[f.ANTHROPIC_MODEL]||"",toolCalls:[],spans:[],pendingTool:null,slashSkill:l,skillContent:a,skillArtifacts:d}),wt("SESSION_STARTED",{traceType:l?"skill":"prompt",slashSkill:l,clientIdExpired:n}),u("UserPromptSubmit",`sid=${s}`,`traceName=${c}`,`slashSkill=${l}`),V(t);}var Go,vn=E(()=>{"use strict";ne();se();hr();ke();Nt();H();v();W();vt();ve();Go=`\u26D4 Your Flow API key has expired. You no longer have access to Claude Code through the Flow platform. To restore observability and access, visit ${Q()}/settings/api-keys to generate a new API key, then run: flow-ai-obs login`;});async function Rn(t){let e=t.session_id||"unknown",r=t.tool_name||"unknown",n=t.tool_input||{},s=Ct(e);s&&(s.pendingTool={name:r,inputStr:q(n,B.TOOL_INPUT),startNs:st()},$t(e,s)),u("PreToolUse",`sid=${e}`,`tool=${r}`,`stateFound=${!!s}`),V(t);}var bn=E(()=>{"use strict";ne();se();Nt();H();v();});function h(t,e){return e==null||e===""?null:{key:t,value:{stringValue:String(e)}}}function St(...t){return t.filter(e=>e!==null)}function In(t,e){return {resourceSpans:[{resource:{attributes:t},scopeSpans:[{scope:Jo,spans:Array.isArray(e)?e:[e]}]}]}}var Jo,O,Un=E(()=>{"use strict";v();Jo={name:ce.SCOPE_NAME,version:ce.SCOPE_VERSION},O={TRACE_NAME:"langfuse.trace.name",TRACE_INPUT:"langfuse.trace.input",TRACE_OUTPUT:"langfuse.trace.output",TRACE_METADATA:"langfuse.trace.metadata",TRACE_TAGS:"langfuse.trace.tags",USER_ID:"langfuse.user.id",SESSION_ID:"langfuse.session.id",OBS_NAME:"langfuse.observation.name",OBS_INPUT:"langfuse.observation.input",OBS_OUTPUT:"langfuse.observation.output",OBS_LEVEL:"langfuse.observation.level",OBS_TYPE:"langfuse.observation.type",MODEL:"gen_ai.request.model",INPUT_TOKENS:"gen_ai.usage.input_tokens",OUTPUT_TOKENS:"gen_ai.usage.output_tokens"};});function Nn(t,e,r,n,s){if(process.env[f.FLOW_OBS_DEBUG]!=="1")return;let i=JSON.stringify({ts:new Date().toISOString(),request:{method:"POST",url:t,headers:e,body:JSON.parse(r)},response:{status:n,body:s}});try{A.writeFileSync(Pn,i+`
|
|
220
|
+
`,{flag:"a",encoding:"utf8",mode:384}),u("sendTraces:dump",`request appendada em ${Pn}`);}catch(o){u("sendTraces:dump",`falha ao salvar: ${o.message}`);}}function Qo(t){let e=new URL(t),r=new URL(dt().GATEWAY_HEALTH);return r.hostname=e.hostname,r.port=e.port,r.protocol=e.protocol,r}function Cn(t,e){return new Promise((r,n)=>{let s=t._isSSL?fs__default.default:Ps__default.default;t.headers=Object.assign({},t.headers,{Connection:"close"});let i=s.request(t,o=>{let c=[];o.on("data",l=>c.push(l)),o.on("end",()=>r({statusCode:o.statusCode??0,body:c.join("")}));});i.setTimeout(1e4,()=>{i.destroy(new Error("Request timeout"));}),i.on("error",o=>n(new Error(`Network error: ${o.message}`))),e&&i.write(e),i.end();})}async function $n(t,e){let r;try{r=Qo(t);}catch{return false}let n=r.protocol==="https:";try{let s={};e&&(s.Authorization=String(e).replace(/[\r\n]/g,""));let i=await Cn({hostname:r.hostname,port:r.port||(n?443:80),path:r.pathname,method:"GET",headers:s,_isSSL:n},null);return u("checkHealth",`url=${r.href} status=${i.statusCode}`),i.statusCode>=200&&i.statusCode<300}catch{return false}}async function Re(t,e,r){let n=JSON.stringify(t),s=new URL(e),i=s.protocol==="https:",o=String(r).replace(/[\r\n]/g,""),c={"Content-Type":"application/json",Authorization:o,"Content-Length":Buffer.byteLength(n)};u("sendTraces:request",`POST ${e}`),u("sendTraces:request",`headers=${JSON.stringify({...c,Authorization:o.slice(0,20)+"\u2026"})}`),u("sendTraces:request",`body=${n.slice(0,500)}${n.length>500?"\u2026":""}`);try{let l=await Cn({hostname:s.hostname,port:s.port||(i?443:80),path:s.pathname,method:"POST",headers:c,_isSSL:i},n);return u("sendTraces:response",`status=${l.statusCode}`),Nn(e,c,n,l.statusCode,l.body),l.statusCode}catch(l){return u("sendTraces:error",l.message),Nn(e,c,n,0,l.message),0}}var Pn,Fn=E(()=>{"use strict";v();H();Pn=Rt.join(gt.tmpdir(),"flow-obs-requests.ndjson");});function ti(){let t=parseInt(process.env[f.BUFFER_TTL_DAYS]??"",10);return (Number.isFinite(t)?Math.max($.MIN_TTL_DAYS,Math.min($.MAX_TTL_DAYS,t)):$.DEFAULT_TTL_DAYS)*24*60*60*1e3}function ei(){let t=parseInt(process.env[f.BUFFER_MAX_FILES]??"",10);return Number.isFinite(t)?Math.max($.MIN_MAX_FILES,Math.min($.MAX_MAX_FILES,t)):$.DEFAULT_MAX_FILES}function Dn(t){if(/[/\\]/.test(t))throw new Error(`Invalid buffer fileId: ${t}`);return Rt__namespace.default.join(gt__namespace.default.tmpdir(),`${$.FILE_PREFIX}${t}.json`)}function Sr(){let t=gt__namespace.default.tmpdir(),e;try{e=A__namespace.default.readdirSync(t);}catch{return []}return e.filter(r=>r.startsWith($.FILE_PREFIX)&&r.endsWith(".json")).map(r=>{let n=Rt__namespace.default.join(t,r),s=0;try{s=A__namespace.default.statSync(n).mtimeMs;}catch{}return {full:n,mtime:s}}).sort((r,n)=>r.mtime-n.mtime).map(r=>r.full)}function oe(t){try{let e=ei(),r=Sr();if(r.length>=e){let i=r.slice(0,r.length-e+1);for(let o of i)try{A__namespace.default.unlinkSync(o);}catch{}}let n=`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,s={fileId:n,bufferedAt:Date.now(),payload:t};return A__namespace.default.writeFileSync(Dn(n),JSON.stringify(s),{encoding:"utf8",mode:384}),u("buffer",`saved fileId=${n}`),n}catch(e){return u("buffer",`saveToBuffer failed: ${e.message}`),null}}function Mn(t){let e=Sr(),r=t!=null&&t>0?t:e.length,n=[];for(let s of e){if(n.length>=r)break;try{let i=A__namespace.default.readFileSync(s,"utf8"),o=JSON.parse(i);o&&o.fileId&&o.payload&&n.push(o);}catch{u("buffer",`skipping malformed file: ${s}`);}}return n}function Bn(t){try{A__namespace.default.unlinkSync(Dn(t)),u("buffer",`deleted fileId=${t}`);}catch{}}function Hn(){let t=Date.now()-ti();for(let e of Sr())try{let{mtimeMs:r}=A__namespace.default.statSync(e);r<t&&(A__namespace.default.unlinkSync(e),u("buffer",`evicted stale: ${Rt__namespace.default.basename(e)}`));}catch{}}var Wn=E(()=>{"use strict";v();H();});async function ri(t){Hn();let e=Mn($.REPLAY_BATCH_SIZE);e.length&&(u("replayBufferedTraces",`replaying ${e.length} buffered trace(s)`),await Promise.allSettled(e.map(async r=>{try{let n=await Re(r.payload,t.endpoint,t.authHeader);n>=200&&n<300?(Bn(r.fileId),u("replayBufferedTraces",`replayed fileId=${r.fileId} status=${n}`)):u("replayBufferedTraces",`replay failed fileId=${r.fileId} status=${n}`);}catch(n){u("replayBufferedTraces",`replay error fileId=${r.fileId}: ${n.message}`);}})));}async function jn(t){let e=await K();if(!e.length)return e.authError&&(u("postToLangfuse","auth refresh failed \u2014 buffering trace"),oe(t)),0;let r=await Promise.all(e.map(async i=>{if(i.mode!=="gateway")return {creds:i,healthy:true};let o=await $n(i.endpoint,i.authHeader);return {creds:i,healthy:o}})),n=r.find(i=>i.creds.mode==="gateway"&&i.healthy)?.creds??r.find(i=>i.creds.mode==="direct")?.creds;return n&&await ri(n),(await Promise.all(r.map(async({creds:i,healthy:o})=>{if(i.mode==="gateway"){if(!o)return u("postToLangfuse","gateway health check failed \u2014 buffering trace"),oe(t),0;let l=await Re(t,i.endpoint,i.authHeader);return (l===0||l>=500)&&(u("postToLangfuse",`gateway send failed (status ${l}) \u2014 buffering trace`),oe(t)),l}let c=await Re(t,i.endpoint,i.authHeader);return (c===0||c>=500)&&(u("postToLangfuse",`direct endpoint unavailable (status ${c}) \u2014 buffering trace`),oe(t)),c}))).find(i=>i!==0)??0}var Vn=E(()=>{"use strict";W();H();Fn();Wn();v();});var Tr=E(()=>{"use strict";Un();Vn();});function it(t){if(t==null)return "";let e=typeof t=="string"?t:JSON.stringify(t);return ii.reduce((r,{re:n,replace:s})=>r.replace(n,s),e)}var D,ni,si,oi,Yn,ii,_r=E(()=>{"use strict";D="[REDACTED]",ni="[REDACTED-EMAIL]",si="[REDACTED-CPF]",oi="[REDACTED-CNPJ]",Yn="[REDACTED-PHONE]",ii=[{re:/\b(sk-[A-Za-z0-9_\-]{20,})/g,replace:()=>`sk-${D}`},{re:/\b(pk-[A-Za-z0-9_\-]{20,})/g,replace:()=>`pk-${D}`},{re:/\b(Bearer\s+)[A-Za-z0-9\-._~+/]+=*/gi,replace:(t,e)=>`${e}${D}`},{re:/\b(Basic\s+)[A-Za-z0-9+/]+=*/gi,replace:(t,e)=>`${e}${D}`},{re:/(-----BEGIN [A-Z ]+-----)[^-]*(-----END [A-Z ]+-----)/g,replace:(t,e,r)=>`${e}
|
|
221
|
+
${D}
|
|
222
|
+
${r}`},{re:/\b(AKIA[0-9A-Z]{16})\b/g,replace:()=>`AKIA${D}`},{re:/(aws_secret_access_key\s*[=:]\s*)([A-Za-z0-9/+]{40})/gi,replace:(t,e)=>`${e}${D}`},{re:/\b(ghp_[A-Za-z0-9]{36,})/g,replace:()=>`ghp_${D}`},{re:/\b(github_pat_[A-Za-z0-9_]{36,})/gi,replace:()=>`github_pat_${D}`},{re:/\b(eyJ[A-Za-z0-9_\-]+\.eyJ[A-Za-z0-9_\-]+\.[A-Za-z0-9_\-]+)/g,replace:()=>`eyJ.${D}`},{re:/\b([A-Z0-9_]*(?:SECRET|TOKEN|KEY|PASSWORD|PASSWD|PWD|CREDENTIAL|API)[A-Z0-9_]*\s*=\s*)(['"]?)([^\s'"#\n]+)\2/gi,replace:(t,e,r)=>`${e}${r}${D}${r}`},{re:/([a-z][a-z0-9+\-.]*:\/\/[^:/?#\s]*):([^@\s]+)@/gi,replace:(t,e)=>`${e}:${D}@`},{re:/[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}/g,replace:()=>ni},{re:/\b\d{3}\.\d{3}\.\d{3}-\d{2}\b/g,replace:()=>si},{re:/\b\d{2}\.\d{3}\.\d{3}\/\d{4}-\d{2}\b/g,replace:()=>oi},{re:/\(\d{2}\)\s?\d{4,5}[-\s]?\d{4}/g,replace:()=>Yn},{re:/\+55[\s-]?\d{2}[\s-]?\d{4,5}[-\s]?\d{4}/g,replace:()=>Yn}];});async function Gn(t){let e=t.session_id||"unknown",r=t.tool_name||"unknown",n=t.tool_input||{},s=t.tool_response,i=s!==null&&typeof s=="object"?s.output??JSON.stringify(s):s??"",o=Ct(e);if(!o){V(t);return}let c=st(),l=o.pendingTool,a=l?.name===r,d=a?l.startNs:String(BigInt(c)-200000000n),m=a?l.inputStr:q(n,B.TOOL_INPUT),T=m,S=null;if(r==="Skill"){let ae=typeof n=="object"&&n!==null?n.skill||n.name||n.skillName||n.commandName||String(Object.values(n)[0]??""):String(n);S=ae?String(ae).trim():null;let ct=S?Ae(S,o.cwd):null;ct&&(T=ct,o.skillContent||(o.skillContent=ct),o.skillArtifacts||(o.skillArtifacts=Le(S,o.cwd))),S&&!o.slashSkill&&(o.slashSkill=S),u("PostToolUse","Skill tool detected",`skillName=${S}`,`contentFound=${!!ct}`);}let p=it(q(i,B.TOOL_OUTPUT)),w=/\b(error|exception|failed|failure|traceback|errno)\b/i.test(p.slice(0,500)),Y=w?"ERROR":"DEFAULT",G=Et(),z=Math.round(Number(BigInt(c)-BigInt(d))/1e6),L={Agent:"AGENT",Task:"AGENT"}[r]??"TOOL",at=r==="Skill"&&S?S:Oe(m,60);o.toolCalls.push({tool:r,brief:at,error:w,durationMs:z});let xt=o.spans;xt.push({traceId:o.traceId,spanId:G,parentSpanId:o.spanId,name:r,kind:3,startTimeUnixNano:d,endTimeUnixNano:c,attributes:St(h(O.OBS_NAME,r),h(O.OBS_TYPE,L),h(O.OBS_LEVEL,Y),h(O.OBS_INPUT,it(T)),h(O.OBS_OUTPUT,p),h("tool.name",r),h("tool.error",String(w)),r==="Skill"&&S?h("skill.name",S):null,r==="Skill"?h("skill.invocation","slash-command"):null),status:{code:w?2:1}}),o.pendingTool=null,$t(e,o),w&&wt("TOOL_ERROR",{toolName:r}),u("PostToolUse",`sid=${e}`,`tool=${r}`,`error=${w}`,`durationMs=${z}`,`totalSpans=${xt.length}`),V(t);}var Jn=E(()=>{"use strict";ne();se();Tr();Nt();ke();H();v();_r();ve();});function qn(t,e,r){let n=Object.keys(Kn).find(o=>(t??"").toLowerCase().includes(o));if(!n)return;let s=Kn[n],i=(e*s.input+r*s.output)/1e6;return Math.round(i*1e6)/1e6}var Kn,Xn=E(()=>{"use strict";Kn={"claude-opus-4-6":{input:15,output:75},"claude-opus-4-5":{input:15,output:75},"claude-sonnet-4-6":{input:3,output:15},"claude-sonnet-4-5":{input:3,output:15},"claude-haiku-4-5":{input:.8,output:4},"claude-4-6-opus":{input:15,output:75},"claude-4-6-sonnet":{input:3,output:15},"claude-4-5-opus":{input:15,output:75},"claude-4-5-sonnet":{input:3,output:15},"claude-4-5-haiku":{input:.8,output:4},"claude-3-5-sonnet-20241022":{input:3,output:15},"claude-3-5-haiku-20241022":{input:.8,output:4},"claude-3-opus-20240229":{input:15,output:75}};});async function zn(t){let e=t.session_id||"unknown",r=t.stop_reason||"end_turn",n=Ct(e);if(!n){V(t);return}n.slashSkill&&!/^[a-z][a-z0-9-]*(?::[a-z][a-z0-9-]*)?$/i.test(n.slashSkill)&&(u("Stop",`sid=${e}`,`slashSkill rejected post-disk: "${n.slashSkill}"`),n.slashSkill=null);let s=st(),i=await en(),o=n.toolCalls,c=n.spans;if(n.slashSkill&&!o.some(y=>y.tool==="Skill")){let y=Et(),lt=n.skillContent?n.skillContent:JSON.stringify({skill:n.slashSkill});o.push({tool:"Skill",brief:n.slashSkill,error:false,durationMs:0,synthetic:true}),c.push({traceId:n.traceId,spanId:y,parentSpanId:n.spanId,name:"Skill",kind:3,startTimeUnixNano:n.startNs,endTimeUnixNano:n.startNs,attributes:St(h(O.OBS_NAME,"Skill"),h(O.OBS_TYPE,"TOOL"),h(O.OBS_LEVEL,"DEFAULT"),h(O.OBS_INPUT,lt),h(O.OBS_OUTPUT,"loaded via slash command"),h("tool.name","Skill"),h("tool.error","false"),h("skill.name",n.slashSkill),h("skill.invocation","slash-command")),status:{code:1}}),u("Stop",`slashSkill=${n.slashSkill}`,"synthetic span injected");}let l=t.transcript_path||n.transcriptPath||"",a=gr(l);if(l&&(o.some(y=>y.tool==="Skill"&&!y.synthetic)||!!n.slashSkill)&&!a?.text){await new Promise(lt=>setTimeout(lt,500));let y=gr(l);y?.text&&(a=y);}u("Stop",`transcriptPath=${l||"(empty)"}`,`assistantOut=${a?`text=${a.text.length}chars`:"null"}`);let m=o.length,T=o.filter(y=>y.error).length,S=it(a?.text?q(a.text,B.TRACE_OUTPUT):m===0?"No tools used":o.map((y,lt)=>`${lt+1}. ${y.tool}${y.brief?` \u2192 ${y.brief}`:""}${y.error?" [ERROR]":""}`).join(`
|
|
223
|
+
`)),p=a?.inputTokens??0,w=a?.outputTokens??0,Y=o.map((y,lt)=>`${lt+1}. ${y.tool}${y.brief?` \u2192 ${y.brief}`:""}${y.error?" [ERROR]":""} (${y.durationMs}ms)`),G=!!(n.slashSkill||o.some(y=>y.tool==="Skill")),z=o.some(y=>y.tool==="Agent");if(!G&&!z){u("Stop",`sid=${e}`,"skipping trace \u2014 no Skill or Agent calls found"),wt("TRACE_SKIPPED",{reason:"no_skill_or_agent"}),mr(e),V(t);return}let _=G?"skill":"agent",L=Math.round(Number(BigInt(s)-BigInt(n.startNs))/1e6),at=qn(n.model,p,w),_t=kn(n);_t==="prerequisite_required"&&a?.text&&(_t="complete"),_t==="prerequisite_required"&&(c.push({traceId:n.traceId,spanId:Et(),parentSpanId:n.spanId,name:"prerequisite-check",kind:3,startTimeUnixNano:n.startNs,endTimeUnixNano:s,attributes:St(h(O.OBS_NAME,"prerequisite-check"),h(O.OBS_TYPE,"EVENT"),h(O.OBS_LEVEL,"WARNING"),h(O.OBS_OUTPUT,S),h("skill.name",n.slashSkill||void 0),h("execution_status","prerequisite_required")),status:{code:1}}),u("Stop",`sid=${e}`,"prerequisite-check span injected",`skill=${n.slashSkill}`));let xt=(()=>{if(!(!G||!n.prompt)){if(n.slashSkill){let y=n.prompt.replace(new RegExp(`^\\/${n.slashSkill}\\s*`,"i"),"").trim();return y?q(it(y),B.USER_INSTRUCTION):void 0}return q(it(n.prompt),B.USER_INSTRUCTION)||void 0}})(),ae=JSON.stringify({trace_type:_,..._t!==null&&{execution_status:_t},...n.slashSkill?{skill_name:n.slashSkill}:{},...n.skillArtifacts?.length&&{skill_artifacts:n.skillArtifacts},...xt!==void 0&&{user_instruction:xt},latency_ms:L,...p&&{tokens_input:p},...w&&{tokens_output:w},cost_usd:at,...n.model?{model:n.model}:{},toolCount:m,errorCount:T,stopReason:r,sessionId:n.sessionId,tools:Y.length?Y:void 0}),ct=it(q(n.prompt,B.TRACE_INPUT)),rs=St(h(O.TRACE_NAME,n.traceName),h(O.TRACE_INPUT,ct),h(O.TRACE_OUTPUT,S),h(O.OBS_INPUT,ct),h(O.OBS_OUTPUT,S),h(O.TRACE_METADATA,ae),h(O.SESSION_ID,n.sessionId),h(O.USER_ID,i.user),h(O.OBS_TYPE,"GENERATION"),h(O.MODEL,n.model),p?h(O.INPUT_TOKENS,p):null,w?h(O.OUTPUT_TOKENS,w):null,h("claude.stop_reason",r),h("claude.tool_count",String(m)),h("claude.error_count",String(T)),h("claude.session_id",n.sessionId),h("flow.trace_type",_),{key:O.TRACE_TAGS,value:{arrayValue:{values:[{stringValue:_}]}}}),ns={traceId:n.traceId,spanId:n.spanId,name:n.traceName,kind:1,startTimeUnixNano:n.startNs,endTimeUnixNano:s,attributes:rs,status:{code:T>0?2:1}},ss=St(h("service.name",process.env.LANGFUSE_PROJECT_NAME||"claude-code"),h("deployment.environment",process.env.LANGFUSE_ENVIRONMENT||"default")),yr=[...c,ns];u("Stop",`sid=${e}`,`totalTools=${m}`,`errorTools=${T}`,`spans=${yr.length}`,`inputTokens=${p}`,`outputTokens=${w}`,`traceOutput="${Oe(S,80)}"`);let os=await jn(In(ss,yr));u("Stop",`POST status=${os}`,`traceId=${n.traceId}`),wt("TRACE_SENT",{latencyMs:L,totalTools:m,errorTools:T,inputTokens:p,outputTokens:w,costUsd:at}),mr(e),V(t);}var Zn=E(()=>{"use strict";ne();se();Tr();W();Xn();hr();Nt();H();ke();_r();v();ve();});var Tt,Qn=E(()=>{"use strict";W();Nt();vn();bn();Jn();Zn();Tt=class t{static passthroughStdin(){let e=[];process.stdin.on("data",r=>e.push(r)),process.stdin.on("end",()=>process.stdout.write(Buffer.concat(e)));}static async userPromptSubmit(){let e=await re(),r;try{r=await K();}catch{process.stdout.write(JSON.stringify(e));return}r.authError?await Er(e,!0):r.length>0?await Er(e):process.stdout.write(JSON.stringify(e));}static async preToolUse(){if(!await me()){t.passthroughStdin();return}let e=await re();await Rn(e);}static async postToolUse(){if(!await me()){t.passthroughStdin();return}let e=await re();await Gn(e);}static async stop(){if(!await me()){t.passthroughStdin();return}let e=await re();await zn(e);}};});var ci={};async function ai(){let t=process.argv[2];switch(t){case "UserPromptSubmit":await Tt.userPromptSubmit();break;case "PreToolUse":await Tt.preToolUse();break;case "PostToolUse":await Tt.postToolUse();break;case "Stop":await Tt.stop();break;default:process.stderr.write(`[flow-obs] unknown event: ${t}
|
|
224
|
+
`),process.stdin.on("data",e=>process.stdout.write(e));}}var ts=E(()=>{"use strict";Qn();ai().catch(t=>{process.stderr.write(`[flow-obs] fatal: ${t.message}
|
|
225
|
+
`),process.exit(0);});});var li=new Set(["UserPromptSubmit","PreToolUse","PostToolUse","Stop"]),[,,M]=process.argv;function ie(t,e){let r=t.indexOf(e);return r!==-1?t[r+1]:void 0}function es(){let{bold:t,cyan:e,dim:r,green:n}=(ut(),P(Ie)),{version:s}=Mt();process.stdout.write(`
|
|
226
|
+
`+t(" flow-ai-obs")+r(" v"+s)+`
|
|
227
|
+
|
|
228
|
+
`),process.stdout.write(e(" init")+r(` Configure environment: Claude Code + Proxy + OTEL + Trace hooks
|
|
229
|
+
`)),process.stdout.write(r(` --custom-url <URL> Set a custom Flow base URL
|
|
230
|
+
`)),process.stdout.write(r(` --no-interactive Suppress interactive prompts (CI/CD)
|
|
231
|
+
`)),process.stdout.write(r(` --custom-email <EMAIL> Set user email (used with --no-interactive)
|
|
232
|
+
`)),process.stdout.write(e(" login")+r(` Refresh authentication token (re-authenticate)
|
|
233
|
+
`)),process.stdout.write(e(" status")+r(` Show current observability configuration
|
|
234
|
+
`)),process.stdout.write(n(" update")+r(` Update to the latest version
|
|
235
|
+
|
|
236
|
+
`)),process.stdout.write(r(` Flags: --version -v Show version
|
|
237
|
+
`)),process.stdout.write(r(` --help -h Show this help
|
|
238
|
+
|
|
239
|
+
`)),process.stdout.write(r(` (Hook events: UserPromptSubmit | PreToolUse | PostToolUse | Stop)
|
|
240
|
+
|
|
241
|
+
`));}if(M==="--version"||M==="-v")(async()=>{let{version:t}=Mt();process.stdout.write(t+`
|
|
242
|
+
`);let e=(Lt(),P(At)),r=await e.fetchLatestVersionAsync().catch(()=>null);if(r&&e.isNewer(t,r.version)){let{dim:n,yellow:s}=(ut(),P(Ie));process.stdout.write(s(`
|
|
243
|
+
Update available: ${t} \u2192 ${r.version}
|
|
244
|
+
`)+n(` Run: flow-ai-obs update
|
|
237
245
|
|
|
238
246
|
`));}process.exit(0);})().catch(()=>process.exit(0));else if(M==="--help"||M==="-h")es(),process.exit(0);else if(M==="init"||M==="install")(async()=>{M==="install"&&process.stderr.write(`Warning: "install" is deprecated, use "init" instead
|
|
239
|
-
`),await(
|
|
240
|
-
`),process.exit(1);});else if(M==="login")(async()=>{await(
|
|
241
|
-
`),process.exit(1);});else if(M==="status")(async()=>{await(
|
|
242
|
-
`),process.exit(1);});else if(M==="update")(async()=>{let t=(
|
|
243
|
-
`),process.exit(1)),t.isNewer(e,
|
|
244
|
-
`),process.exit(0)),await t.runUpdate(
|
|
245
|
-
`),process.exit(1);});else if(M==="otel-headers"){let{runOtelHeaders:t}=(
|
|
247
|
+
`),await(Lt(),P(At)).checkForUpdateInteractive();let{runInit:t}=(un(),P(ln)),e=process.argv.slice(3);process.exit(await t({url:ie(e,"--custom-url"),noInteractive:e.includes("--no-interactive"),email:ie(e,"--custom-email")}));})().catch(t=>{process.stderr.write(`Unexpected error: ${t.message}
|
|
248
|
+
`),process.exit(1);});else if(M==="login")(async()=>{await(Lt(),P(At)).checkForUpdateInteractive();let{runLogin:t}=(Te(),P(Se)),e=process.argv.slice(3),r=await t({clientId:ie(e,"--client-id"),clientSecret:ie(e,"--client-secret"),tenant:ie(e,"--tenant")});process.exit(typeof r=="number"?r:r.code);})().catch(t=>{process.stderr.write(`Unexpected error: ${t.message}
|
|
249
|
+
`),process.exit(1);});else if(M==="status")(async()=>{await(Lt(),P(At)).checkForUpdateInteractive();let{runStatus:t}=(mn(),P(fn));process.exit(await t());})().catch(t=>{process.stderr.write(`Unexpected error: ${t.message}
|
|
250
|
+
`),process.exit(1);});else if(M==="update")(async()=>{let t=(Lt(),P(At)),{version:e}=Mt(),r=await t.fetchLatestVersionAsync();r||(process.stderr.write(` \u2717 Could not reach npm registry \u2014 check your connection.
|
|
251
|
+
`),process.exit(1)),t.isNewer(e,r.version)||(process.stdout.write(` \u2713 Already up to date (v${e})
|
|
252
|
+
`),process.exit(0)),await t.runUpdate(r.version),process.exit(0);})().catch(t=>{process.stderr.write(`Unexpected error: ${t.message}
|
|
253
|
+
`),process.exit(1);});else if(M==="otel-headers"){let{runOtelHeaders:t}=(hn(),P(gn));t().then(e=>process.exit(e)).catch(()=>process.exit(1));}else li.has(M)?(ts(),P(ci)):(es(),process.exit(0));
|