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