@ciandt-flow/flow-ai-obs 0.9.3-beta.728 → 0.9.3-beta.752
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 +196 -188
- package/dist/index.js +15 -14
- package/dist/setup.js +5 -5
- package/package.json +1 -1
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'),ms=require('https'),A=require('fs'),ht=require('os'),bt=require('path'),child_process=require('child_process'),Ns=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 ms__default=/*#__PURE__*/_interopDefault(ms);var A__namespace=/*#__PURE__*/_interopNamespace(A);var ht__namespace=/*#__PURE__*/_interopNamespace(ht);var bt__namespace=/*#__PURE__*/_interopNamespace(bt);var Ns__default=/*#__PURE__*/_interopDefault(Ns);var be=Object.defineProperty;var as=Object.getOwnPropertyDescriptor;var cs=Object.getOwnPropertyNames;var ls=Object.prototype.hasOwnProperty;var Mt=(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 w=(t,e,r)=>()=>{if(r)throw r[0];try{return t&&(e=t(t=0)),e}catch(n){throw r=[n],n}};var us=(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});},ds=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of cs(e))!ls.call(t,s)&&s!==r&&be(t,s,{get:()=>e[s],enumerable:!(n=as(e,s))||n.enumerable});return t};var P=t=>ds(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 ps?r=>`\x1B[${t}m${r}\x1B[${e}m`:r=>r}var ps,k,I,R,U,b,g,dt=w(()=>{"use strict";ps=!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 Bt=us((di,fs)=>{fs.exports={name:"@ciandt-flow/flow-ai-obs",version:"0.9.3-beta.752",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 Ht(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 o=1;o<=3;o++)try{let i=(await r.question(s)).trim().toLowerCase();if(i===""&&e!==void 0)return r.close(),e;if(i==="y"||i==="yes")return r.close(),!0;if(i==="n"||i==="no")return r.close(),!1;o<3&&process.stdout.write(` Invalid input. Please answer "y" or "n".
|
|
3
|
+
`);}catch(i){throw r.close(),i}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=w(()=>{"use strict";});var At={};N(At,{checkForUpdate:()=>Ts,checkForUpdateInteractive:()=>_s,fetchLatestVersionAsync:()=>vr,isNewer:()=>Ot,primeUpdateCache:()=>ys,runUpdate:()=>kr});function C(){return Ce||(Ce=Bt()),Ce}function Ot(t,e){let r=o=>{let i=String(o).replace(/^v/,"").match(/^(\d+)\.(\d+)\.(\d+)/);return i?[+i[1],+i[2],+i[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>=Es?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=ms__default.default.get(`https://registry.npmjs.org/${encodeURIComponent(e)}/latest`,{timeout:ws},n=>{if(n.statusCode!==200)return n.resume(),t(new Error(`HTTP ${n.statusCode}`));let s="";n.setEncoding("utf8"),n.on("data",o=>{s+=o;}),n.on("end",()=>{try{let o=JSON.parse(s);if(typeof o.version!="string")throw new Error("no version field");t(null,{version:o.version,updatePriority:typeof o.updatePriority=="string"?o.updatePriority:null});}catch(o){t(o);}});});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}`,o=Math.max(n.length,s.length)+2,i="\u2500".repeat(o);process.stderr.write(`
|
|
4
|
+
\u256D${i}\u256E
|
|
5
|
+
\u2502${n.padEnd(o)}\u2502
|
|
6
|
+
\u2502${s.padEnd(o)}\u2502
|
|
7
|
+
\u2570${i}\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${
|
|
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 Ss(t,e=1e4){let r=Mt("readline"),n=C().name,o=` Update available: ${C().version} \u2192 ${t}`,i=` Run: npm install -g ${n}`,l=" Install now? [y/N]: ",c=Math.max(o.length,i.length,l.length-2)+2,a="\u2500".repeat(c);return process.stderr.write(`
|
|
13
|
+
\u256D${a}\u256E
|
|
14
|
+
\u2502${o.padEnd(c)}\u2502
|
|
14
15
|
\u2502${i.padEnd(c)}\u2502
|
|
15
|
-
\u2502${
|
|
16
|
-
\
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
`),
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
`);}}var Ps,j=g(()=>{"use strict";L();Ps=Lt.join(mt.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 n=e.length>400?e.slice(0,400)+"\u2026":e;l("toAuthError",`status=${t} body=${n}`);try{let r=JSON.parse(e);if(typeof r.error=="string"&&(l("toAuthError",`api_error_code=${r.error}`+(r.message?` api_message=${r.message}`:"")),vn[r.error]))return new pt(vn[r.error])}catch{}return t===401||t===403||t===500?new pt("Invalid credentials"):t>=400&&t<500?new pt("Authentication request was rejected"):new Error("Authentication service unavailable, please try again later")}function x(t){return new Promise((e,n)=>{try{Cs(t.tenant);}catch(d){return n(d)}let r=JSON.stringify({clientSecret:t.clientSecret}),o=new URL(ut().AUTH_ENGINE),i=o.protocol==="https:",s={hostname:o.hostname,port:o.port||(i?443:80),path:o.pathname+o.search,method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(r),FlowTenant:t.tenant}};l("getToken",`requesting token tenant=${t.tenant} host=${s.hostname} path=${s.path}`);let c=(i?fs__default.default:Us__default.default).request(s,d=>{let h=[];d.on("data",O=>h.push(O)),d.on("end",()=>{let O=h.join("");if((d.statusCode??0)>=400)return n($s(d.statusCode??0,O));let w;try{w=JSON.parse(O);}catch{return n(new Error("Invalid response from auth engine"))}let S=w.expires_at??new Date(Date.now()+(w.expires_in??3600)*1e3).toISOString();e({accessToken:w.access_token??"",expiresAt:S});});});c.on("error",d=>n(new Error(`Network error: ${d.message}`))),c.write(r),c.end();})}var pt,Ns,vn,ft=g(()=>{"use strict";L();j();pt=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]$/;vn={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 bn(){return process.platform==="win32"?false:process.getuid?.()===0}function oe(){if(bn())return process.stderr.write(`
|
|
16
|
+
\u2502${l.padEnd(c)}\u2502
|
|
17
|
+
\u2570${a}\u256F
|
|
18
|
+
`),new Promise(p=>{let m=r.createInterface({input:process.stdin,output:void 0,terminal:false}),T=false;function S(E){T||(T=true,clearTimeout(d),m.close(),process.stderr.write(`
|
|
19
|
+
`),p(E));}let d=setTimeout(()=>S(false),e);m.once("line",E=>S(E.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 o(i,l){if(!s){if(s=true,i)process.stderr.write(` \u2713 Updated to ${t}. Please restart the command.
|
|
21
|
+
|
|
22
|
+
`);else {let c=l?` (${l})`:"";process.stderr.write(` \u2717 Update failed${c} \u2014 continuing with current version.
|
|
23
|
+
|
|
24
|
+
`);}r();}}n.on("close",(i,l)=>o(i===0,l??void 0)),n.on("error",i=>o(false,i.code));})}function vr(){return new Promise(t=>{Me((e,r)=>t(e||!r?null:r));})}function Ts(){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 _s(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 Ss(e.latestVersion,t.timeoutMs)&&await kr(e.latestVersion);}catch{}}function ys(){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,Es,ws,Lt=w(()=>{"use strict";Ne();Lr=bt__namespace.default.join(ht__namespace.default.tmpdir(),"flow-obs-update-cache.json"),Es=1440*60*1e3,ws=3e3;});var Rr={};N(Rr,{BUFFER:()=>$,CONFIG_DIR_NAME:()=>jt,CONFIG_FILE_NAME:()=>Vt,DEBUG_LOG_FILENAME:()=>Be,ENV:()=>f,FEATURES:()=>ks,FLOW_URLS:()=>As,HOOK_TIMEOUTS:()=>ft,INSTALLER:()=>Yt,NATIVE_OTEL:()=>tt,OTLP:()=>le,STATE_FILE_PREFIX:()=>vs,TRACE_LIMITS:()=>B,VAULT:()=>Wt,getFlowBaseUrl:()=>Q,getFlowUrls:()=>pt,getLlmProxy:()=>Ls,getMetrics:()=>kt});function Q(){let t=process.env.FLOW_BASE_URL;return t&&t.trim()?t.trim():Os}function pt(){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 Ls(){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 kt(){let t=Q();return {API_URL:process.env.FLOW_METRICS_URL||`${t}/metrics-collector-api/log-event`,BOOSTER:"flow-ai-obs"}}var Os,As,Wt,jt,Vt,le,tt,f,ks,Yt,ft,$,Be,B,vs,v=w(()=>{"use strict";Os="https://flow.ciandt.com";As=pt(),Wt={SERVICE:"flow-plugins-cli",ACCOUNT_CREDS:"credentials",ACCOUNT_TOKEN:"token-cache"},jt="FLOW-nodejs",Vt="config.json",le={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"},ks={KEYCHAIN_ENABLED:!1},Yt={LOCK_STALE_MS:3e4,CONNECTIVITY_MAX_RETRY:3,CONNECTIVITY_RETRY_MS:2e3,CLI:"flow-ai-obs "},ft={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};vs="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(Us,e,{flag:"a"});}catch(r){process.stderr.write(`[flow-obs debug ERROR] ${r.message}
|
|
26
|
+
`);}}var Us,H=w(()=>{"use strict";v();Us=bt.join(ht.tmpdir(),Be);});function $s(t){if(!Cs.test(t))throw new Error(`Invalid tenant value: "${t}". Tenant must be lowercase alphanumeric and hyphens (1-64 chars).`)}function Fs(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 mt(br[n.error])}catch{}return t===401||t===403||t===500?new mt("Invalid credentials"):t>=400&&t<500?new mt("Authentication request was rejected"):new Error("Authentication service unavailable, please try again later")}function F(t){return new Promise((e,r)=>{try{$s(t.tenant);}catch(a){return r(a)}let n=JSON.stringify({clientSecret:t.clientSecret}),s=new URL(pt().AUTH_ENGINE),o=s.protocol==="https:",i={hostname:s.hostname,port:s.port||(o?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=${i.hostname} path=${i.path}`);let c=(o?ms__default.default:Ns__default.default).request(i,a=>{let p=[];a.on("data",m=>p.push(m)),a.on("end",()=>{let m=p.join("");if((a.statusCode??0)>=400)return r(Fs(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});});});c.on("error",a=>r(new Error(`Network error: ${a.message}`))),c.write(n),c.end();})}var mt,Cs,br,gt=w(()=>{"use strict";v();H();mt=class extends Error{constructor(e){super(e),this.name="AuthError";}},Cs=/^[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{A__namespace.chmodSync(
|
|
33
|
-
`,{encoding:"utf8",mode:384});try{A__namespace.chmodSync(e,384);}catch{}}finally{xn(n);}}var Fs,jt=g(()=>{"use strict";L();ft();ae();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=A__namespace.default.readFileSync(Wt(),"utf8");return JSON.parse(t)}catch{return {}}}function Bn(t){let e=Wt();A__namespace.default.mkdirSync(Lt__namespace.default.dirname(e),{recursive:true}),A__namespace.default.writeFileSync(e,JSON.stringify(t,null,2),{encoding:"utf8",mode:384});}var Ve,Yt,Mn=g(()=>{"use strict";L();Ve={credentials:"credentials","token-cache":"tokenCache"};Yt=class{static isAvailable(){return !0}static hasExistingData(){try{if(!A__namespace.default.existsSync(Wt()))return !1;let e=JSON.parse(A__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 A.accessSync("/usr/bin/security",A.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 A.accessSync(n,A.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 process.env[p.FLOW_OBS_USE_JSON_VAULT]==="1"?new Yt:await Ks()??new Yt}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";L();Mn();});var zn={};C(zn,{clearFlowCredentials:()=>Xs,getConfigPath:()=>Zs,getEmailFromToken:()=>ue,getFlowCredentials:()=>Xn,getTokenCache:()=>Gt,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 Gt(){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 Gt();return t?new Date(t.expiresAt)>new Date:false}async function ue(){let t=await Gt();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,Jt=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[p.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[p.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 Gt();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[p.ANTHROPIC_MODEL]??"",n=et(process.env[p.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[p.FLOW_TELEMETRY]==="true",i=process.env[p.LANGFUSE_BASE_URL],s=process.env[p.LANGFUSE_PUBLIC_KEY],a=process.env[p.LANGFUSE_SECRET_KEY];if(o&&i&&s&&a){let w="",S=r;n&&(w=await ue().catch(()=>null)??n.clientId);let u={user:w??"",tenant:S??"",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 w=[];return w.authError=false,w}return t}let c;try{c=await so(n);}catch(w){if(l("resolveCredentials",`token refresh failed: ${w.message}`,`(tenant=${n.tenant} clientId=${n.clientId})`),t.length>0)return t.authError=true,t;let S=[];return S.authError=true,S}let h={user:no(c)??n.clientId,tenant:r,team:"",project:"",model:e},O=process.env[p.FLOW_TELEMETRY_GATEWAY]??Z();return t.push({mode:"gateway",...oo(gt(O),{accessToken:c}),...h}),t}async function de(){return (await G()).length>0}var to,W=g(()=>{"use strict";Jt();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 n=child_process.spawnSync("cmd.exe",["/c","claude","--version"],{encoding:"utf8",timeout:5e3});return n.status===0?n.stdout.trim():null}let t=process.platform==="win32"?{encoding:"utf8",timeout:5e3,shell:!0}:{encoding:"utf8",timeout:5e3},e=child_process.spawnSync("claude",["--version"],t);return e.status===0?e.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();A__namespace.default.mkdirSync(Lt__namespace.default.dirname(t),{recursive:!0}),A__namespace.default.writeFileSync(t,"",{mode:384});}catch{}}function tn(){try{A__namespace.default.unlinkSync(Qe());}catch{}}function lo(){try{return A__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(p.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";Jt();W();jt();L();ft();});var he={};C(he,{promptRaw:()=>Kt,runLogin:()=>mo});function V(t){return typeof t=="string"?t.replace(po,""):t}function Kt(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=w(()=>{"use strict";dt();});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:ht__namespace.homedir(),username:process.env.SUDO_USER||process.env.USER||ht__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 bt__namespace.join(e,".claude","settings.json")}return bt__namespace.join(ht__namespace.homedir(),".claude","settings.json")}if(process.platform==="win32"){let t=process.env.USERPROFILE||ht__namespace.homedir();return bt__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 bt__namespace.join(e,".claude","settings.json")}return bt__namespace.join(ht__namespace.homedir(),".claude","settings.json")}var pe=w(()=>{"use strict";de();});function fe(){if(process.platform==="win32"){let r=process.env.APPDATA||bt__namespace.join(ht__namespace.homedir(),"AppData","Roaming");return bt__namespace.join(r,Pr,Nr)}let t=Ur(),e=process.env.XDG_CONFIG_HOME||bt__namespace.join(t.home,".config");return bt__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=w(()=>{"use strict";pe();Pr="flow-ai-obs",Nr="config.json";});function Fr(t){try{let e=A__namespace.statSync(t);Date.now()-e.mtimeMs>xs&&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 Ds(t,e){let n=(Array.isArray(t)?t:[]).map(s=>{if(!Array.isArray(s?.hooks))return null;let o=s.hooks.filter(i=>!i.command?.startsWith?.("flow-ai-obs "));return o.length>0?{...s,hooks:o}:null}).filter(s=>s!=null);return [e,...n]}function Dr(t,e){let r=x(),n=r+".lock",s=[];A__namespace.mkdirSync(bt__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 o=fe();if(A__namespace.existsSync(o)){let d=o+".bkp";A__namespace.copyFileSync(o,d);try{A__namespace.chmodSync(d,384);}catch{}}let i={};try{i=JSON.parse(A__namespace.readFileSync(r,"utf8"));}catch{}let l=i.env&&typeof i.env=="object"?i.env:{};delete l.OTEL_EXPORTER_OTLP_HEADERS;let{getFlowUrls:c}=(v(),P(Rr)),a=c().OTEL_ENDPOINT,p={...tt,OTEL_EXPORTER_OTLP_ENDPOINT:t??a};i.env={...l,...p,...e??{}},i.otelHeadersHelper="flow-ai-obs otel-headers",(!i.hooks||typeof i.hooks!="object"||Array.isArray(i.hooks))&&(i.hooks={});let m=(d,E)=>({matcher:"",hooks:[{type:"command",command:`flow-ai-obs ${d}`,timeout:E}]}),T=["UserPromptSubmit","PreToolUse","PostToolUse","Stop"],S=i.hooks;for(let d of T){let E=Ds(S[d],m(d,ft[d]));E.length>1&&s.push(d),S[d]=E;}A__namespace.writeFileSync(r,JSON.stringify(i,null,2)+`
|
|
32
|
+
`,{encoding:"utf8",mode:384});try{A__namespace.chmodSync(r,384);}catch{}}finally{xr(n);}return {settingsPath:r,preserved:s}}function Jt(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(bt__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 xs,Rt=w(()=>{"use strict";v();gt();pe();je();xs=Yt.LOCK_STALE_MS;});function Kt(){let t=ht__namespace.default.homedir();if(process.platform==="darwin")return bt__namespace.default.join(t,"Library","Preferences",jt,Vt);if(process.platform==="win32"){let r=process.env.APPDATA??bt__namespace.default.join(t,"AppData","Roaming");return bt__namespace.default.join(r,jt,Vt)}let e=process.env.XDG_CONFIG_HOME??bt__namespace.default.join(t,".config");return bt__namespace.default.join(e,jt,Vt)}function Ge(){try{let t=A__namespace.default.readFileSync(Kt(),"utf8");return JSON.parse(t)}catch{return {}}}function Mr(t){let e=Kt();A__namespace.default.mkdirSync(bt__namespace.default.dirname(e),{recursive:true}),A__namespace.default.writeFileSync(e,JSON.stringify(t,null,2),{encoding:"utf8",mode:384});}var Ye,Xt,Br=w(()=>{"use strict";v();Ye={credentials:"credentials","token-cache":"tokenCache"};Xt=class{static isAvailable(){return !0}static hasExistingData(){try{if(!A__namespace.default.existsSync(Kt()))return !1;let e=JSON.parse(A__namespace.default.readFileSync(Kt(),"utf8"));return !!(e&&e.credentials)}catch{return !1}}async getSecret(e,r){let n=Ge(),s=Ye[r]??r,o=n[s];return o?typeof o=="string"?o:JSON.stringify(o):null}async setSecret(e,r,n){let s=Ge(),o=Ye[r]??r;if(r==="token-cache")try{s[o]=JSON.parse(n);}catch{s[o]=n;}else s[o]=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 ${Kt()}`}};});var Hr={};N(Hr,{MacOsKeyVaultProvider:()=>Ke});var Je,Ke,Wr=w(()=>{"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=w(()=>{"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,o)=>{let i=child_process.spawn("secret-tool",["store","--label",e,"service",e,"account",r]);i.on("error",o),i.on("close",l=>{l===0?s():o(new Error(`secret-tool exited with code ${l}`));}),i.stdin.write(n),i.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=w(()=>{"use strict";Xe=class{static async isAvailable(){try{return await Mt("keytar").getPassword("__flow_probe__","__flow_probe__"),!0}catch{return !1}}async getSecret(e,r){return Mt("keytar").getPassword(e,r)}async setSecret(e,r,n){await Mt("keytar").setPassword(e,r,n);}async deleteSecret(e,r){return Mt("keytar").deletePassword(e,r)}getStoragePath(){return "Windows Credential Manager"}};});async function Kr(){return process.env[f.FLOW_OBS_USE_JSON_VAULT]==="1"?new Xt:await qs()??new Xt}async function qs(){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=w(()=>{"use strict";v();Br();});var zr={};N(zr,{clearFlowCredentials:()=>zs,getConfigPath:()=>Qs,getEmailFromToken:()=>Pt,getFlowCredentials:()=>Xr,getTokenCache:()=>zt,hasCredentials:()=>to,isTokenValid:()=>Zs,saveFlowCredentials:()=>Xs,saveTokenCache:()=>et});function Ut(){return ze||(ze=Kr()),ze}async function Xr(){let e=await(await Ut()).getSecret(It,Ze);if(!e)return null;try{return JSON.parse(e)}catch{return null}}async function Xs(t){if(!t.clientId||!t.clientSecret||!t.tenant)throw new Error("clientId, clientSecret and tenant are required");await(await Ut()).setSecret(It,Ze,JSON.stringify(t));}async function zs(){let t=await Ut();await t.deleteSecret(It,Ze),await t.deleteSecret(It,Qe);}async function et(t){await(await Ut()).setSecret(It,Qe,JSON.stringify({accessToken:t.accessToken,expiresAt:t.expiresAt,lastAuthCheckAt:t.lastAuthCheckAt}));}async function zt(){let e=await(await Ut()).getSecret(It,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 zt();return t?new Date(t.expiresAt)>new Date:false}async function Pt(){let t=await zt();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 Qs(){let t=await Ut();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 to(){let t=await Xr();return !!(t&&t.clientId&&t.clientSecret&&t.tenant)}var It,Ze,Qe,ze,Zt=w(()=>{"use strict";qr();v();It=Wt.SERVICE,Ze=Wt.ACCOUNT_CREDS,Qe=Wt.ACCOUNT_TOKEN,ze=null;});function no(t){return ro.some(e=>e.test(t))}function so(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 nt(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:o}=r;return !n||!s||!o?null:{clientId:n,clientSecret:s,tenant:o}}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 rt(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&&no(e.hostname))throw new Error(`SSRF: private/loopback host not allowed: ${e.hostname}`);return t}async function en(){let t=nt(process.env[f.ANTHROPIC_AUTH_TOKEN]);return t?{user:await Pt().catch(()=>null)??t.clientId,tenant:t.tenant}:{user:"",tenant:""}}function oo(){return new Date().toISOString().slice(0,10)}async function io(t){let e=oo(),r=await zt();if(r?.lastAuthCheckAt!==e){u("getOrRefreshToken",`daily auth check (last: ${r?.lastAuthCheckAt??"never"})`);try{let o=await F(t);try{await et({...o,lastAuthCheckAt:e});}catch{}return u("getOrRefreshToken",`daily check passed, expires=${o.expiresAt}`),o.accessToken}catch(o){if(o instanceof mt)throw o;u("getOrRefreshToken",`daily check network error \u2014 using cache: ${o.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(o){u("getOrRefreshToken",`token cache save failed (non-fatal): ${o.message}`);}return u("getOrRefreshToken",`token refreshed, expires=${s.expiresAt}`),s.accessToken}function ao(t,e){let r=e&&e.accessToken?e.accessToken:"";return {endpoint:t.replace(/\/$/,"")+"/flow-langfuse-gateway/v1/traces",authHeader:`Bearer ${r}`}}function co(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=nt(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",o=process.env[f.LANGFUSE_BASE_URL],i=process.env[f.LANGFUSE_PUBLIC_KEY],l=process.env[f.LANGFUSE_SECRET_KEY];if(s&&o&&i&&l){let T="",S=n;r&&(T=await Pt().catch(()=>null)??r.clientId);let d={user:T??"",tenant:S??"",team:"",project:"",model:e};t.push({mode:"direct",...co(rt(o),i,l),...d}),u("resolveCredentials","direct mode active",`user=${d.user}`,`tenant=${d.tenant}`);}if(!r){if(t.length===0){let T=[];return T.authError=false,T}return t}let c;try{c=await io(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 p={user:so(c)??r.clientId,tenant:n,team:"",project:"",model:e},m=process.env[f.FLOW_TELEMETRY_GATEWAY]??Q();return t.push({mode:"gateway",...ao(rt(m),{accessToken:c}),...p}),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=ht__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 lo(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 lo("x-flow-api-key")}var ro,Zr,Qr,W=w(()=>{"use strict";Zt();gt();v();H();ro=[/^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:()=>fo,markLoggedOut:()=>po});function tr(){return bt__namespace.default.join(ht__namespace.default.homedir(),".claude","flow-obs",".logged-out")}function po(){try{let t=tr();A__namespace.default.mkdirSync(bt__namespace.default.dirname(t),{recursive:!0}),A__namespace.default.writeFileSync(t,"",{mode:384});}catch{}}function er(){try{A__namespace.default.unlinkSync(tr());}catch{}}function fo(){try{return A__namespace.default.existsSync(tr())}catch{return false}}var rr=w(()=>{"use strict";});function nr(){let t=process.env.FLOW_BASE_URL;return t&&t.trim()?t.trim():Jt("FLOW_BASE_URL")}function mo(){return Jt(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=mo(),r=nt(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 o=r.clientId;try{let i=s.accessToken.split(".");if(i.length>=2){let l=JSON.parse(Buffer.from(i[1].replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf8"));o=l.email??l.preferred_username??l.upn??l.sub??o;}}catch{}return {ok:!0,baseUrl:t,user:o,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=w(()=>{"use strict";Zt();W();Rt();v();gt();});var Se={};N(Se,{promptRaw:()=>Qt,runLogin:()=>Eo});function j(t){return typeof t=="string"?t.replace(go,""):t}function Qt(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:o=""}=e;process.stdout.write(t+o);let i=o;function l(){try{process.stdin.setRawMode(!1);}catch{}}process.once("uncaughtException",l),process.once("unhandledRejection",l);let c=p=>{if(p===""){a(),n(new Error("SIGINT"));return}if(p==="\r"||p===`
|
|
34
|
+
`){a(),process.stdout.write(`
|
|
35
|
+
`),r(i);return}if(p==="\x7F"){i.length>0&&(i=i.slice(0,-1),process.stdout.write("\b \b"));return}p.startsWith("\x1B")||(i+=p,process.stdout.write(s?"*".repeat(p.length):p));};function a(){process.stdin.setRawMode(false),process.stdin.removeListener("data",c),process.removeListener("uncaughtException",l),process.removeListener("unhandledRejection",l);}process.stdin.setRawMode(true),process.stdin.resume(),process.stdin.setEncoding("utf8"),process.stdin.on("data",c);})}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:o}=await F(t),i=tn(t);if(e)return {jwt:i,accessToken:s,expiresAt:o};J({[f.ANTHROPIC_AUTH_TOKEN]:i}),er(),await et({accessToken:s,expiresAt:o});}finally{n===void 0?delete process.env.FLOW_BASE_URL:process.env.FLOW_BASE_URL=n;}}async function ho(t=false){try{let e=(await Qt(U(" ? ")+"Client ID: ")).trim(),r=(await Qt(U(" ? ")+"Client Secret: ",{masked:!0})).trim(),n=(await Qt(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:
|
|
54
|
-
|
|
55
|
-
`)),0}catch(
|
|
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 Eo(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 o=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:o}}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(o){return process.stderr.write(I(` \u2717 Authentication failed: ${j(o.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
|
|
66
|
-
`),130;if(
|
|
65
|
+
`);let o;try{o=await Qt(U(" ? ")+"Re-authenticate? (y/N): ");}catch(i){if(i.message==="SIGINT")return process.stdout.write(`
|
|
66
|
+
`),130;if(i.message==="NOT_A_TTY")return process.stdout.write(k(` \u2713 Using existing credentials.
|
|
67
67
|
|
|
68
|
-
`)),0;throw
|
|
68
|
+
`)),0;throw i}if(o.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
|
|
79
|
-
`),130;if(
|
|
78
|
+
`));}try{return await ho(r)}catch(o){if(o.message==="SIGINT")return process.stdout.write(`
|
|
79
|
+
`),130;if(o.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
|
|
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 o}}var go,Te=w(()=>{"use strict";Zt();rr();gt();W();Rt();v();dt();de();sr();go=/[\x00-\x08\x0B-\x1F\x7F]|\x1b\[[0-9;]*[a-zA-Z]/g;});var ln={};N(ln,{normalizeCustomUrl:()=>cn,runInit:()=>_o,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 wo(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 So(){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 o=/^https?:\/\//i.test(t.trim())?t.trim().replace(/\\/g,"/"):`https://${t.trim().replace(/\\/g,"/")}`,i;try{i=new URL(o);}catch{throw new Error(`Invalid URL: ${t}`)}if(i.protocol!=="https:")throw new Error(`Custom URL must use HTTPS: ${t}`);if(i.pathname!=="/"&&i.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(i.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(i.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(i.username||i.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(!i.hostname.includes("."))throw new Error(`Invalid domain: ${i.hostname}. Expected format: tenant.example.com`);let l=`${i.protocol}//${i.host}`,c=process.env[f.FLOW_OBS_ALLOW_HTTP];try{delete process.env[f.FLOW_OBS_ALLOW_HTTP],rt(l);}finally{c!==void 0&&(process.env[f.FLOW_OBS_ALLOW_HTTP]=c);}return l}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],rt(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
|
-
flow-ai-obs init
|
|
103
|
-
`))),process.stdout.write(f(` Configuring your development environment:
|
|
100
|
+
`)),new Error("Too many invalid URL attempts")}throw new Error("Too many invalid URL attempts")}async function To(t,e,r){let n=ar()[f.FLOW_USER_EMAIL]??null,s=ge(),o=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 i(a){return a.trim()}function l(a){if(/\s/.test(a))return "Email must not contain spaces";if((a.match(/@/g)??[]).length!==1)return "Email must contain exactly one @";let p=a.indexOf("@");if(p<=0)return "Email must contain a local part before @";let m=a.slice(p+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 c(){for(let a=1;a<=3;a++)try{let p=await Pe(" Enter your corporate email (e.g., user@company.com)"),m=i(p),T=l(m);if(T)throw new Error(T);return m}catch(p){if(process.stderr.write(R(` \u2717 ${p.message}
|
|
104
101
|
|
|
105
|
-
`)),process.
|
|
106
|
-
`)),process.stdout.write(f(` [2/4] Flow Environment Setup Configure Flow URLs and LLM routing
|
|
107
|
-
`)),process.stdout.write(f(` [3/4] Authentication Authenticate with Flow
|
|
108
|
-
`)),process.stdout.write(f(` [4/4] Observability OpenTelemetry metrics, logs and trace hooks
|
|
109
|
-
`)),Se(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.
|
|
102
|
+
`)),a===3)throw process.stderr.write(I(` Too many invalid attempts.
|
|
111
103
|
|
|
112
|
-
`)),process.stdout.write(`
|
|
104
|
+
`)),new Error("Too many invalid email attempts")}throw new Error("Too many invalid email attempts")}if(n){if(await Ht(` Registered email: ${b(n)} \u2014 still correct?`,true))return process.stdout.write(k(` \u2713 Email: ${b(n)}
|
|
113
105
|
|
|
114
|
-
`),process.stdout.write(
|
|
106
|
+
`)),n;let p=await c();return J({[f.FLOW_USER_EMAIL]:p}),process.stdout.write(k(` \u2713 Email updated: ${p}
|
|
115
107
|
|
|
116
|
-
`)),process.stdout.write(`
|
|
108
|
+
`)),p}if(!s){process.stdout.write(R(`
|
|
109
|
+
\u26A0 Could not derive email from OS username.
|
|
110
|
+
`));let a=await c();return J({[f.FLOW_USER_EMAIL]:a}),process.stdout.write(k(` \u2713 Email saved: ${a}
|
|
117
111
|
|
|
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.
|
|
112
|
+
`)),a}if(e){if(await Ht(" Is your corporate email domain @ciandt.com?",true))return process.stdout.write(k(` \u2713 Email: ${b(o)}
|
|
121
113
|
|
|
122
|
-
`)),
|
|
123
|
-
|
|
124
|
-
`),
|
|
125
|
-
|
|
126
|
-
`)
|
|
127
|
-
|
|
114
|
+
`)),s;{let p=await c();return J({[f.FLOW_USER_EMAIL]:p}),process.stdout.write(k(` \u2713 Email saved: ${p}
|
|
115
|
+
|
|
116
|
+
`)),p}}else return process.stdout.write(k(` \u2713 Email: ${b(o)}
|
|
117
|
+
|
|
118
|
+
`)),s}function te(){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 _o(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(_&&(wo(`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
|
+
`)),So(),!r&&!t.noInteractive&&Z()){let _=te();try{s?r=await ir():_?(process.stdout.write(`
|
|
131
|
+
Current base URL: ${b(_)}
|
|
132
|
+
`),await Ht(" Keep this URL?",!0)||(r=await ir())):(process.stdout.write(`
|
|
133
|
+
`),await Ht(" 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 _=te();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 o,i=false;if(r){let _;try{_=cr(r,!0);}catch(ct){return process.stderr.write(`
|
|
141
|
+
\u2717 Invalid --custom-url: ${ct.message}
|
|
134
142
|
|
|
135
|
-
`),1}let
|
|
136
|
-
`)+
|
|
137
|
-
`)+
|
|
143
|
+
`),1}let L=te();o=_,i=!!L&&L!==_,i?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 o=te()??"https://flow.ciandt.com";let l={FLOW_BASE_URL:o,OTEL_EXPORTER_OTLP_ENDPOINT:`${o}/otel`,ANTHROPIC_BASE_URL:`${o}/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=o,process.stdout.write(k(`
|
|
142
150
|
\u2713 Flow environment ready.
|
|
143
|
-
`));let
|
|
144
|
-
`);
|
|
151
|
+
`));let c=36;for(let[_,L]of Object.entries(l))process.stdout.write(g(` ${_.padEnd(c)}`)+L+`
|
|
152
|
+
`);_e(2,n,"User Identity"),await To(!t.noInteractive,!!(r??We()),t.email),_e(3,n,"Authentication");let a=null,p=te(),m=!!p&&p!==o;if(!an()||i||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:i});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,d={...l,...a?{[f.ANTHROPIC_AUTH_TOKEN]:a.jwt}:{},...S&&!a?{[f.ANTHROPIC_AUTH_TOKEN]:S}:{}},E,Y;_e(4,n,"Observability (OpenTelemetry)"),process.stdout.write(`
|
|
160
|
+
${b("Metrics and Logs")}
|
|
161
|
+
`);let G={...tt,OTEL_EXPORTER_OTLP_ENDPOINT:l.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=ft[_];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:E,preserved:Y}=Dr(l.OTEL_EXPORTER_OTLP_ENDPOINT,d));}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: ${E}`),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
|
|
178
|
-
`);}function
|
|
179
|
+
`))),0}var un=w(()=>{"use strict";Rt();v();dt();pe();de();je();W();Ne();});var fn={};N(fn,{runStatus:()=>Oo});function dn(t){return !t||t.length<=8?"****":t.slice(0,4)+"****...****"+t.slice(-4)}function yo(t){process.stdout.write(` ${k("\u2713")} ${t}
|
|
180
|
+
`);}function lr(t){process.stdout.write(` ${R("\u26A0")} ${t}
|
|
181
|
+
`);}function Nt(t){process.stdout.write(` ${k("\u2713")} ${t}
|
|
182
|
+
`);}function ee(t){process.stdout.write(` ${R("\u26A0")} ${t}
|
|
183
|
+
`);}function re(t){process.stdout.write(` ${I("\u2717")} ${t}
|
|
184
|
+
`);}function st(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 Oo(){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?(yo("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 d=A__namespace.readFileSync(x(),"utf8");n=JSON.parse(d),r=n.env||{};}catch{}let s=e.filter(d=>!r[d]),o=s.length===0;dr("LLM Proxy",!o),o?(Nt("Flow LLM Proxy configured"),st(`Endpoint: ${r.ANTHROPIC_BASE_URL}`),st(`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
|
+
`),ee(`${s.length} proxy var(s) missing from settings.json`),s.forEach(d=>re(`Missing: ${d}`))),ye();for(let d of e){let E=r[d]??I("(missing)");process.stdout.write(g(` ${d.padEnd(36)}`)+E+`
|
|
200
|
+
`);}ur("Observability configuration (OpenTelemetry)");let i=Object.keys(tt).filter(d=>!r[d]);dr("Metrics and Logs",i.length>0),i.length===0?(Nt("All OTEL env vars present in settings.json"),st(`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
|
+
`),ee(`${i.length} OTEL var(s) missing from settings.json`),i.forEach(d=>re(`Missing: ${d}`))),ye();for(let d of Object.keys(tt)){let E=r[d]??I("(missing)");process.stdout.write(g(` ${d.padEnd(36)}`)+E+`
|
|
204
|
+
`);}let l=n.hooks??{},c=["UserPromptSubmit","PreToolUse","PostToolUse","Stop"],a=c.every(d=>{let E=l[d];return Array.isArray(E)?E.some(Y=>{let G=Y;return Array.isArray(G?.hooks)&&G.hooks.some(z=>z?.command?.startsWith(Yt.CLI))}):false});dr("Tracing",!a),a?Nt("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
|
+
`),ee("Hooks NOT registered."));for(let d of c){let E=ft[d];process.stdout.write(g(` ${d.padEnd(18)}`)+`\u2192 flow-ai-obs ${d} (timeout: ${E}s)
|
|
208
|
+
`);}ye();let p=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(p)if(m&&T&&S){let d=await K();for(let E of d)E.mode==="direct"&&(Nt("FLOW_TELEMETRY=true (direct mode enabled)"),Nt("Mode: direct"),st(`Endpoint: ${E.endpoint}`),st(`PK: ${dn(T)}`),st(`SK: ${dn(S)}`));}else ee("FLOW_TELEMETRY=true but missing LANGFUSE vars:"),m||re("LANGFUSE_BASE_URL not set"),T||re("LANGFUSE_PUBLIC_KEY not set"),S||re("LANGFUSE_SECRET_KEY not set");else {let d=await K();if(d.length>0)for(let E of d)E.mode==="gateway"&&(Nt("Mode: gateway"),st(`Endpoint: ${E.endpoint}`));else d.authError?ee("Gateway mode: token refresh failed. Run `flow-ai-obs login`."):st("No active tracing destination configured.");}return ye(),0}var mn=w(()=>{"use strict";W();Rt();v();dt();sr();});var gn={};N(gn,{runOtelHeaders:()=>Ao});async function Ao(){let t=nt(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
|
|
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
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
`)
|
|
240
|
-
`),
|
|
241
|
-
`),process.exit(1);});else if(M==="
|
|
242
|
-
`),process.exit(1);});else if(M==="
|
|
243
|
-
`),process.exit(1))
|
|
244
|
-
`),process.exit(
|
|
245
|
-
`),process.exit(
|
|
212
|
+
`),1)}var hn=w(()=>{"use strict";gt();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 ne(){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 Ct=w(()=>{"use strict";});function ot(){return String(BigInt(Date.now())*1000000n)}var pr,Et,se=w(()=>{"use strict";pr=()=>crypto.randomBytes(16).toString("hex"),Et=()=>crypto.randomBytes(8).toString("hex");});function $o(t,e){let r=bt.resolve(t);if(!r.startsWith(e))throw new Error(`Path traversal detected: ${t}`);return r}function fr(t){if(!No.test(t))throw new Error(`Invalid session ID: ${t}`);return $o(bt.join(ht.tmpdir(),`flow-obs-${t}.json`),Co)}function $t(t){let e=fr(t);if(!A.existsSync(e))return null;try{return JSON.parse(A.readFileSync(e,"utf8"))}catch{return null}}function Ft(t,e){A.writeFileSync(fr(t),JSON.stringify(e),{encoding:"utf8",mode:384});}function mr(t){try{A.unlinkSync(fr(t));}catch{}}var No,Co,oe=w(()=>{"use strict";No=/^[0-9a-f-]{1,64}$/i,Co=bt.normalize(ht.tmpdir())+bt.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 o=e.length-1;o>=0;o--)try{let i=JSON.parse(e[o]);if(i.type==="user")break;if(i.type==="assistant"){let c=(i.message?.content??[]).filter(p=>p.type==="text").map(p=>p.text??"").join("");c&&r.unshift(c);let a=i.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=w(()=>{"use strict";});function An(t){return t.replace(":","/")}function Ae(t,e){if(!t)return null;let r=An(t),n=[bt.join(ht.homedir(),".claude","skills",r,"SKILL.md"),bt.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||Wo.has(n.tool))?"complete":"prerequisite_required":null}function Le(t,e){if(!t)return null;let r=An(t),n=[bt.join(ht.homedir(),".claude","skills",r),bt.join(e??"",".claude","skills",r)],s=null;for(let l of n)if(A.existsSync(bt.join(l,"SKILL.md"))){s=l;break}if(!s)return null;let o=[];function i(l,c){for(let a of A.readdirSync(l,{withFileTypes:true})){if(Mo.has(a.name)||Ho.has(a.name)||Bo.has(bt.extname(a.name)))continue;let p=c?`${c}/${a.name}`:a.name;a.isDirectory()?i(bt.join(l,a.name),p):o.push(p);}}return i(s,""),o.length>0?o:null}var Mo,Bo,Ho,Wo,ke=w(()=>{"use strict";Mo=new Set([".venv","__pycache__",".git","node_modules"]),Bo=new Set([".pyc",".pyo"]),Ho=new Set(["SKILL.md",".DS_Store",".gitignore"]);Wo=new Set(["Read","Write","Edit","MultiEdit","Bash","Glob","Grep","TodoWrite","WebFetch","WebSearch","Agent","Task"]);});function Yo(t){try{let e=t.split(".")[1].replace(/-/g,"+").replace(/_/g,"/");return JSON.parse(Buffer.from(e,"base64").toString())}catch{return null}}function vn(t,e,r,n,s,o){return new Promise(i=>{let l=new URL(t),c=l.protocol==="https:",a=m=>m.replace(/[\r\n]/g,""),p=(c?ms__default.default:Ns__default.default).request({hostname:l.hostname,port:l.port||(c?443:80),path:l.pathname+l.search,method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(e),...o?{}:{Authorization:`Bearer ${a(String(r))}`},FlowTenant:a(String(n)),...s?{"x-flow-user":a(s)}:{},...o?{"x-flow-api-key":a(o)}:{}}},m=>{m.resume(),i(m.statusCode??0);});p.on("error",()=>i(0)),p.setTimeout(5e3,()=>{p.destroy(),i(0);}),p.write(e),p.end();})}async function wt(t,e={}){try{let r=ge(),n=rn(),s=nt(process.env[f.ANTHROPIC_AUTH_TOKEN]);if(n){let S=JSON.stringify({action:t,booster:kt().BOOSTER,metadata:e,success:!0,tenant:"",timestamp:new Date().toISOString(),os:process.platform,user:{email:r||"",id:"",name:r||""}}),d=rt(kt().API_URL),E=await vn(d,S,"","",r,n);u("metrics.logEvent",`action=${t} status=${E} x-flow-user=${r?"[REDACTED]":"omitted"} x-flow-api-key=[REDACTED]`);return}if(!s)return;let o,i=new Promise((S,d)=>{o=setTimeout(()=>d(new Error("getToken timeout")),4e3),o.unref();}),{accessToken:l}=await Promise.race([F(s),i]);clearTimeout(o);let c=Yo(l);if(!c)return;let a=c.tenant||s.tenant,p=JSON.stringify({action:t,booster:kt().BOOSTER,metadata:e,success:!0,tenant:a,timestamp:new Date().toISOString(),os:process.platform,user:{email:c.email||"",id:c.sub||"",name:c.name||c.email||""}}),m=rt(kt().API_URL),T=await vn(m,p,l,a,r,n);u("metrics.logEvent",`action=${t} status=${T} x-flow-user=${r?"[REDACTED]":"omitted"} x-flow-api-key=${n?"[REDACTED]":"omitted"}`);}catch(r){u("metrics.logEvent",`silenced error: ${r.message}`);}}var ve=w(()=>{"use strict";v();gt();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]&&!Jt(f.FLOW_USER_EMAIL)&&Pt().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",o=t.prompt||"",i=t.cwd||"",l=_n(t.transcript_path)||pr(),c=Ln(o),a=c?Ae(c,i):null,p=c?Le(c,i):null;Ft(s,{traceId:pr(),spanId:Et(),startNs:ot(),sessionId:s,prompt:o,cwd:i,traceName:l,transcriptPath:t.transcript_path||"",model:process.env[f.ANTHROPIC_MODEL]||"",toolCalls:[],spans:[],pendingTool:null,slashSkill:c,skillContent:a,skillArtifacts:p}),wt("SESSION_STARTED",{traceType:c?"skill":"prompt",slashSkill:c,clientIdExpired:n}),u("UserPromptSubmit",`sid=${s}`,`traceName=${l}`,`slashSkill=${c}`),V(t);}var Go,Rn=w(()=>{"use strict";se();oe();hr();ke();Ct();H();v();W();Rt();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 bn(t){let e=t.session_id||"unknown",r=t.tool_name||"unknown",n=t.tool_input||{},s=$t(e);s&&(s.pendingTool={name:r,inputStr:q(n,B.TOOL_INPUT),startNs:ot()},Ft(e,s)),u("PreToolUse",`sid=${e}`,`tool=${r}`,`stateFound=${!!s}`),V(t);}var In=w(()=>{"use strict";se();oe();Ct();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 Un(t,e){return {resourceSpans:[{resource:{attributes:t},scopeSpans:[{scope:Jo,spans:Array.isArray(e)?e:[e]}]}]}}var Jo,O,Pn=w(()=>{"use strict";v();Jo={name:le.SCOPE_NAME,version:le.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 Cn(t,e,r,n,s){if(process.env[f.FLOW_OBS_DEBUG]!=="1")return;let o=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(Nn,o+`
|
|
220
|
+
`,{flag:"a",encoding:"utf8",mode:384}),u("sendTraces:dump",`request appendada em ${Nn}`);}catch(i){u("sendTraces:dump",`falha ao salvar: ${i.message}`);}}function Qo(t){let e=new URL(t),r=new URL(pt().GATEWAY_HEALTH);return r.hostname=e.hostname,r.port=e.port,r.protocol=e.protocol,r}function $n(t,e){return new Promise((r,n)=>{let s=t._isSSL?ms__default.default:Ns__default.default;t.headers=Object.assign({},t.headers,{Connection:"close"});let o=s.request(t,i=>{let l=[];i.on("data",c=>l.push(c)),i.on("end",()=>r({statusCode:i.statusCode??0,body:l.join("")}));});o.setTimeout(1e4,()=>{o.destroy(new Error("Request timeout"));}),o.on("error",i=>n(new Error(`Network error: ${i.message}`))),e&&o.write(e),o.end();})}async function Fn(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 o=await $n({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=${o.statusCode}`),o.statusCode>=200&&o.statusCode<300}catch{return false}}async function Re(t,e,r){let n=JSON.stringify(t),s=new URL(e),o=s.protocol==="https:",i=String(r).replace(/[\r\n]/g,""),l={"Content-Type":"application/json",Authorization:i,"Content-Length":Buffer.byteLength(n)};u("sendTraces:request",`POST ${e}`),u("sendTraces:request",`headers=${JSON.stringify({...l,Authorization:i.slice(0,20)+"\u2026"})}`),u("sendTraces:request",`body=${n.slice(0,500)}${n.length>500?"\u2026":""}`);try{let c=await $n({hostname:s.hostname,port:s.port||(o?443:80),path:s.pathname,method:"POST",headers:l,_isSSL:o},n);return u("sendTraces:response",`status=${c.statusCode}`),Cn(e,l,n,c.statusCode,c.body),c.statusCode}catch(c){return u("sendTraces:error",c.message),Cn(e,l,n,0,c.message),0}}var Nn,xn=w(()=>{"use strict";v();H();Nn=bt.join(ht.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 Mn(t){if(/[/\\]/.test(t))throw new Error(`Invalid buffer fileId: ${t}`);return bt__namespace.default.join(ht__namespace.default.tmpdir(),`${$.FILE_PREFIX}${t}.json`)}function Sr(){let t=ht__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=bt__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 ie(t){try{let e=ei(),r=Sr();if(r.length>=e){let o=r.slice(0,r.length-e+1);for(let i of o)try{A__namespace.default.unlinkSync(i);}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(Mn(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 Bn(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 o=A__namespace.default.readFileSync(s,"utf8"),i=JSON.parse(o);i&&i.fileId&&i.payload&&n.push(i);}catch{u("buffer",`skipping malformed file: ${s}`);}}return n}function Hn(t){try{A__namespace.default.unlinkSync(Mn(t)),u("buffer",`deleted fileId=${t}`);}catch{}}function Wn(){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: ${bt__namespace.default.basename(e)}`));}catch{}}var jn=w(()=>{"use strict";v();H();});async function ri(t){Wn();let e=Bn($.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?(Hn(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 Vn(t){let e=await K();if(!e.length)return e.authError&&(u("postToLangfuse","auth refresh failed \u2014 buffering trace"),ie(t)),0;let r=await Promise.all(e.map(async o=>{if(o.mode!=="gateway")return {creds:o,healthy:true};let i=await Fn(o.endpoint,o.authHeader);return {creds:o,healthy:i}})),n=r.find(o=>o.creds.mode==="gateway"&&o.healthy)?.creds??r.find(o=>o.creds.mode==="direct")?.creds;return n&&await ri(n),(await Promise.all(r.map(async({creds:o,healthy:i})=>{if(o.mode==="gateway"){if(!i)return u("postToLangfuse","gateway health check failed \u2014 buffering trace"),ie(t),0;let c=await Re(t,o.endpoint,o.authHeader);return (c===0||c>=500)&&(u("postToLangfuse",`gateway send failed (status ${c}) \u2014 buffering trace`),ie(t)),c}let l=await Re(t,o.endpoint,o.authHeader);return (l===0||l>=500)&&(u("postToLangfuse",`direct endpoint unavailable (status ${l}) \u2014 buffering trace`),ie(t)),l}))).find(o=>o!==0)??0}var Yn=w(()=>{"use strict";W();H();xn();jn();v();});var Tr=w(()=>{"use strict";Pn();Yn();});function at(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,Gn,ii,_r=w(()=>{"use strict";D="[REDACTED]",ni="[REDACTED-EMAIL]",si="[REDACTED-CPF]",oi="[REDACTED-CNPJ]",Gn="[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:()=>Gn},{re:/\+55[\s-]?\d{2}[\s-]?\d{4,5}[-\s]?\d{4}/g,replace:()=>Gn}];});async function Jn(t){let e=t.session_id||"unknown",r=t.tool_name||"unknown",n=t.tool_input||{},s=t.tool_response,o=s!==null&&typeof s=="object"?s.output??JSON.stringify(s):s??"",i=$t(e);if(!i){V(t);return}let l=ot(),c=i.pendingTool,a=c?.name===r,p=a?c.startNs:String(BigInt(l)-200000000n),m=a?c.inputStr:q(n,B.TOOL_INPUT),T=m,S=null;if(r==="Skill"){let ce=typeof n=="object"&&n!==null?n.skill||n.name||n.skillName||n.commandName||String(Object.values(n)[0]??""):String(n);S=ce?String(ce).trim():null;let lt=S?Ae(S,i.cwd):null;lt&&(T=lt,i.skillContent||(i.skillContent=lt),i.skillArtifacts||(i.skillArtifacts=Le(S,i.cwd))),S&&!i.slashSkill&&(i.slashSkill=S),u("PostToolUse","Skill tool detected",`skillName=${S}`,`contentFound=${!!lt}`);}let d=at(q(o,B.TOOL_OUTPUT)),E=/\b(error|exception|failed|failure|traceback|errno)\b/i.test(d.slice(0,500)),Y=E?"ERROR":"DEFAULT",G=Et(),z=Math.round(Number(BigInt(l)-BigInt(p))/1e6),L={Agent:"AGENT",Task:"AGENT"}[r]??"TOOL",ct=r==="Skill"&&S?S:Oe(m,60);i.toolCalls.push({tool:r,brief:ct,error:E,durationMs:z});let Dt=i.spans;Dt.push({traceId:i.traceId,spanId:G,parentSpanId:i.spanId,name:r,kind:3,startTimeUnixNano:p,endTimeUnixNano:l,attributes:St(h(O.OBS_NAME,r),h(O.OBS_TYPE,L),h(O.OBS_LEVEL,Y),h(O.OBS_INPUT,at(T)),h(O.OBS_OUTPUT,d),h("tool.name",r),h("tool.error",String(E)),r==="Skill"&&S?h("skill.name",S):null,r==="Skill"?h("skill.invocation","slash-command"):null),status:{code:E?2:1}}),i.pendingTool=null,Ft(e,i),E&&wt("TOOL_ERROR",{toolName:r}),u("PostToolUse",`sid=${e}`,`tool=${r}`,`error=${E}`,`durationMs=${z}`,`totalSpans=${Dt.length}`),V(t);}var Kn=w(()=>{"use strict";se();oe();Tr();Ct();ke();H();v();_r();ve();});function Xn(t,e,r){let n=Object.keys(qn).find(i=>(t??"").toLowerCase().includes(i));if(!n)return;let s=qn[n],o=(e*s.input+r*s.output)/1e6;return Math.round(o*1e6)/1e6}var qn,zn=w(()=>{"use strict";qn={"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=$t(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=ot(),o=await en(),i=n.toolCalls,l=n.spans;if(n.slashSkill&&!i.some(y=>y.tool==="Skill")){let y=Et(),ut=n.skillContent?n.skillContent:JSON.stringify({skill:n.slashSkill});i.push({tool:"Skill",brief:n.slashSkill,error:false,durationMs:0,synthetic:true}),l.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,ut),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 c=t.transcript_path||n.transcriptPath||"",a=gr(c);if(c&&(i.some(y=>y.tool==="Skill"&&!y.synthetic)||!!n.slashSkill)&&!a?.text){await new Promise(ut=>setTimeout(ut,500));let y=gr(c);y?.text&&(a=y);}u("Stop",`transcriptPath=${c||"(empty)"}`,`assistantOut=${a?`text=${a.text.length}chars`:"null"}`);let m=i.length,T=i.filter(y=>y.error).length,S=at(a?.text?q(a.text,B.TRACE_OUTPUT):m===0?"No tools used":i.map((y,ut)=>`${ut+1}. ${y.tool}${y.brief?` \u2192 ${y.brief}`:""}${y.error?" [ERROR]":""}`).join(`
|
|
223
|
+
`)),d=a?.inputTokens??0,E=a?.outputTokens??0,Y=i.map((y,ut)=>`${ut+1}. ${y.tool}${y.brief?` \u2192 ${y.brief}`:""}${y.error?" [ERROR]":""} (${y.durationMs}ms)`),G=!!(n.slashSkill||i.some(y=>y.tool==="Skill")),z=i.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),ct=Xn(n.model,d,E),_t=kn(n);_t==="prerequisite_required"&&a?.text&&(_t="complete"),_t==="prerequisite_required"&&(l.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 Dt=(()=>{if(!(!G||!n.prompt)){if(n.slashSkill){let y=n.prompt.replace(new RegExp(`^\\/${n.slashSkill}\\s*`,"i"),"").trim();return y?q(at(y),B.USER_INSTRUCTION):void 0}return q(at(n.prompt),B.USER_INSTRUCTION)||void 0}})(),ce=JSON.stringify({trace_type:_,..._t!==null&&{execution_status:_t},...n.slashSkill?{skill_name:n.slashSkill}:{},...n.skillArtifacts?.length&&{skill_artifacts:n.skillArtifacts},...Dt!==void 0&&{user_instruction:Dt},latency_ms:L,...d&&{tokens_input:d},...E&&{tokens_output:E},cost_usd:ct,...n.model?{model:n.model}:{},toolCount:m,errorCount:T,stopReason:r,sessionId:n.sessionId,tools:Y.length?Y:void 0}),lt=at(q(n.prompt,B.TRACE_INPUT)),ns=St(h(O.TRACE_NAME,n.traceName),h(O.TRACE_INPUT,lt),h(O.TRACE_OUTPUT,S),h(O.OBS_INPUT,lt),h(O.OBS_OUTPUT,S),h(O.TRACE_METADATA,ce),h(O.SESSION_ID,n.sessionId),h(O.USER_ID,o.user),h(O.OBS_TYPE,"GENERATION"),h(O.MODEL,n.model),d?h(O.INPUT_TOKENS,d):null,E?h(O.OUTPUT_TOKENS,E):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:_}]}}}),ss={traceId:n.traceId,spanId:n.spanId,name:n.traceName,kind:1,startTimeUnixNano:n.startNs,endTimeUnixNano:s,attributes:ns,status:{code:T>0?2:1}},os=St(h("service.name",process.env.LANGFUSE_PROJECT_NAME||"claude-code"),h("deployment.environment",process.env.LANGFUSE_ENVIRONMENT||"default")),yr=[...l,ss];u("Stop",`sid=${e}`,`totalTools=${m}`,`errorTools=${T}`,`spans=${yr.length}`,`inputTokens=${d}`,`outputTokens=${E}`,`traceOutput="${Oe(S,80)}"`);let is=await Vn(Un(os,yr));u("Stop",`POST status=${is}`,`traceId=${n.traceId}`),wt("TRACE_SENT",{latencyMs:L,totalTools:m,errorTools:T,inputTokens:d,outputTokens:E,costUsd:ct}),mr(e),V(t);}var Qn=w(()=>{"use strict";se();oe();Tr();W();zn();hr();Ct();H();ke();_r();v();ve();});var Tt,ts=w(()=>{"use strict";W();Ct();Rn();In();Kn();Qn();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 ne(),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 ne();await bn(e);}static async postToolUse(){if(!await me()){t.passthroughStdin();return}let e=await ne();await Jn(e);}static async stop(){if(!await me()){t.passthroughStdin();return}let e=await ne();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 es=w(()=>{"use strict";ts();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 ae(t,e){let r=t.indexOf(e);return r!==-1?t[r+1]:void 0}function rs(){let{bold:t,cyan:e,dim:r,green:n}=(dt(),P(Ie)),{version:s}=Bt();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}=Bt();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}=(dt(),P(Ie));process.stdout.write(s(`
|
|
243
|
+
Update available: ${t} \u2192 ${r.version}
|
|
244
|
+
`)+n(` Run: flow-ai-obs update
|
|
245
|
+
|
|
246
|
+
`));}process.exit(0);})().catch(()=>process.exit(0));else if(M==="--help"||M==="-h")rs(),process.exit(0);else if(M==="init"||M==="install")(async()=>{M==="install"&&process.stderr.write(`Warning: "install" is deprecated, use "init" instead
|
|
247
|
+
`),await(Lt(),P(At)).checkForUpdateInteractive();let{runInit:t}=(un(),P(ln)),e=process.argv.slice(3);process.exit(await t({url:ae(e,"--custom-url"),noInteractive:e.includes("--no-interactive"),email:ae(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:ae(e,"--client-id"),clientSecret:ae(e,"--client-secret"),tenant:ae(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}=Bt(),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)?(es(),P(ci)):(rs(),process.exit(0));
|