opencrater 1.4.5 → 1.4.7

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 CHANGED
@@ -1,15 +1,15 @@
1
1
  #!/usr/bin/env node
2
- 'use strict';var we=require('crypto'),m=require('fs'),T=require('os'),u=require('path'),child_process=require('child_process'),ye=require('readline'),ke=require('http');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 we__namespace=/*#__PURE__*/_interopNamespace(we);var m__namespace=/*#__PURE__*/_interopNamespace(m);var T__namespace=/*#__PURE__*/_interopNamespace(T);var u__namespace=/*#__PURE__*/_interopNamespace(u);var ye__namespace=/*#__PURE__*/_interopNamespace(ye);var ke__namespace=/*#__PURE__*/_interopNamespace(ke);var K=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var oe=360*60*1e3;function Oe(e=process.env){return u__namespace.join(T__namespace.homedir(),".config","opencrater")}function E(e=process.env){return u__namespace.join(Oe(e),"state.json")}function q(){return {installId:we.randomUUID(),lastShownAt:0,optOut:false,disclosureShown:false,cachedConfig:null,configFetchedAt:0,pool:[],allowedPlacements:{},sessionTopics:[],integrations:[],devToken:null,computeRouting:null,computeCards:null}}function h(e){return typeof e=="number"&&Number.isFinite(e)}var ie=new Set(["EPERM","EACCES","EBUSY","EEXIST"]);function se(e){for(let t=0;;t++)try{return {text:m__namespace.readFileSync(e,"utf8")}}catch(n){let o=n.code??"";if(!(o==="ENOENT"||ie.has(o)))return {locked:true};if(t>=4)return o==="ENOENT"?{missing:true}:{locked:true};try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(t+1));}catch{}}}function Ae(e){if(typeof e!="object"||e===null)return null;let t=e;return !h(t.minIntervalSeconds)||!h(t.serveTimeoutMs)||!h(t.preloadPoolSize)||typeof t.killSwitch!="boolean"?null:{minIntervalSeconds:t.minIntervalSeconds,serveTimeoutMs:t.serveTimeoutMs,preloadPoolSize:t.preloadPoolSize,killSwitch:t.killSwitch,displayDurationSeconds:h(t.displayDurationSeconds)?t.displayDurationSeconds:25,minSdkVersion:typeof t.minSdkVersion=="string"?t.minSdkVersion:""}}function Pe(e){if(!Array.isArray(e))return [];let t=[];for(let n of e){if(typeof n!="object"||n===null)continue;let o=n,r=o.blip;if(!h(o.renderBy)||typeof r!="object"||r===null||typeof r.impressionId!="string"||typeof r.clickUrl!="string"||typeof r.sponsorLabel!="string"||typeof r.creative!="object"||r.creative===null)continue;let i=r.creative;typeof i.title!="string"||typeof i.body!="string"||t.push({blip:{impressionId:r.impressionId,...typeof r.campaignId=="string"?{campaignId:r.campaignId}:{},clickUrl:r.clickUrl,sponsorLabel:r.sponsorLabel,creative:{format:"text",title:i.title,body:i.body,...typeof i.cta=="string"?{cta:i.cta}:{}}},renderBy:o.renderBy});}return t}function Re(e){if(typeof e!="object"||e===null||Array.isArray(e))return {};let t={};for(let[n,o]of Object.entries(e)){if(!Array.isArray(o))continue;let r=o.filter(i=>typeof i=="string"&&i.length<=64);t[n]=r.slice(0,64);}return t}function Ee(e){if(!Array.isArray(e))return [];let t=[];for(let n of e){if(typeof n!="object"||n===null)continue;let o=n;if(!(typeof o.topic!="string"||!h(o.at))&&(t.push({topic:o.topic.slice(0,32),at:o.at}),t.length>=24))break}return t}function $e(e){if(!Array.isArray(e))return [];let t=[],n=new Set;for(let o of e){if(typeof o!="object"||o===null)continue;let r=o;if(typeof r.key!="string"||typeof r.package!="string"||r.key===""||r.package==="")continue;let i=`${r.package}\0${r.key}`;if(!n.has(i)&&(n.add(i),t.push({key:r.key,package:r.package}),t.length>=32))break}return t}function Te(e){if(typeof e!="object"||e===null)return null;let t=e,n={};if(typeof t.savedEnv=="object"&&t.savedEnv!==null)for(let[o,r]of Object.entries(t.savedEnv))(typeof r=="string"||r===null)&&(n[o]=r);return {active:t.active===true,savedEnv:n}}function Ne(e){if(typeof e!="object"||e===null)return null;let t=e,n=o=>h(o)&&o>=0?o:0;return {turns:n(t.turns),lastLimitAt:n(t.lastLimitAt),lastDepletedAt:n(t.lastDepletedAt),lastBackupAt:n(t.lastBackupAt)}}function _e(e){let t=e.attrTagsAt,n=e.attrTagsCwd;return !h(t)||Date.now()-t>oe||typeof n!="string"||n.length===0||n.length>64?{}:{attrTags:Array.isArray(e.attrTags)?e.attrTags.filter(r=>typeof r=="string"&&r.length<=40).slice(0,48):[],attrTagsCwd:n,attrTagsAt:t}}function Ie(e){let t=q();if(typeof e!="object"||e===null)return t;let n=e;return {installId:typeof n.installId=="string"&&n.installId.length>0?n.installId:t.installId,lastShownAt:h(n.lastShownAt)&&n.lastShownAt>=0?n.lastShownAt:0,optOut:n.optOut===true,disclosureShown:n.disclosureShown===true,cachedConfig:Ae(n.cachedConfig),allowedPlacements:Re(n.allowedPlacements),sessionTopics:Ee(n.sessionTopics),integrations:$e(n.integrations),devToken:typeof n.devToken=="string"?n.devToken:null,computeRouting:Te(n.computeRouting),computeCards:Ne(n.computeCards),configFetchedAt:h(n.configFetchedAt)&&n.configFetchedAt>=0?n.configFetchedAt:0,pool:Pe(n.pool),..._e(n)}}function g(e=process.env){let t=E(e),n=se(t);if(n.text!==void 0)try{return Ie(JSON.parse(n.text))}catch{let o=q();try{R(o,e);}catch{}return o}if(n.missing){let o=q();try{R(o,e);}catch{}return o}return q()}function R(e,t=process.env,n={}){let o=E(t),r=u__namespace.dirname(o);m__namespace.mkdirSync(r,{recursive:true});let i=se(o),a=null;if(i.text!==void 0)try{a=JSON.parse(i.text);}catch{a=null;}if(a)typeof a.lastShownAt=="number"&&a.lastShownAt>e.lastShownAt&&(e={...e,lastShownAt:a.lastShownAt}),!n.allowClearToken&&typeof a.devToken=="string"&&e.devToken==null&&(e={...e,devToken:a.devToken}),typeof a.installId=="string"&&a.installId.length>0&&a.installId!==e.installId&&(e={...e,installId:a.installId});else if(!n.allowClearToken&&e.devToken==null&&i.text===void 0&&!i.missing)return;let f=u__namespace.join(r,`.state.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`);m__namespace.writeFileSync(f,JSON.stringify(e,null,2)+`
3
- `,"utf8");for(let s=0;;s++)try{m__namespace.renameSync(f,o);return}catch(c){let l=c.code??"";if(s>=4||!ie.has(l)){try{m__namespace.rmSync(f,{force:!0});}catch{}if(s>=4)return;throw c}try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(s+1));}catch{}}}function C(e,t=process.env){let n={...g(t),...e};return R(n,t),n}var ae={claude_code:["SessionStart","Stop","SessionEnd","Notification","UserPromptSubmit","SubagentStart","SubagentStop","StopFailure","PreToolUse","PostToolUse","PostToolUseFailure","PostToolBatch","PermissionRequest","PermissionDenied","UserPromptExpansion","PreCompact","PostCompact","TaskCreated","TaskCompleted","Setup","TeammateIdle","Elicitation","ElicitationResult","ConfigChange","InstructionsLoaded","WorktreeCreate","WorktreeRemove","CwdChanged","FileChanged","MessageDisplay"],codex:["Stop","SessionStart","UserPromptSubmit","PreToolUse","PostToolUse","PermissionRequest","PreCompact","PostCompact"],openclaw:[],antigravity:["PreToolUse","PostToolUse","PreInvocation","PostInvocation","Stop"],copilot_cli:["agentStop","sessionStart","sessionEnd","notification","userPromptSubmitted","preToolUse","postToolUse","permissionRequest","errorOccurred","subagentStart","subagentStop"],grok_cli:["SessionStart","Stop","SessionEnd","Notification"],generic:["SessionStart","Stop"]};var j=["claude_code","codex","antigravity","copilot_cli","grok_cli"];function b(e){return e.includes("opencrater-hook")||/opencrater[\\/][^"']*hook\.js/.test(e)}function We(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function He(e,t){return b(e)&&new RegExp(`--package ['"]?${We(t)}['"]?`).test(e)}function X(e,t){return t?He(e,t):b(e)&&!/--package\b/.test(e)}function L(e){return /^[A-Za-z0-9@_./:-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}var U='"$HOME/.config/opencrater/runtime/node_modules/opencrater/dist/hook.js"',ce="$env:USERPROFILE\\.config\\opencrater\\runtime\\node_modules\\opencrater\\dist\\hook.js";function $(e,t,n,o){let r=`--placement ${t}`;return n&&(r+=` --key ${L(n)}`),o&&(r+=` --package ${L(o)}`),r+=` --host ${e}`,`{ if [ -f ${U} ]; then node ${U} ${r}; else npx -y -p opencrater opencrater-hook ${r}; fi; } 2>/dev/null || true`}function Me(e,t,n){if(process.platform!=="win32")return $("grok_cli",e,t,n);let o=`--placement ${e}`;t&&(o+=` --key ${t}`),n&&(o+=` --package ${n}`),o+=" --host grok_cli";let r=`${T__namespace.homedir()}\\.config\\opencrater\\runtime\\node_modules\\opencrater\\dist\\hook.js`;return `try { if (Test-Path "${r}") { node "${r}" ${o} } else { npx -y -p opencrater opencrater-hook ${o} } } catch {}`}function qe(e,t,n){if(process.platform==="win32"){let r=`--placement ${e}`;t&&(r+=` --key ${t}`),n&&(r+=` --package ${n}`),r+=" --host antigravity";let i=`${T__namespace.homedir()}\\.config\\opencrater\\runtime\\node_modules\\opencrater\\dist\\hook.js`;return `( if exist "${i}" ( node "${i}" ${r} ) else ( npx -y -p opencrater opencrater-hook ${r} ) ) >NUL 2>&1 & echo {"decision":"allow"}`}let o=`--placement ${e}`;return t&&(o+=` --key ${L(t)}`),n&&(o+=` --package ${L(n)}`),o+=" --host antigravity",`{ if [ -f ${U} ]; then node ${U} ${o}; else npx -y -p opencrater opencrater-hook ${o}; fi; } >/dev/null 2>&1; echo '{"decision":"allow"}'`}function fe(e,t,n,o){let r=`--placement ${t}`;return n&&(r+=` --key '${n}'`),o&&(r+=` --package '${o}'`),r+=` --host ${e}`,`try { if (Test-Path "${ce}") { node "${ce}" ${r} } else { npx -y -p opencrater opencrater-hook ${r} } } catch {}`}function Le(e,t,n){if(process.platform!=="win32")return $("claude_code",e,t,n);let o=`--placement ${e}`;return t&&(o+=` --key ${t}`),n&&(o+=` --package ${n}`),o+=" --host claude_code",`node "${`${T__namespace.homedir()}\\.config\\opencrater\\runtime\\node_modules\\opencrater\\dist\\hook.js`}" ${o}; exit 0`}function Y(e,t,n,o){if(e==="grok_cli")return {type:"command",command:Me(t,n,o),timeout:15};let i={type:"command",command:e==="claude_code"?Le(t,n,o):$(e,t,n,o)};return e==="codex"&&(i.commandWindows=fe(e,t,n,o)),i}function B(e,t){let n=T__namespace.homedir();switch(e){case "claude_code":{let o=t.CLAUDE_CONFIG_DIR;return o&&o.trim()!==""?o:u__namespace.join(n,".claude")}case "codex":{let o=t.CODEX_HOME;return o&&o.trim()!==""?o:u__namespace.join(n,".codex")}case "antigravity":return u__namespace.join(n,".gemini");case "copilot_cli":{let o=t.COPILOT_HOME;return o&&o.trim()!==""?o:u__namespace.join(n,".copilot")}case "grok_cli":{let o=t.GROK_HOME;return o&&o.trim()!==""?o:u__namespace.join(n,".grok")}default:return u__namespace.join(n,".opencrater-unknown")}}function N(e,t=process.env){let n=B(e,t);switch(e){case "claude_code":return u__namespace.join(n,"settings.json");case "codex":return u__namespace.join(n,"hooks.json");case "antigravity":return u__namespace.join(n,"config","hooks.json");case "copilot_cli":return u__namespace.join(n,"hooks","hooks.json");case "grok_cli":return u__namespace.join(n,"hooks","opencrater.json");default:return u__namespace.join(n,"hooks.json")}}var Ue={claude_code:["claude"],codex:["codex"],antigravity:["agy"],copilot_cli:["copilot"],grok_cli:["grok"]};function Be(e,t){if(e.length===0)return false;let n=(t.PATH??t.Path??"").split(u__namespace.delimiter).filter(Boolean),o=process.platform==="win32"?["",".exe",".cmd",".bat"]:[""];for(let r of n)for(let i of e)for(let a of o)try{if(m__namespace.existsSync(u__namespace.join(r,i+a)))return !0}catch{}return false}function Fe(e,t=process.env){try{if(m__namespace.existsSync(B(e,t)))return !0}catch{}return Be(Ue[e]??[],t)}function Q(e=process.env){return j.filter(t=>Fe(t,e))}function A(e){let t;try{t=m__namespace.readFileSync(e,"utf8");}catch{return {}}let n=JSON.parse(t);if(typeof n!="object"||n===null||Array.isArray(n))throw new Error(`${e} is not a JSON object`);return n}function O(e,t){let n=u__namespace.dirname(e);m__namespace.mkdirSync(n,{recursive:true});let o=u__namespace.join(n,`.${u__namespace.basename(e)}.${process.pid}.tmp`);m__namespace.writeFileSync(o,JSON.stringify(t,null,2)+`
4
- `,"utf8"),m__namespace.renameSync(o,e);}function De(e,t){return Array.isArray(e.hooks)&&e.hooks.some(n=>typeof n.command=="string"&&X(n.command,t))}function ze(e,t,n,o){let r=N(e),i=A(r),a=i.hooks&&typeof i.hooks=="object"?i.hooks:{};if(o.every(s=>{let c=Y(e,s,t,n);return (Array.isArray(a[s])?a[s]:[]).some(l=>Array.isArray(l.hooks)&&l.hooks.some(d=>d.command===c.command&&d.commandWindows===c.commandWindows))}))return "nochange";for(let s of o){let l=(Array.isArray(a[s])?a[s]:[]).filter(p=>!De(p,n)),d=e==="grok_cli"?{hooks:[Y(e,s,t,n)]}:{matcher:"",hooks:[Y(e,s,t,n)]};l.push(d),a[s]=l;}return i.hooks=a,O(r,i),"wrote"}var Ge=15;function Je(e){return e?`opencrater-${e}`:"opencrater-compute"}function Ke(e,t){if(!e||typeof e!="object")return false;for(let n of Object.values(e))for(let o of Array.isArray(n)?n:[])if(Array.isArray(o.hooks)&&o.hooks.some(r=>typeof r.command=="string"&&X(r.command,t)))return true;return false}function de(e){try{let t=u__namespace.join(B("antigravity",e),"settings.json"),n;try{n=A(t);}catch{return}let o=!1,r=n.hooks;if(r&&typeof r=="object"&&!Array.isArray(r)){let i=r;for(let a of Object.keys(i)){let f=Array.isArray(i[a])?i[a]:[],s=f.filter(c=>!(Array.isArray(c.hooks)&&c.hooks.some(l=>typeof l.command=="string"&&b(l.command))));s.length!==f.length&&(o=!0,s.length>0?i[a]=s:delete i[a]);}Object.keys(i).length===0&&(delete n.hooks,o=!0);}n["json-hooks-enabled"]===!0&&(delete n["json-hooks-enabled"],o=!0),o&&O(t,n);}catch{}}function Ve(e,t,n){let o=N("antigravity"),r=A(o),i=Je(t),a={};for(let c of n)a[c]=[{hooks:[{type:"command",command:qe(c,e,t),timeout:Ge}]}];let f=JSON.stringify(a),s=false;JSON.stringify(r[i]??null)!==f&&(r[i]=a,s=true);for(let c of Object.keys(r))c!==i&&Ke(r[c],t)&&(delete r[c],s=true);return de(process.env),s?(O(o,r),"wrote"):"nochange"}var le=12;function Ye(e,t){return [e.bash,e.powershell,e.command].some(n=>typeof n=="string"&&X(n,t))}function Xe(e,t,n,o){let r=N(e),i=A(r);typeof i.version!="number"&&(i.version=1);let a=i.hooks&&typeof i.hooks=="object"?i.hooks:{};if(o.every(s=>{let c=$(e,s,t,n);return (Array.isArray(a[s])?a[s]:[]).some(l=>l.bash===c&&l.timeoutSec===le)}))return "nochange";for(let s of o){let l=(Array.isArray(a[s])?a[s]:[]).filter(d=>!Ye(d,n));l.push({type:"command",bash:$(e,s,t,n),powershell:fe(e,s,t,n),timeoutSec:le}),a[s]=l;}return i.hooks=a,O(r,i),"wrote"}function F(e){return [...ae[e]]}function Qe(e){let t=e;for(let n of ["claude","cursor"]){if(new RegExp(`^\\s*\\[compat\\.${n}\\]`,"m").test(t))continue;let o=t.length===0?"":t.endsWith(`
2
+ 'use strict';var ve=require('crypto'),m=require('fs'),T=require('os'),u=require('path'),child_process=require('child_process'),we=require('readline'),be=require('http');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 ve__namespace=/*#__PURE__*/_interopNamespace(ve);var m__namespace=/*#__PURE__*/_interopNamespace(m);var T__namespace=/*#__PURE__*/_interopNamespace(T);var u__namespace=/*#__PURE__*/_interopNamespace(u);var we__namespace=/*#__PURE__*/_interopNamespace(we);var be__namespace=/*#__PURE__*/_interopNamespace(be);var V=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var re=360*60*1e3;function Pe(e=process.env){return u__namespace.join(T__namespace.homedir(),".config","opencrater")}function E(e=process.env){return u__namespace.join(Pe(e),"state.json")}function q(){return {installId:ve.randomUUID(),lastShownAt:0,optOut:false,disclosureShown:false,cachedConfig:null,configFetchedAt:0,pool:[],allowedPlacements:{},sessionTopics:[],integrations:[],devToken:null,computeRouting:null,computeCards:null}}function h(e){return typeof e=="number"&&Number.isFinite(e)}var se=new Set(["EPERM","EACCES","EBUSY","EEXIST"]);function ae(e){for(let t=0;;t++)try{return {text:m__namespace.readFileSync(e,"utf8")}}catch(n){let o=n.code??"";if(!(o==="ENOENT"||se.has(o)))return {locked:true};if(t>=4)return o==="ENOENT"?{missing:true}:{locked:true};try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(t+1));}catch{}}}function Re(e){if(typeof e!="object"||e===null)return null;let t=e;return !h(t.minIntervalSeconds)||!h(t.serveTimeoutMs)||!h(t.preloadPoolSize)||typeof t.killSwitch!="boolean"?null:{minIntervalSeconds:t.minIntervalSeconds,serveTimeoutMs:t.serveTimeoutMs,preloadPoolSize:t.preloadPoolSize,killSwitch:t.killSwitch,displayDurationSeconds:h(t.displayDurationSeconds)?t.displayDurationSeconds:25,minSdkVersion:typeof t.minSdkVersion=="string"?t.minSdkVersion:""}}function Ee(e){if(!Array.isArray(e))return [];let t=[];for(let n of e){if(typeof n!="object"||n===null)continue;let o=n,r=o.blip;if(!h(o.renderBy)||typeof r!="object"||r===null||typeof r.impressionId!="string"||typeof r.clickUrl!="string"||typeof r.sponsorLabel!="string"||typeof r.creative!="object"||r.creative===null)continue;let i=r.creative;typeof i.title!="string"||typeof i.body!="string"||t.push({blip:{impressionId:r.impressionId,...typeof r.campaignId=="string"?{campaignId:r.campaignId}:{},clickUrl:r.clickUrl,sponsorLabel:r.sponsorLabel,creative:{format:"text",title:i.title,body:i.body,...typeof i.cta=="string"?{cta:i.cta}:{}}},renderBy:o.renderBy});}return t}function $e(e){if(typeof e!="object"||e===null||Array.isArray(e))return {};let t={};for(let[n,o]of Object.entries(e)){if(!Array.isArray(o))continue;let r=o.filter(i=>typeof i=="string"&&i.length<=64);t[n]=r.slice(0,64);}return t}function Te(e){if(!Array.isArray(e))return [];let t=[];for(let n of e){if(typeof n!="object"||n===null)continue;let o=n;if(!(typeof o.topic!="string"||!h(o.at))&&(t.push({topic:o.topic.slice(0,32),at:o.at}),t.length>=24))break}return t}function Ie(e){if(!Array.isArray(e))return [];let t=[],n=new Set;for(let o of e){if(typeof o!="object"||o===null)continue;let r=o;if(typeof r.key!="string"||typeof r.package!="string"||r.key===""||r.package==="")continue;let i=`${r.package}\0${r.key}`;if(!n.has(i)&&(n.add(i),t.push({key:r.key,package:r.package}),t.length>=32))break}return t}function Ne(e){if(typeof e!="object"||e===null)return null;let t=e,n={};if(typeof t.savedEnv=="object"&&t.savedEnv!==null)for(let[o,r]of Object.entries(t.savedEnv))(typeof r=="string"||r===null)&&(n[o]=r);return {active:t.active===true,savedEnv:n}}function _e(e){if(typeof e!="object"||e===null)return null;let t=e,n=o=>h(o)&&o>=0?o:0;return {turns:n(t.turns),lastLimitAt:n(t.lastLimitAt),lastDepletedAt:n(t.lastDepletedAt),lastBackupAt:n(t.lastBackupAt)}}function We(e){let t=e.attrTagsAt,n=e.attrTagsCwd;return !h(t)||Date.now()-t>re||typeof n!="string"||n.length===0||n.length>64?{}:{attrTags:Array.isArray(e.attrTags)?e.attrTags.filter(r=>typeof r=="string"&&r.length<=40).slice(0,48):[],attrTagsCwd:n,attrTagsAt:t}}function Me(e){let t=q();if(typeof e!="object"||e===null)return t;let n=e;return {installId:typeof n.installId=="string"&&n.installId.length>0?n.installId:t.installId,lastShownAt:h(n.lastShownAt)&&n.lastShownAt>=0?n.lastShownAt:0,optOut:n.optOut===true,disclosureShown:n.disclosureShown===true,cachedConfig:Re(n.cachedConfig),allowedPlacements:$e(n.allowedPlacements),sessionTopics:Te(n.sessionTopics),integrations:Ie(n.integrations),devToken:typeof n.devToken=="string"?n.devToken:null,computeRouting:Ne(n.computeRouting),computeCards:_e(n.computeCards),configFetchedAt:h(n.configFetchedAt)&&n.configFetchedAt>=0?n.configFetchedAt:0,pool:Ee(n.pool),...We(n)}}function g(e=process.env){let t=E(e),n=ae(t);if(n.text!==void 0)try{return Me(JSON.parse(n.text))}catch{let o=q();try{R(o,e);}catch{}return o}if(n.missing){let o=q();try{R(o,e);}catch{}return o}return q()}function R(e,t=process.env,n={}){let o=E(t),r=u__namespace.dirname(o);m__namespace.mkdirSync(r,{recursive:true});let i=ae(o),a=null;if(i.text!==void 0)try{a=JSON.parse(i.text);}catch{a=null;}if(a)typeof a.lastShownAt=="number"&&a.lastShownAt>e.lastShownAt&&(e={...e,lastShownAt:a.lastShownAt}),!n.allowClearToken&&typeof a.devToken=="string"&&e.devToken==null&&(e={...e,devToken:a.devToken}),typeof a.installId=="string"&&a.installId.length>0&&a.installId!==e.installId&&(e={...e,installId:a.installId});else if(!n.allowClearToken&&e.devToken==null&&i.text===void 0&&!i.missing)return;let f=u__namespace.join(r,`.state.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`);m__namespace.writeFileSync(f,JSON.stringify(e,null,2)+`
3
+ `,"utf8");for(let s=0;;s++)try{m__namespace.renameSync(f,o);return}catch(c){let l=c.code??"";if(s>=4||!se.has(l)){try{m__namespace.rmSync(f,{force:!0});}catch{}if(s>=4)return;throw c}try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(s+1));}catch{}}}function O(e,t=process.env){let n={...g(t),...e};return R(n,t),n}var ce={claude_code:["SessionStart","Stop","SessionEnd","Notification","UserPromptSubmit","SubagentStart","SubagentStop","StopFailure","PreToolUse","PostToolUse","PostToolUseFailure","PostToolBatch","PermissionRequest","PermissionDenied","UserPromptExpansion","PreCompact","PostCompact","TaskCreated","TaskCompleted","Setup","TeammateIdle","Elicitation","ElicitationResult","ConfigChange","InstructionsLoaded","WorktreeCreate","WorktreeRemove","CwdChanged","FileChanged","MessageDisplay"],codex:["Stop","SessionStart","UserPromptSubmit","PreToolUse","PostToolUse","PermissionRequest","PreCompact","PostCompact"],openclaw:[],antigravity:["PreToolUse","PostToolUse","PreInvocation","PostInvocation","Stop"],copilot_cli:["agentStop","sessionStart","sessionEnd","notification","userPromptSubmitted","preToolUse","postToolUse","permissionRequest","errorOccurred","subagentStart","subagentStop"],grok_cli:["SessionStart","Stop","SessionEnd","Notification"],generic:["SessionStart","Stop"]};var x=["claude_code","codex","antigravity","copilot_cli","grok_cli"];function b(e){return e.includes("opencrater-hook")||/opencrater[\\/][^"']*hook\.js/.test(e)}function He(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function qe(e,t){return b(e)&&new RegExp(`--package ['"]?${He(t)}['"]?`).test(e)}function Q(e,t){return t?qe(e,t):b(e)&&!/--package\b/.test(e)}function L(e){return /^[A-Za-z0-9@_./:-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}var U='"$HOME/.config/opencrater/runtime/node_modules/opencrater/dist/hook.js"',le="$env:USERPROFILE\\.config\\opencrater\\runtime\\node_modules\\opencrater\\dist\\hook.js";function $(e,t,n,o){let r=`--placement ${t}`;return n&&(r+=` --key ${L(n)}`),o&&(r+=` --package ${L(o)}`),r+=` --host ${e}`,`{ if [ -f ${U} ]; then node ${U} ${r}; else npx -y -p opencrater opencrater-hook ${r}; fi; } 2>/dev/null || true`}function Le(e,t,n){if(process.platform!=="win32")return $("grok_cli",e,t,n);let o=`--placement ${e}`;t&&(o+=` --key ${t}`),n&&(o+=` --package ${n}`),o+=" --host grok_cli";let r=`${T__namespace.homedir()}\\.config\\opencrater\\runtime\\node_modules\\opencrater\\dist\\hook.js`;return `try { if (Test-Path "${r}") { node "${r}" ${o} } else { npx -y -p opencrater opencrater-hook ${o} } } catch {}`}function Ue(e,t,n){if(process.platform==="win32"){let r=`--placement ${e}`;t&&(r+=` --key ${t}`),n&&(r+=` --package ${n}`),r+=" --host antigravity";let i=`${T__namespace.homedir()}\\.config\\opencrater\\runtime\\node_modules\\opencrater\\dist\\hook.js`;return `( if exist "${i}" ( node "${i}" ${r} ) else ( npx -y -p opencrater opencrater-hook ${r} ) ) >NUL 2>&1 & echo {"decision":"allow"}`}let o=`--placement ${e}`;return t&&(o+=` --key ${L(t)}`),n&&(o+=` --package ${L(n)}`),o+=" --host antigravity",`{ if [ -f ${U} ]; then node ${U} ${o}; else npx -y -p opencrater opencrater-hook ${o}; fi; } >/dev/null 2>&1; echo '{"decision":"allow"}'`}function de(e,t,n,o){let r=`--placement ${t}`;return n&&(r+=` --key '${n}'`),o&&(r+=` --package '${o}'`),r+=` --host ${e}`,`try { if (Test-Path "${le}") { node "${le}" ${r} } else { npx -y -p opencrater opencrater-hook ${r} } } catch {}`}function Be(e,t,n){if(process.platform!=="win32")return $("claude_code",e,t,n);let o=`--placement ${e}`;return t&&(o+=` --key ${t}`),n&&(o+=` --package ${n}`),o+=" --host claude_code",`node "${`${T__namespace.homedir()}\\.config\\opencrater\\runtime\\node_modules\\opencrater\\dist\\hook.js`}" ${o}; exit 0`}function X(e,t,n,o){if(e==="grok_cli")return {type:"command",command:Le(t,n,o),timeout:15};let i={type:"command",command:e==="claude_code"?Be(t,n,o):$(e,t,n,o)};return e==="codex"&&(i.commandWindows=de(e,t,n,o)),i}function B(e,t){let n=T__namespace.homedir();switch(e){case "claude_code":{let o=t.CLAUDE_CONFIG_DIR;return o&&o.trim()!==""?o:u__namespace.join(n,".claude")}case "codex":{let o=t.CODEX_HOME;return o&&o.trim()!==""?o:u__namespace.join(n,".codex")}case "antigravity":return u__namespace.join(n,".gemini");case "copilot_cli":{let o=t.COPILOT_HOME;return o&&o.trim()!==""?o:u__namespace.join(n,".copilot")}case "grok_cli":{let o=t.GROK_HOME;return o&&o.trim()!==""?o:u__namespace.join(n,".grok")}default:return u__namespace.join(n,".opencrater-unknown")}}function I(e,t=process.env){let n=B(e,t);switch(e){case "claude_code":return u__namespace.join(n,"settings.json");case "codex":return u__namespace.join(n,"hooks.json");case "antigravity":return u__namespace.join(n,"config","hooks.json");case "copilot_cli":return u__namespace.join(n,"hooks","hooks.json");case "grok_cli":return u__namespace.join(n,"hooks","opencrater.json");default:return u__namespace.join(n,"hooks.json")}}var Fe={claude_code:["claude"],codex:["codex"],antigravity:["agy"],copilot_cli:["copilot"],grok_cli:["grok"]};function De(e,t){if(e.length===0)return false;let n=(t.PATH??t.Path??"").split(u__namespace.delimiter).filter(Boolean),o=process.platform==="win32"?["",".exe",".cmd",".bat"]:[""];for(let r of n)for(let i of e)for(let a of o)try{if(m__namespace.existsSync(u__namespace.join(r,i+a)))return !0}catch{}return false}function ze(e,t=process.env){try{if(m__namespace.existsSync(B(e,t)))return !0}catch{}return De(Fe[e]??[],t)}function Z(e=process.env){return x.filter(t=>ze(t,e))}function P(e){let t;try{t=m__namespace.readFileSync(e,"utf8");}catch{return {}}let n=JSON.parse(t);if(typeof n!="object"||n===null||Array.isArray(n))throw new Error(`${e} is not a JSON object`);return n}function A(e,t){let n=u__namespace.dirname(e);m__namespace.mkdirSync(n,{recursive:true});let o=u__namespace.join(n,`.${u__namespace.basename(e)}.${process.pid}.tmp`);m__namespace.writeFileSync(o,JSON.stringify(t,null,2)+`
4
+ `,"utf8"),m__namespace.renameSync(o,e);}function Ge(e,t){return Array.isArray(e.hooks)&&e.hooks.some(n=>typeof n.command=="string"&&Q(n.command,t))}function Je(e,t,n,o){let r=I(e),i=P(r),a=i.hooks&&typeof i.hooks=="object"?i.hooks:{};if(o.every(s=>{let c=X(e,s,t,n);return (Array.isArray(a[s])?a[s]:[]).some(l=>Array.isArray(l.hooks)&&l.hooks.some(d=>d.command===c.command&&d.commandWindows===c.commandWindows))}))return "nochange";for(let s of o){let l=(Array.isArray(a[s])?a[s]:[]).filter(p=>!Ge(p,n)),d=e==="grok_cli"?{hooks:[X(e,s,t,n)]}:{matcher:"",hooks:[X(e,s,t,n)]};l.push(d),a[s]=l;}return i.hooks=a,A(r,i),"wrote"}var Ke=15;function Ve(e){return e?`opencrater-${e}`:"opencrater-compute"}function Ye(e,t){if(!e||typeof e!="object")return false;for(let n of Object.values(e))for(let o of Array.isArray(n)?n:[])if(Array.isArray(o.hooks)&&o.hooks.some(r=>typeof r.command=="string"&&Q(r.command,t)))return true;return false}function ue(e){try{let t=u__namespace.join(B("antigravity",e),"settings.json"),n;try{n=P(t);}catch{return}let o=!1,r=n.hooks;if(r&&typeof r=="object"&&!Array.isArray(r)){let i=r;for(let a of Object.keys(i)){let f=Array.isArray(i[a])?i[a]:[],s=f.filter(c=>!(Array.isArray(c.hooks)&&c.hooks.some(l=>typeof l.command=="string"&&b(l.command))));s.length!==f.length&&(o=!0,s.length>0?i[a]=s:delete i[a]);}Object.keys(i).length===0&&(delete n.hooks,o=!0);}n["json-hooks-enabled"]===!0&&(delete n["json-hooks-enabled"],o=!0),o&&A(t,n);}catch{}}function Xe(e,t,n){let o=I("antigravity"),r=P(o),i=Ve(t),a={};for(let c of n)a[c]=[{hooks:[{type:"command",command:Ue(c,e,t),timeout:Ke}]}];let f=JSON.stringify(a),s=false;JSON.stringify(r[i]??null)!==f&&(r[i]=a,s=true);for(let c of Object.keys(r))c!==i&&Ye(r[c],t)&&(delete r[c],s=true);return ue(process.env),s?(A(o,r),"wrote"):"nochange"}var fe=12;function Qe(e,t){return [e.bash,e.powershell,e.command].some(n=>typeof n=="string"&&Q(n,t))}function Ze(e,t,n,o){let r=I(e),i=P(r);typeof i.version!="number"&&(i.version=1);let a=i.hooks&&typeof i.hooks=="object"?i.hooks:{};if(o.every(s=>{let c=$(e,s,t,n);return (Array.isArray(a[s])?a[s]:[]).some(l=>l.bash===c&&l.timeoutSec===fe)}))return "nochange";for(let s of o){let l=(Array.isArray(a[s])?a[s]:[]).filter(d=>!Qe(d,n));l.push({type:"command",bash:$(e,s,t,n),powershell:de(e,s,t,n),timeoutSec:fe}),a[s]=l;}return i.hooks=a,A(r,i),"wrote"}function F(e){return [...ce[e]]}function en(e){let t=e;for(let n of ["claude","cursor"]){if(new RegExp(`^\\s*\\[compat\\.${n}\\]`,"m").test(t))continue;let o=t.length===0?"":t.endsWith(`
5
5
  `)?`
6
6
  `:`
7
7
 
8
8
  `;t+=`${o}[compat.${n}]
9
9
  hooks = false
10
- `;}return t}function Ze(e){try{let t=u__namespace.join(B("grok_cli",e),"config.toml"),n="";try{n=m__namespace.readFileSync(t,"utf8");}catch{}let o=Qe(n);if(o===n)return;m__namespace.mkdirSync(u__namespace.dirname(t),{recursive:!0}),m__namespace.writeFileSync(t,o,"utf8");}catch{}}function D(e,t,n){let o=F(e);return o.length===0?"nochange":(e==="grok_cli"&&Ze(process.env),e==="copilot_cli"?Xe(e,t,n,o):e==="antigravity"?Ve(t,n,o):ze(e,t,n,o))}function _(e,t,n=process.env){return Q(n).map(o=>{try{let r=D(o,e,t);return {host:o,status:r,events:F(o)}}catch(r){return {host:o,status:"error",events:[],error:r.message}}})}function Z(e=process.env){let t=[];for(let n of j){let o;try{o=A(N(n,e));}catch{continue}if(n==="antigravity"){for(let i of Object.values(o))if(!(!i||typeof i!="object"))for(let[a,f]of Object.entries(i))for(let s of Array.isArray(f)?f:[]){let c=s,l=Array.isArray(c.hooks)?c.hooks.find(d=>typeof d.command=="string"&&b(d.command))?.command:void 0;l&&t.push({host:n,event:a,command:l});}continue}let r=o.hooks;if(!(!r||typeof r!="object"))for(let[i,a]of Object.entries(r))for(let f of Array.isArray(a)?a:[]){let s=f,c=Array.isArray(s.hooks)?s.hooks.find(p=>typeof p.command=="string"&&b(p.command))?.command:void 0,l=[s.bash,s.command,s.powershell].find(p=>typeof p=="string"&&b(p)),d=c??l;d&&t.push({host:n,event:i,command:d});}}return t}function ue(e=process.env){let t=0;for(let n of j){let o=N(n,e),r;try{r=A(o);}catch{continue}if(n==="antigravity"){let s=false;for(let c of Object.keys(r)){let l=r[c];if(!l||typeof l!="object"||Array.isArray(l))continue;let d=l;for(let p of Object.keys(d)){let k=Array.isArray(d[p])?d[p]:[],w=k.filter(je=>{let ee=je,ne=Array.isArray(ee.hooks)&&ee.hooks.some(te=>typeof te.command=="string"&&b(te.command));return ne&&t++,!ne});w.length!==k.length&&(s=true,w.length>0?d[p]=w:delete d[p]);}Object.keys(d).length===0&&(delete r[c],s=true);}if(s)try{Object.keys(r).length===0?m__namespace.rmSync(o,{force:!0}):O(o,r);}catch{}de(e);continue}let i=r.hooks;if(!i||typeof i!="object")continue;let a=i,f=false;for(let s of Object.keys(a)){let c=Array.isArray(a[s])?a[s]:[],l=c.filter(d=>{let p=d,k=Array.isArray(p.hooks)&&p.hooks.some(w=>typeof w.command=="string"&&b(w.command))||[p.bash,p.powershell,p.command].some(w=>typeof w=="string"&&b(w));return k&&t++,!k});l.length!==c.length&&(f=true,l.length>0?a[s]=l:delete a[s]);}if(f)try{let s=Object.keys(r).filter(l=>l!=="version"&&l!=="hooks"),c=n==="copilot_cli"||n==="codex";Object.keys(a).length===0&&s.length===0&&c?m__namespace.rmSync(o,{force:!0}):O(o,r);}catch{}}return t}var I="1.4.5";var en="https://api.opencrater.to";function P(e,t=process.env){let n=t.OPENCRATER_API_ORIGIN;return (e??(n&&n.trim()!==""?n:en)).replace(/\/+$/,"")}function tn(){return u__namespace.join(T__namespace.homedir(),".config","opencrater","runtime")}function on(e){return ["install","--prefix",e,"opencrater@latest","--silent","--no-audit","--no-fund"]}function z(e=tn()){if(process.env.VITEST||process.env.OPENCRATER_DISABLE_RUNTIME_PIN)return false;try{return child_process.spawnSync("npm",on(e),{stdio:"ignore",windowsHide:!0,shell:process.platform==="win32"}).status===0}catch{return false}}function be(){let e=process.env.OPENCRATER_WEB_ORIGIN;return e&&e.trim()!==""?e.replace(/\/$/,""):P().replace("//api.","//").replace(/\/$/,"")}function rn(e){try{let t=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";child_process.spawn(t,[e],{stdio:"ignore",detached:!0,shell:process.platform==="win32"}).unref();}catch{}}function W(e){return `${Math.round(e/1e3).toLocaleString()} tokens`}function sn(e){let t=e/1e3;return t>0&&t<10?`${(Math.round(t*10)/10).toFixed(1)} tokens`:`${Math.round(t).toLocaleString()} tokens`}function H(e){let t=e?.pendingMicroUsd??0;return t>0?` \xB7 +${sn(t)} pending`:""}async function M(e,t){try{let n=new URL(`${P()}/v1/dev/me`);t&&n.searchParams.set("installId",t);let o=await fetch(n,{headers:{authorization:`Bearer ${e}`}});return o.ok?await o.json():null}catch{return null}}function an(){return new Promise((e,t)=>{let n=we__namespace.randomBytes(16).toString("hex"),o,r,i=new Promise((c,l)=>{o=c,r=l;}),a=ke__namespace.createServer((c,l)=>{try{let d=new URL(c.url??"/","http://127.0.0.1");if(d.pathname==="/cb"&&d.searchParams.get("state")===n){let p=(d.searchParams.get("token")??"").trim(),k=p.startsWith("ocd_");l.writeHead(k?200:400,{"content-type":"text/html"}),l.end(`<!doctype html><meta charset="utf-8"><body style="font-family:system-ui;background:#0d1117;color:#e7e9ee;display:grid;place-items:center;height:100vh;margin:0"><div style="text-align:center"><h2>${k?"\u2713 Signed in":"Something went wrong"}</h2><p style="color:#9aa0aa">You can close this tab and return to your terminal.</p></div>`),k&&o(p);return}l.writeHead(404).end("not found");}catch{try{l.writeHead(500).end();}catch{}}}),f=setTimeout(()=>r(new Error("timeout")),18e4),s=()=>{clearTimeout(f);try{a.close();}catch{}};a.on("error",c=>{s(),t(c instanceof Error?c:new Error(String(c))),r(c instanceof Error?c:new Error(String(c)));}),a.listen(0,"127.0.0.1",()=>{let c=a.address(),l=typeof c=="object"&&c?c.port:0;if(!l){s(),t(new Error("no port"));return}let d=encodeURIComponent(`http://127.0.0.1:${l}/cb?state=${n}`);e({url:`${be()}/dev/link?callback=${d}`,token:i,cancel:s});});})}async function cn(e){let t=await M(e,g().installId);if(!t)return console.error("Couldn't verify that token \u2014 check it and try again."),1;C({devToken:e}),console.log(`
11
- \u2713 Signed in as ${t.displayName}.`),console.log(` Compute balance: ${W(t.balanceMicroUsd)}${H(t)} \xB7 tier: ${t.trustTier}`);let n=_().filter(o=>o.status!=="error").map(o=>o.host);return n.length?(console.log(` Wired into: ${n.join(", ")}`),process.stdout.write(" Pinning fast runtime (one-time, ~15s)\u2026 "),console.log(z()?"\u2713":"skipped (hooks use npx fallback)")):console.log(" No supported AI CLIs detected yet \u2014 they'll wire automatically once you install one."),console.log(" See Blips in your sessions to earn your weekly compute."),0}async function ln(){let e=null;try{e=await an();}catch{e=null;}let t=e?.url??`${be()}/dev/link`;console.log("Sign in to OpenCrater in your browser (we tried to open it):"),console.log(` ${t}
12
- `),rn(t);let n=ye__namespace.createInterface({input:process.stdin,output:process.stdout});console.log(e?"Waiting for your browser to finish\u2026 (or paste a token here and press enter)":"Generate a token on that page, then paste it here:");let o=new Promise(i=>{n.on("line",a=>{let f=a.trim();f.startsWith("ocd_")&&i(f);});}),r=null;try{let i=e?[e.token,o]:[o];r=await Promise.race(i.map(a=>a.catch(()=>""))),r||(r=await o);}finally{e?.cancel(),n.close();}return !r||!r.startsWith("ocd_")?(console.error("That doesn't look like a token (should start with ocd_)."),1):cn(r)}async function fn(){let e=g().devToken;if(!e)return console.error("Not signed in. Run: opencrater login"),1;let t=await M(e,g().installId);return t?(console.log(`Compute balance: ${W(t.balanceMicroUsd)}${H(t)}`),console.log(` signed in as: ${t.displayName} \xB7 tier: ${t.trustTier}`),0):(console.error("Couldn't reach OpenCrater (or your session expired \u2014 try: opencrater login)."),1)}function dn(){return R({...g(),devToken:null},process.env,{allowClearToken:true}),console.log("Signed out of the OpenCrater compute wallet on this machine."),0}async function un(e){let t=g().devToken;if(!t)return console.error("Not signed in. Run: opencrater login"),1;let n=await M(t,g().installId);if(n&&n.balanceMicroUsd<=0)return console.error("Your OpenCrater compute balance is empty \u2014 see Blips to earn more."),console.error("Check anytime with: opencrater balance"),1;let o=`${P().replace(/\/$/,"")}/gateway`,r=u__namespace.join(u__namespace.dirname(E()),"claude-gateway.settings.json");try{m__namespace.mkdirSync(u__namespace.dirname(r),{recursive:!0}),m__namespace.writeFileSync(r,JSON.stringify({apiKeyHelper:`echo ${t}`}),{mode:384});}catch(f){return console.error(`Couldn't write gateway settings: ${f.message}`),1}n&&console.log(`Launching Claude Code on OpenCrater compute \xB7 balance ${W(n.balanceMicroUsd)}${H(n)}`);let i={...process.env,ANTHROPIC_BASE_URL:o,OPENCRATER_ON_GATEWAY:"1"};delete i.ANTHROPIC_API_KEY;let a=child_process.spawn("claude",[...e,"--settings",r],{stdio:"inherit",env:i,shell:process.platform==="win32"});return await new Promise(f=>{a.on("exit",s=>f(s??0)),a.on("error",s=>{console.error(`Couldn't launch claude: ${s.message}`),console.error("Is Claude Code installed? https://claude.com/claude-code"),f(127);});})}async function pn(e){let t=g().devToken;if(!t)return console.error("Not signed in. Run: opencrater login"),1;let n=await M(t,g().installId);if(n&&n.balanceMicroUsd<=0)return console.error("Your OpenCrater compute balance is empty \u2014 see Blips to earn more."),console.error("Check anytime with: opencrater balance"),1;let o=`${P().replace(/\/$/,"")}/gateway/v1`;n&&console.log(`Launching Codex on OpenCrater compute \xB7 balance ${W(n.balanceMicroUsd)}${H(n)}`);let r={...process.env,OPENCRATER_TOKEN:t,OPENCRATER_ON_GATEWAY:"1"},i=["-c",'model_provider="opencrater"',"-c",'model_providers.opencrater.name="OpenCrater"',"-c",`model_providers.opencrater.base_url="${o}"`,"-c",'model_providers.opencrater.wire_api="responses"',"-c",'model_providers.opencrater.env_key="OPENCRATER_TOKEN"'],a=[];for(let s=0;s<e.length;s++){let c=e[s],l=e[s+1];c==="-c"&&(l===void 0||!l.includes("="))?a.push("resume","--last"):a.push(c);}let f=child_process.spawn("codex",[...i,...a],{stdio:"inherit",env:r,shell:process.platform==="win32"});return await new Promise(s=>{f.on("exit",c=>s(c??0)),f.on("error",c=>{console.error(`Couldn't launch codex: ${c.message}`),console.error("Is Codex installed? npm i -g @openai/codex"),s(127);});})}function mn(){let e=process.env.GROK_HOME;return e&&e.trim()!==""?e:u__namespace.join(T__namespace.homedir(),".grok")}function gn(e){let t=u__namespace.join(mn(),"config.toml"),n="";try{n=m__namespace.readFileSync(t,"utf8");}catch{}if(/^\s*\[model\.opencrater\]/m.test(n))return;let o=n.length===0?"":n.endsWith(`
10
+ `;}return t}function nn(e){try{let t=u__namespace.join(B("grok_cli",e),"config.toml"),n="";try{n=m__namespace.readFileSync(t,"utf8");}catch{}let o=en(n);if(o===n)return;m__namespace.mkdirSync(u__namespace.dirname(t),{recursive:!0}),m__namespace.writeFileSync(t,o,"utf8");}catch{}}function D(e,t,n){let o=F(e);return o.length===0?"nochange":(e==="grok_cli"&&nn(process.env),e==="copilot_cli"?Ze(e,t,n,o):e==="antigravity"?Xe(t,n,o):Je(e,t,n,o))}function N(e,t,n=process.env){return Z(n).map(o=>{try{let r=D(o,e,t);return {host:o,status:r,events:F(o)}}catch(r){return {host:o,status:"error",events:[],error:r.message}}})}function ee(e=process.env){let t=[];for(let n of x){let o;try{o=P(I(n,e));}catch{continue}if(n==="antigravity"){for(let i of Object.values(o))if(!(!i||typeof i!="object"))for(let[a,f]of Object.entries(i))for(let s of Array.isArray(f)?f:[]){let c=s,l=Array.isArray(c.hooks)?c.hooks.find(d=>typeof d.command=="string"&&b(d.command))?.command:void 0;l&&t.push({host:n,event:a,command:l});}continue}let r=o.hooks;if(!(!r||typeof r!="object"))for(let[i,a]of Object.entries(r))for(let f of Array.isArray(a)?a:[]){let s=f,c=Array.isArray(s.hooks)?s.hooks.find(p=>typeof p.command=="string"&&b(p.command))?.command:void 0,l=[s.bash,s.command,s.powershell].find(p=>typeof p=="string"&&b(p)),d=c??l;d&&t.push({host:n,event:i,command:d});}}return t}function pe(e=process.env){let t=0;for(let n of x){let o=I(n,e),r;try{r=P(o);}catch{continue}if(n==="antigravity"){let s=false;for(let c of Object.keys(r)){let l=r[c];if(!l||typeof l!="object"||Array.isArray(l))continue;let d=l;for(let p of Object.keys(d)){let k=Array.isArray(d[p])?d[p]:[],w=k.filter(Ce=>{let ne=Ce,te=Array.isArray(ne.hooks)&&ne.hooks.some(oe=>typeof oe.command=="string"&&b(oe.command));return te&&t++,!te});w.length!==k.length&&(s=true,w.length>0?d[p]=w:delete d[p]);}Object.keys(d).length===0&&(delete r[c],s=true);}if(s)try{Object.keys(r).length===0?m__namespace.rmSync(o,{force:!0}):A(o,r);}catch{}ue(e);continue}let i=r.hooks;if(!i||typeof i!="object")continue;let a=i,f=false;for(let s of Object.keys(a)){let c=Array.isArray(a[s])?a[s]:[],l=c.filter(d=>{let p=d,k=Array.isArray(p.hooks)&&p.hooks.some(w=>typeof w.command=="string"&&b(w.command))||[p.bash,p.powershell,p.command].some(w=>typeof w=="string"&&b(w));return k&&t++,!k});l.length!==c.length&&(f=true,l.length>0?a[s]=l:delete a[s]);}if(f)try{let s=Object.keys(r).filter(l=>l!=="version"&&l!=="hooks"),c=n==="copilot_cli"||n==="codex";Object.keys(a).length===0&&s.length===0&&c?m__namespace.rmSync(o,{force:!0}):A(o,r);}catch{}}return t}var _="1.4.7";var tn="https://api.opencrater.to";function v(e,t=process.env){let n=t.OPENCRATER_API_ORIGIN;return (e??(n&&n.trim()!==""?n:tn)).replace(/\/+$/,"")}function rn(){return u__namespace.join(T__namespace.homedir(),".config","opencrater","runtime")}function sn(e){return ["install","--prefix",e,"opencrater@latest","--silent","--no-audit","--no-fund"]}function z(e=rn()){if(process.env.VITEST||process.env.OPENCRATER_DISABLE_RUNTIME_PIN)return false;try{return child_process.spawnSync("npm",sn(e),{stdio:"ignore",windowsHide:!0,shell:process.platform==="win32"}).status===0}catch{return false}}async function he(){let e=u__namespace.join(T.homedir(),".config","opencrater"),t=u__namespace.join(e,"painter.lock"),n={};try{n=JSON.parse(m.readFileSync(t,"utf8"));}catch{console.log("opencrater: no Blip is on screen.");return}try{m.mkdirSync(e,{recursive:!0}),m.writeFileSync(u__namespace.join(e,"dismiss.signal"),JSON.stringify({impressionId:n.impressionId,at:Date.now()}));}catch{}if(n.dismissUrl)try{await fetch(n.dismissUrl,{signal:AbortSignal.timeout(1e3)});}catch{}if(n.impressionId)try{await fetch(`${v()}/x/${n.impressionId}`,{signal:AbortSignal.timeout(2500)});}catch{}if(n.pid&&n.pid>1)try{process.kill(n.pid,"SIGTERM");}catch{}console.log("opencrater: Blip dismissed \u2014 feedback recorded.");}function Se(){let e=process.env.OPENCRATER_WEB_ORIGIN;return e&&e.trim()!==""?e.replace(/\/$/,""):v().replace("//api.","//").replace(/\/$/,"")}function dn(e){try{let t=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";child_process.spawn(t,[e],{stdio:"ignore",detached:!0,shell:process.platform==="win32"}).unref();}catch{}}function W(e){return `${Math.round(e/1e3).toLocaleString()} tokens`}function un(e){let t=e/1e3;return t>0&&t<10?`${(Math.round(t*10)/10).toFixed(1)} tokens`:`${Math.round(t).toLocaleString()} tokens`}function M(e){let t=e?.pendingMicroUsd??0;return t>0?` \xB7 +${un(t)} pending`:""}async function H(e,t){try{let n=new URL(`${v()}/v1/dev/me`);t&&n.searchParams.set("installId",t);let o=await fetch(n,{headers:{authorization:`Bearer ${e}`}});return o.ok?await o.json():null}catch{return null}}function pn(){return new Promise((e,t)=>{let n=ve__namespace.randomBytes(16).toString("hex"),o,r,i=new Promise((c,l)=>{o=c,r=l;}),a=be__namespace.createServer((c,l)=>{try{let d=new URL(c.url??"/","http://127.0.0.1");if(d.pathname==="/cb"&&d.searchParams.get("state")===n){let p=(d.searchParams.get("token")??"").trim(),k=p.startsWith("ocd_");l.writeHead(k?200:400,{"content-type":"text/html"}),l.end(`<!doctype html><meta charset="utf-8"><body style="font-family:system-ui;background:#0d1117;color:#e7e9ee;display:grid;place-items:center;height:100vh;margin:0"><div style="text-align:center"><h2>${k?"\u2713 Signed in":"Something went wrong"}</h2><p style="color:#9aa0aa">You can close this tab and return to your terminal.</p></div>`),k&&o(p);return}l.writeHead(404).end("not found");}catch{try{l.writeHead(500).end();}catch{}}}),f=setTimeout(()=>r(new Error("timeout")),18e4),s=()=>{clearTimeout(f);try{a.close();}catch{}};a.on("error",c=>{s(),t(c instanceof Error?c:new Error(String(c))),r(c instanceof Error?c:new Error(String(c)));}),a.listen(0,"127.0.0.1",()=>{let c=a.address(),l=typeof c=="object"&&c?c.port:0;if(!l){s(),t(new Error("no port"));return}let d=encodeURIComponent(`http://127.0.0.1:${l}/cb?state=${n}`);e({url:`${Se()}/dev/link?callback=${d}`,token:i,cancel:s});});})}async function mn(e){let t=await H(e,g().installId);if(!t)return console.error("Couldn't verify that token \u2014 check it and try again."),1;O({devToken:e}),console.log(`
11
+ \u2713 Signed in as ${t.displayName}.`),console.log(` Compute balance: ${W(t.balanceMicroUsd)}${M(t)} \xB7 tier: ${t.trustTier}`);let n=N().filter(o=>o.status!=="error").map(o=>o.host);return n.length?(console.log(` Wired into: ${n.join(", ")}`),process.stdout.write(" Pinning fast runtime (one-time, ~15s)\u2026 "),console.log(z()?"\u2713":"skipped (hooks use npx fallback)")):console.log(" No supported AI CLIs detected yet \u2014 they'll wire automatically once you install one."),console.log(" See Blips in your sessions to earn your weekly compute."),0}async function gn(){let e=null;try{e=await pn();}catch{e=null;}let t=e?.url??`${Se()}/dev/link`;console.log("Sign in to OpenCrater in your browser (we tried to open it):"),console.log(` ${t}
12
+ `),dn(t);let n=we__namespace.createInterface({input:process.stdin,output:process.stdout});console.log(e?"Waiting for your browser to finish\u2026 (or paste a token here and press enter)":"Generate a token on that page, then paste it here:");let o=new Promise(i=>{n.on("line",a=>{let f=a.trim();f.startsWith("ocd_")&&i(f);});}),r=null;try{let i=e?[e.token,o]:[o];r=await Promise.race(i.map(a=>a.catch(()=>""))),r||(r=await o);}finally{e?.cancel(),n.close();}return !r||!r.startsWith("ocd_")?(console.error("That doesn't look like a token (should start with ocd_)."),1):mn(r)}async function hn(){let e=g().devToken;if(!e)return console.error("Not signed in. Run: opencrater login"),1;let t=await H(e,g().installId);return t?(console.log(`Compute balance: ${W(t.balanceMicroUsd)}${M(t)}`),console.log(` signed in as: ${t.displayName} \xB7 tier: ${t.trustTier}`),0):(console.error("Couldn't reach OpenCrater (or your session expired \u2014 try: opencrater login)."),1)}function yn(){return R({...g(),devToken:null},process.env,{allowClearToken:true}),console.log("Signed out of the OpenCrater compute wallet on this machine."),0}async function kn(e){let t=g().devToken;if(!t)return console.error("Not signed in. Run: opencrater login"),1;let n=await H(t,g().installId);if(n&&n.balanceMicroUsd<=0)return console.error("Your OpenCrater compute balance is empty \u2014 see Blips to earn more."),console.error("Check anytime with: opencrater balance"),1;let o=`${v().replace(/\/$/,"")}/gateway`,r=u__namespace.join(u__namespace.dirname(E()),"claude-gateway.settings.json");try{m__namespace.mkdirSync(u__namespace.dirname(r),{recursive:!0}),m__namespace.writeFileSync(r,JSON.stringify({apiKeyHelper:`echo ${t}`}),{mode:384});}catch(f){return console.error(`Couldn't write gateway settings: ${f.message}`),1}n&&console.log(`Launching Claude Code on OpenCrater compute \xB7 balance ${W(n.balanceMicroUsd)}${M(n)}`);let i={...process.env,ANTHROPIC_BASE_URL:o,OPENCRATER_ON_GATEWAY:"1"};delete i.ANTHROPIC_API_KEY;let a=child_process.spawn("claude",[...e,"--settings",r],{stdio:"inherit",env:i,shell:process.platform==="win32"});return await new Promise(f=>{a.on("exit",s=>f(s??0)),a.on("error",s=>{console.error(`Couldn't launch claude: ${s.message}`),console.error("Is Claude Code installed? https://claude.com/claude-code"),f(127);});})}async function wn(e){let t=g().devToken;if(!t)return console.error("Not signed in. Run: opencrater login"),1;let n=await H(t,g().installId);if(n&&n.balanceMicroUsd<=0)return console.error("Your OpenCrater compute balance is empty \u2014 see Blips to earn more."),console.error("Check anytime with: opencrater balance"),1;let o=`${v().replace(/\/$/,"")}/gateway/v1`;n&&console.log(`Launching Codex on OpenCrater compute \xB7 balance ${W(n.balanceMicroUsd)}${M(n)}`);let r={...process.env,OPENCRATER_TOKEN:t,OPENCRATER_ON_GATEWAY:"1"},i=["-c",'model_provider="opencrater"',"-c",'model_providers.opencrater.name="OpenCrater"',"-c",`model_providers.opencrater.base_url="${o}"`,"-c",'model_providers.opencrater.wire_api="responses"',"-c",'model_providers.opencrater.env_key="OPENCRATER_TOKEN"'],a=[];for(let s=0;s<e.length;s++){let c=e[s],l=e[s+1];c==="-c"&&(l===void 0||!l.includes("="))?a.push("resume","--last"):a.push(c);}let f=child_process.spawn("codex",[...i,...a],{stdio:"inherit",env:r,shell:process.platform==="win32"});return await new Promise(s=>{f.on("exit",c=>s(c??0)),f.on("error",c=>{console.error(`Couldn't launch codex: ${c.message}`),console.error("Is Codex installed? npm i -g @openai/codex"),s(127);});})}function bn(){let e=process.env.GROK_HOME;return e&&e.trim()!==""?e:u__namespace.join(T__namespace.homedir(),".grok")}function vn(e){let t=u__namespace.join(bn(),"config.toml"),n="";try{n=m__namespace.readFileSync(t,"utf8");}catch{}if(/^\s*\[model\.opencrater\]/m.test(n))return;let o=n.length===0?"":n.endsWith(`
13
13
  `)?`
14
14
  `:`
15
15
 
@@ -18,7 +18,7 @@ model = "x-ai/grok-build-0.1"
18
18
  base_url = "${e}"
19
19
  name = "OpenCrater Compute"
20
20
  env_key = "OPENCRATER_TOKEN"
21
- `,m__namespace.mkdirSync(u__namespace.dirname(t),{recursive:true}),m__namespace.writeFileSync(t,n,"utf8");}async function hn(e){let t=g().devToken;if(!t)return console.error("Not signed in. Run: opencrater login"),1;let n=await M(t,g().installId);if(n&&n.balanceMicroUsd<=0)return console.error("Your OpenCrater compute balance is empty \u2014 see Blips to earn more."),console.error("Check anytime with: opencrater balance"),1;let o=`${P().replace(/\/$/,"")}/gateway/v1`;n&&console.log(`Launching Grok on OpenCrater compute \xB7 balance ${W(n.balanceMicroUsd)}${H(n)}`);try{D("grok_cli");}catch{}try{gn(o);}catch(s){return console.error(`Couldn't configure the Grok compute model: ${s.message}`),1}let r={...process.env,OPENCRATER_TOKEN:t,OPENCRATER_ON_GATEWAY:"1"};delete r.GROK_MODELS_BASE_URL,delete r.GROK_HOME;let a=e.some(s=>s==="-m"||s==="--model"||s.startsWith("--model="))?[]:["-m","opencrater"],f=child_process.spawn("grok",[...a,...e],{stdio:"inherit",env:r,shell:process.platform==="win32"});return await new Promise(s=>{f.on("exit",c=>s(c??0)),f.on("error",c=>{console.error(`Couldn't launch grok: ${c.message}`),console.error("Is Grok installed? npm i -g @xai-official/grok"),s(127);});})}function ve(e){let t=new Map,n=[];for(let o=0;o<e.length;o++){let r=e[o];if(r!==void 0)if(r.startsWith("--")){let i=r.indexOf("=");if(i!==-1)t.set(r.slice(2,i),r.slice(i+1));else {let a=e[o+1];a!==void 0&&!a.startsWith("--")?(t.set(r.slice(2),a),o++):t.set(r.slice(2),"true");}}else n.push(r);}return {flags:t,rest:n}}function Se(e,t){let n=g();n.integrations.some(o=>o.key===e&&o.package===t)||C({integrations:[...n.integrations,{key:e,package:t}].slice(-32)});}function G(e,t){let n=t||"compute hooks";if(e.length===0){console.log(`No supported AI CLIs detected yet \u2014 OpenCrater will wire ${n} automatically the moment you install one (it re-checks on the next session).`);return}console.log(`OpenCrater wired ${n} into:`);for(let o of e)if(o.status==="error")console.log(` \u2717 ${o.host}: ${o.error}`);else {let r=o.status==="nochange"?" \u2014 already set up":"";console.log(` \u2022 ${o.host} (${o.events.join(", ")})${r}`);}}function yn(){return C({optOut:true}),console.log("OpenCrater Blips are now OFF for this machine."),console.log("Re-enable any time with: npx opencrater on"),0}function kn(e){let{flags:t}=ve(e),n=t.get("key"),o=t.get("package");return C({optOut:false}),n&&o?(Se(n,o),G(_(n,o),o),process.stdout.write("Pinning fast runtime (one-time, ~15s)\u2026 "),console.log(z()?"\u2713":"skipped (npm unavailable \u2014 hooks use npx fallback)")):g().devToken?(G(_()),process.stdout.write("Pinning fast runtime (one-time, ~15s)\u2026 "),console.log(z()?"\u2713":"skipped (npm unavailable \u2014 hooks use npx fallback)")):(console.log("OpenCrater Blips are now ON for this machine."),console.log("Earn compute: run `opencrater login` (no package needed)."),console.log("Earn cash as a publisher: `opencrater on --key <key> --package <name>`.")),console.log("Opt out any time with: npx opencrater off"),0}function wn(){let e=g(),t=e.lastShownAt>0?new Date(e.lastShownAt).toISOString():"never";console.log(`opencrater v${I}`),console.log(` state file: ${E()}`),console.log(` install id: ${e.installId}`),console.log(` opted out: ${e.optOut?"yes":"no"}`),console.log(` last shown: ${t}`),console.log(` pooled Blips: ${e.pool.length}`),console.log(` hosts found: ${Q().join(", ")||"(none)"}`),console.log(` integrations: ${e.integrations.map(o=>o.package).join(", ")||"(none)"}`);let n=Z();return console.log(` wired hooks: ${n.length}`),0}function bn(e){let{flags:t}=ve(e),n=t.get("key"),o=t.get("package");if(!n||!o)return console.error("Usage: opencrater hooks install --key <publisherKey> --package <name> [--host <host>]"),1;Se(n,o);let r=t.get("host");if(r&&r!=="true"){if(!j.includes(r))return console.error(`Unknown host "${r}". Supported: ${j.join(", ")}`),1;let i=r;try{let a=D(i,n,o);G([{host:i,status:a,events:F(i)}],o);}catch(a){return console.error(`Could not wire ${i}: ${a.message}`),1}}else G(_(n,o),o);return console.log("Remove with: npx opencrater hooks uninstall"),0}function vn(){let e=ue();return C({integrations:[]}),console.log(e>0?`Removed ${e} OpenCrater hook${e===1?"":"s"} across all hosts.`:"No OpenCrater hooks installed."),0}function Sn(){let e=Z();if(e.length===0)return console.log("No OpenCrater hooks installed."),0;for(let t of e)console.log(`${t.host} ${t.event}: ${t.command}`);return 0}function ge(){return console.log(`opencrater v${I} \u2014 OpenCrater Blips
21
+ `,m__namespace.mkdirSync(u__namespace.dirname(t),{recursive:true}),m__namespace.writeFileSync(t,n,"utf8");}async function Sn(e){let t=g().devToken;if(!t)return console.error("Not signed in. Run: opencrater login"),1;let n=await H(t,g().installId);if(n&&n.balanceMicroUsd<=0)return console.error("Your OpenCrater compute balance is empty \u2014 see Blips to earn more."),console.error("Check anytime with: opencrater balance"),1;let o=`${v().replace(/\/$/,"")}/gateway/v1`;n&&console.log(`Launching Grok on OpenCrater compute \xB7 balance ${W(n.balanceMicroUsd)}${M(n)}`);try{D("grok_cli");}catch{}try{vn(o);}catch(s){return console.error(`Couldn't configure the Grok compute model: ${s.message}`),1}let r={...process.env,OPENCRATER_TOKEN:t,OPENCRATER_ON_GATEWAY:"1"};delete r.GROK_MODELS_BASE_URL,delete r.GROK_HOME;let a=e.some(s=>s==="-m"||s==="--model"||s.startsWith("--model="))?[]:["-m","opencrater"],f=child_process.spawn("grok",[...a,...e],{stdio:"inherit",env:r,shell:process.platform==="win32"});return await new Promise(s=>{f.on("exit",c=>s(c??0)),f.on("error",c=>{console.error(`Couldn't launch grok: ${c.message}`),console.error("Is Grok installed? npm i -g @xai-official/grok"),s(127);});})}function je(e){let t=new Map,n=[];for(let o=0;o<e.length;o++){let r=e[o];if(r!==void 0)if(r.startsWith("--")){let i=r.indexOf("=");if(i!==-1)t.set(r.slice(2,i),r.slice(i+1));else {let a=e[o+1];a!==void 0&&!a.startsWith("--")?(t.set(r.slice(2),a),o++):t.set(r.slice(2),"true");}}else n.push(r);}return {flags:t,rest:n}}function xe(e,t){let n=g();n.integrations.some(o=>o.key===e&&o.package===t)||O({integrations:[...n.integrations,{key:e,package:t}].slice(-32)});}function J(e,t){let n=t||"compute hooks";if(e.length===0){console.log(`No supported AI CLIs detected yet \u2014 OpenCrater will wire ${n} automatically the moment you install one (it re-checks on the next session).`);return}console.log(`OpenCrater wired ${n} into:`);for(let o of e)if(o.status==="error")console.log(` \u2717 ${o.host}: ${o.error}`);else {let r=o.status==="nochange"?" \u2014 already set up":"";console.log(` \u2022 ${o.host} (${o.events.join(", ")})${r}`);}}function jn(){return O({optOut:true}),console.log("OpenCrater Blips are now OFF for this machine."),console.log("Re-enable any time with: npx opencrater on"),0}function xn(e){let{flags:t}=je(e),n=t.get("key"),o=t.get("package");return O({optOut:false}),n&&o?(xe(n,o),J(N(n,o),o),process.stdout.write("Pinning fast runtime (one-time, ~15s)\u2026 "),console.log(z()?"\u2713":"skipped (npm unavailable \u2014 hooks use npx fallback)")):g().devToken?(J(N()),process.stdout.write("Pinning fast runtime (one-time, ~15s)\u2026 "),console.log(z()?"\u2713":"skipped (npm unavailable \u2014 hooks use npx fallback)")):(console.log("OpenCrater Blips are now ON for this machine."),console.log("Earn compute: run `opencrater login` (no package needed)."),console.log("Earn cash as a publisher: `opencrater on --key <key> --package <name>`.")),console.log("Opt out any time with: npx opencrater off"),0}function Cn(){let e=g(),t=e.lastShownAt>0?new Date(e.lastShownAt).toISOString():"never";console.log(`opencrater v${_}`),console.log(` state file: ${E()}`),console.log(` install id: ${e.installId}`),console.log(` opted out: ${e.optOut?"yes":"no"}`),console.log(` last shown: ${t}`),console.log(` pooled Blips: ${e.pool.length}`),console.log(` hosts found: ${Z().join(", ")||"(none)"}`),console.log(` integrations: ${e.integrations.map(o=>o.package).join(", ")||"(none)"}`);let n=ee();return console.log(` wired hooks: ${n.length}`),0}function On(e){let{flags:t}=je(e),n=t.get("key"),o=t.get("package");if(!n||!o)return console.error("Usage: opencrater hooks install --key <publisherKey> --package <name> [--host <host>]"),1;xe(n,o);let r=t.get("host");if(r&&r!=="true"){if(!x.includes(r))return console.error(`Unknown host "${r}". Supported: ${x.join(", ")}`),1;let i=r;try{let a=D(i,n,o);J([{host:i,status:a,events:F(i)}],o);}catch(a){return console.error(`Could not wire ${i}: ${a.message}`),1}}else J(N(n,o),o);return console.log("Remove with: npx opencrater hooks uninstall"),0}function An(){let e=pe();return O({integrations:[]}),console.log(e>0?`Removed ${e} OpenCrater hook${e===1?"":"s"} across all hosts.`:"No OpenCrater hooks installed."),0}function Pn(){let e=ee();if(e.length===0)return console.log("No OpenCrater hooks installed."),0;for(let t of e)console.log(`${t.host} ${t.event}: ${t.command}`);return 0}function ye(){return console.log(`opencrater v${_} \u2014 OpenCrater Blips
22
22
 
23
23
  Usage:
24
24
  opencrater on [--key <ock_\u2026> --package <name>]
@@ -37,10 +37,11 @@ Usage:
37
37
  opencrater balance Show your compute wallet balance
38
38
  opencrater logout Unlink the compute wallet on this machine
39
39
  opencrater status Show install id, opt-out state, detected hosts
40
+ opencrater x Dismiss the Blip currently on screen
40
41
  opencrater hooks install --key <ock_\u2026> --package <name> [--host <host>]
41
42
  (Re)install hooks \u2014 all detected hosts, or one --host
42
43
  opencrater hooks uninstall Remove all OpenCrater hooks (every host)
43
44
  opencrater hooks list List installed OpenCrater hooks
44
45
 
45
- Hosts: ${j.join(", ")}
46
- Environment: OPENCRATER_DISABLE=1 disables everything; NO_COLOR respected.`),0}function jn(e){let[t,...n]=e;switch(t){case "off":return yn();case "on":return kn(n);case "login":return ln();case "balance":return fn();case "logout":return dn();case "claude":case "code":return un(n);case "codex":return pn(n);case "grok":return hn(n);case "status":return wn();case "hooks":{let[o,...r]=n;switch(o){case "install":return bn(r);case "uninstall":return vn();case "list":return Sn();default:return console.error("Usage: opencrater hooks <install|uninstall|list>"),1}}case "version":case "--version":case "-v":return console.log(I),0;case void 0:case "help":case "--help":case "-h":return ge();default:return console.error(`Unknown command: ${t}`),ge(),1}}typeof K<"u"&&typeof module<"u"&&K.main===module&&Promise.resolve().then(()=>jn(process.argv.slice(2))).then(e=>{process.exitCode=e;}).catch(e=>{console.error(`opencrater: ${e.message}`),process.exitCode=1;});exports.runCli=jn;
46
+ Hosts: ${x.join(", ")}
47
+ Environment: OPENCRATER_DISABLE=1 disables everything; NO_COLOR respected.`),0}function Rn(e){let[t,...n]=e;switch(t){case "off":return jn();case "on":return xn(n);case "login":return gn();case "balance":return hn();case "logout":return yn();case "claude":case "code":return kn(n);case "codex":return wn(n);case "grok":return Sn(n);case "status":return Cn();case "x":case "dismiss":return he().then(()=>0);case "hooks":{let[o,...r]=n;switch(o){case "install":return On(r);case "uninstall":return An();case "list":return Pn();default:return console.error("Usage: opencrater hooks <install|uninstall|list>"),1}}case "version":case "--version":case "-v":return console.log(_),0;case void 0:case "help":case "--help":case "-h":return ye();default:return console.error(`Unknown command: ${t}`),ye(),1}}typeof V<"u"&&typeof module<"u"&&V.main===module&&Promise.resolve().then(()=>Rn(process.argv.slice(2))).then(e=>{process.exitCode=e;}).catch(e=>{console.error(`opencrater: ${e.message}`),process.exitCode=1;});exports.runCli=Rn;
package/dist/dismiss.js CHANGED
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- 'use strict';var fs=require('fs'),os=require('os'),t=require('path');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 t__namespace=/*#__PURE__*/_interopNamespace(t);var i=(n,o)=>()=>(n&&(o=n(n=0)),o);var c=(n,o)=>()=>(o||n((o={exports:{}}).exports,o),o.exports);var r=i(()=>{});var s=i(()=>{});function a(n,o=process.env){let e=o.OPENCRATER_API_ORIGIN;return (n??(e&&e.trim()!==""?e:p)).replace(/\/+$/,"")}var p,l=i(()=>{r();s();p="https://api.opencrater.to";});var S=c(()=>{l();async function f(){let n=t__namespace.join(os.homedir(),".config","opencrater"),o=t__namespace.join(n,"painter.lock"),e={};try{e=JSON.parse(fs.readFileSync(o,"utf8"));}catch{console.log("opencrater: no Blip is on screen.");return}try{fs.mkdirSync(n,{recursive:!0}),fs.writeFileSync(t__namespace.join(n,"dismiss.signal"),JSON.stringify({impressionId:e.impressionId,at:Date.now()}));}catch{}if(e.dismissUrl)try{await fetch(e.dismissUrl,{signal:AbortSignal.timeout(1e3)});}catch{}if(e.impressionId)try{await fetch(`${a()}/x/${e.impressionId}`,{signal:AbortSignal.timeout(2500)});}catch{}if(e.pid&&e.pid>1)try{process.kill(e.pid,"SIGTERM");}catch{}console.log("opencrater: Blip dismissed \u2014 feedback recorded."),console.log(" changed your mind? npx opencrater show");}f().finally(()=>{setTimeout(()=>process.exit(0),50).unref?.();});});var dismiss = S();
2
+ 'use strict';var fs=require('fs'),os=require('os'),i=require('path');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 i__namespace=/*#__PURE__*/_interopNamespace(i);var t=(n,o)=>()=>(n&&(o=n(n=0)),o);var u=(n,o)=>()=>(o||n((o={exports:{}}).exports,o),o.exports);var r=t(()=>{});var s=t(()=>{});function a(n,o=process.env){let e=o.OPENCRATER_API_ORIGIN;return (n??(e&&e.trim()!==""?e:d)).replace(/\/+$/,"")}var d,l=t(()=>{r();s();d="https://api.opencrater.to";});async function c(){let n=i__namespace.join(os.homedir(),".config","opencrater"),o=i__namespace.join(n,"painter.lock"),e={};try{e=JSON.parse(fs.readFileSync(o,"utf8"));}catch{console.log("opencrater: no Blip is on screen.");return}try{fs.mkdirSync(n,{recursive:!0}),fs.writeFileSync(i__namespace.join(n,"dismiss.signal"),JSON.stringify({impressionId:e.impressionId,at:Date.now()}));}catch{}if(e.dismissUrl)try{await fetch(e.dismissUrl,{signal:AbortSignal.timeout(1e3)});}catch{}if(e.impressionId)try{await fetch(`${a()}/x/${e.impressionId}`,{signal:AbortSignal.timeout(2500)});}catch{}if(e.pid&&e.pid>1)try{process.kill(e.pid,"SIGTERM");}catch{}console.log("opencrater: Blip dismissed \u2014 feedback recorded.");}var p=t(()=>{l();});var b=u(()=>{p();c().finally(()=>{setTimeout(()=>process.exit(0),50).unref?.();});});var dismiss = b();
3
3
  module.exports=dismiss;
package/dist/hook.js CHANGED
@@ -1,13 +1,13 @@
1
1
  #!/usr/bin/env node
2
- 'use strict';var child_process=require('child_process'),h=require('fs'),N=require('os'),y=require('path'),crypto=require('crypto');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 h__namespace=/*#__PURE__*/_interopNamespace(h);var N__namespace=/*#__PURE__*/_interopNamespace(N);var y__namespace=/*#__PURE__*/_interopNamespace(y);var M=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(o,e)=>(typeof require<"u"?require:o)[e]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var H={minIntervalSeconds:600,serveTimeoutMs:2500,preloadPoolSize:3,killSwitch:false,displayDurationSeconds:25,minSdkVersion:""},_e={claude_code:["SessionStart","Stop","SessionEnd","Notification"],codex:["Stop"],openclaw:[],antigravity:["Stop"],copilot_cli:["agentStop","sessionStart","sessionEnd","notification"],grok_cli:["SessionStart","Stop","SessionEnd","Notification"],generic:["SessionStart","Stop"]},Ie={claude_code:["SessionStart","Stop","SessionEnd","Notification","UserPromptSubmit","SubagentStart","SubagentStop","StopFailure","PreToolUse","PostToolUse","PostToolUseFailure","PostToolBatch","PermissionRequest","PermissionDenied","UserPromptExpansion","PreCompact","PostCompact","TaskCreated","TaskCompleted","Setup","TeammateIdle","Elicitation","ElicitationResult","ConfigChange","InstructionsLoaded","WorktreeCreate","WorktreeRemove","CwdChanged","FileChanged","MessageDisplay"],codex:["Stop","SessionStart","UserPromptSubmit","PreToolUse","PostToolUse","PermissionRequest","PreCompact","PostCompact"],openclaw:[],antigravity:["PreToolUse","PostToolUse","PreInvocation","PostInvocation","Stop"],copilot_cli:["agentStop","sessionStart","sessionEnd","notification","userPromptSubmitted","preToolUse","postToolUse","permissionRequest","errorOccurred","subagentStart","subagentStop"],grok_cli:["SessionStart","Stop","SessionEnd","Notification"],generic:["SessionStart","Stop"]};var A="1.4.5";var yt="https://api.opencrater.to";function K(t,o=process.env){let e=o.OPENCRATER_API_ORIGIN;return ((e&&e.trim()!==""?e:yt)).replace(/\/+$/,"")}function x(...t){try{if(process.env.OPENCRATER_DEBUG!=="1")return;console.error("[opencrater]",...t);try{let o=M("os"),e=M("fs"),r=M("path");e.appendFileSync(r.join(o.homedir(),".config","opencrater","hook.log"),`${new Date().toISOString()} [opencrater] ${t.map(n=>String(n)).join(" ")}
3
- `);}catch{}}catch{}}function J(t){return typeof t=="number"&&Number.isFinite(t)}function bt(t){let o=H;if(typeof t!="object"||t===null)return {...o};let e=t;return {minIntervalSeconds:J(e.minIntervalSeconds)?e.minIntervalSeconds:o.minIntervalSeconds,serveTimeoutMs:J(e.serveTimeoutMs)?e.serveTimeoutMs:o.serveTimeoutMs,preloadPoolSize:J(e.preloadPoolSize)?e.preloadPoolSize:o.preloadPoolSize,killSwitch:e.killSwitch===true,displayDurationSeconds:J(e.displayDurationSeconds)?e.displayDurationSeconds:o.displayDurationSeconds,minSdkVersion:typeof e.minSdkVersion=="string"?e.minSdkVersion:o.minSdkVersion}}async function Pe(t,o,e,r,n){try{let c=await fetch(`${t}${o}`,{method:"POST",headers:{"content-type":"application/json",...n??{}},body:JSON.stringify(e),signal:AbortSignal.timeout(r)});return c.ok?await c.json():(x(`POST ${o} -> HTTP ${c.status}`),null)}catch(c){return x(`POST ${o} failed:`,c),null}}function Ne(t,o){let e=t.host??"generic";return {publisherKey:t.publisherKey,packageName:t.packageName,placement:t.placement,host:e,sdkVersion:A,installId:o.installId,os:process.platform,termProgram:process.env.TERM_PROGRAM??void 0,topics:o.topics&&o.topics.length>0?o.topics:void 0,tags:o.tags&&o.tags.length>0?o.tags:void 0}}function $e(t){if(typeof t!="object"||t===null)return null;let o=t;if(typeof o.fill!="boolean")return null;let e={fill:o.fill,fallback:o.fallback??null,config:bt(o.config),...Array.isArray(o.allowedPlacements)?{allowedPlacements:o.allowedPlacements.filter(r=>typeof r=="string")}:{}};return o.blip!==void 0&&o.blip!==null&&(e.blip=o.blip),typeof o.computeBalanceMicroUsd=="number"&&(e.computeBalanceMicroUsd=o.computeBalanceMicroUsd),typeof o.weeklyGrantMicroUsd=="number"&&(e.weeklyGrantMicroUsd=o.weeklyGrantMicroUsd),typeof o.pendingMicroUsd=="number"&&(e.pendingMicroUsd=o.pendingMicroUsd),e}async function Me(t,o){let e=await Pe(o.origin,"/v1/serve",Ne(t,o),o.timeoutMs);return $e(e)}async function Le(t,o,e){let r={...Ne(o,e),publisherKey:o.publisherKey??"",packageName:o.packageName??""},n=await Pe(e.origin,"/v1/dev/serve",r,e.timeoutMs,{authorization:`Bearer ${t}`});return $e(n)}var wt=48,Y=360*60*1e3;function De(t){return crypto.createHash("sha256").update(t).digest("hex").slice(0,16)}function We(t){let o=new Set,e=s=>{o.size<wt&&o.add(s);},r=[];try{r=h__namespace.readdirSync(t);}catch{return []}let n=s=>r.includes(s),c=s=>{try{return h__namespace.readFileSync(y__namespace.join(t,s),"utf8")}catch{return ""}},f=s=>{try{return JSON.parse(c(s))}catch{return null}},p=f("package.json")??{},u={...p.dependencies??{},...p.devDependencies??{},...p.peerDependencies??{}},a=s=>Object.prototype.hasOwnProperty.call(u,s),d=s=>Object.keys(u).some(i=>i===s||i.startsWith(s));n("package.json")&&(e("lang:javascript"),(a("typescript")||n("tsconfig.json"))&&e("lang:typescript")),(n("deno.json")||n("deno.jsonc"))&&e("lang:typescript"),(n("tsconfig.json")||n("tsconfig.base.json"))&&e("lang:typescript"),n("jsconfig.json")&&e("lang:javascript"),(n("bun.lockb")||n("bun.lock"))&&e("lang:javascript"),r.some(s=>s.endsWith(".ts")||s.endsWith(".tsx")||s.endsWith(".mts")||s.endsWith(".cts"))&&e("lang:typescript"),r.some(s=>s.endsWith(".js")||s.endsWith(".jsx")||s.endsWith(".mjs")||s.endsWith(".cjs"))&&e("lang:javascript"),(n("requirements.txt")||n("pyproject.toml")||n("setup.py")||n("Pipfile"))&&e("lang:python"),(n("setup.cfg")||n("Pipfile.lock")||n("poetry.lock")||n("uv.lock")||n("environment.yml"))&&e("lang:python"),r.some(s=>s.endsWith(".py")||s.endsWith(".pyi")||s.endsWith(".ipynb"))&&e("lang:python"),(n("go.mod")||n("go.sum")||n("go.work"))&&e("lang:go"),r.some(s=>s.endsWith(".go"))&&e("lang:go"),(n("Cargo.toml")||n("Cargo.lock"))&&e("lang:rust"),r.some(s=>s.endsWith(".rs"))&&e("lang:rust"),(n("pom.xml")||n("build.gradle"))&&e("lang:java"),r.some(s=>s.endsWith(".java"))&&e("lang:java"),(n("build.gradle.kts")||n("settings.gradle.kts"))&&e("lang:kotlin"),r.some(s=>s.endsWith(".kt")||s.endsWith(".kts"))&&e("lang:kotlin"),(n("build.sbt")||n(".scalafmt.conf"))&&e("lang:scala"),r.some(s=>s.endsWith(".scala")||s.endsWith(".sc"))&&e("lang:scala"),r.some(s=>s.endsWith(".groovy")||s.endsWith(".gradle"))&&e("lang:groovy"),(n("deps.edn")||n("project.clj")||n("shadow-cljs.edn"))&&e("lang:clojure"),r.some(s=>s.endsWith(".clj")||s.endsWith(".cljs")||s.endsWith(".cljc"))&&e("lang:clojure"),r.some(s=>s.endsWith(".csproj")||s.endsWith(".sln"))&&e("lang:csharp"),r.some(s=>s.endsWith(".fsproj"))&&e("lang:fsharp"),r.some(s=>s.endsWith(".cs"))&&e("lang:csharp"),r.some(s=>s.endsWith(".fs")||s.endsWith(".fsx")||s.endsWith(".fsi"))&&e("lang:fsharp"),r.some(s=>s.endsWith(".cpp")||s.endsWith(".cc")||s.endsWith(".cxx")||s.endsWith(".hpp")||s.endsWith(".hxx"))&&e("lang:cpp"),r.some(s=>s.endsWith(".c"))&&e("lang:c"),(n("composer.json")||n("composer.lock"))&&e("lang:php"),r.some(s=>s.endsWith(".php"))&&e("lang:php"),(n("Gemfile")||n("Gemfile.lock")||n(".ruby-version")||r.some(s=>s.endsWith(".gemspec")))&&e("lang:ruby"),r.some(s=>s.endsWith(".rb")||s==="Rakefile")&&e("lang:ruby"),(n("Package.swift")||n("Podfile")||r.some(s=>s.endsWith(".xcodeproj")||s.endsWith(".xcworkspace")))&&e("lang:swift"),r.some(s=>s.endsWith(".swift"))&&e("lang:swift"),r.some(s=>s.endsWith(".m")||s.endsWith(".mm"))&&e("lang:objective-c"),(n("pubspec.yaml")||n("pubspec.yml")||n("pubspec.lock"))&&e("lang:dart"),r.some(s=>s.endsWith(".dart"))&&e("lang:dart"),(n("mix.exs")||n("mix.lock"))&&e("lang:elixir"),r.some(s=>s.endsWith(".ex")||s.endsWith(".exs"))&&e("lang:elixir"),(n("rebar.config")||n("rebar.lock"))&&e("lang:erlang"),r.some(s=>s.endsWith(".erl")||s.endsWith(".hrl"))&&e("lang:erlang"),(n("gleam.toml")||r.some(s=>s.endsWith(".gleam")))&&e("lang:gleam"),(n("stack.yaml")||n("cabal.project")||r.some(s=>s.endsWith(".cabal")||s.endsWith(".hs")))&&e("lang:haskell"),(n("dune-project")||n("dune")||r.some(s=>s.endsWith(".ml")||s.endsWith(".mli")))&&e("lang:ocaml"),(r.some(s=>s.endsWith(".rockspec")||s.endsWith(".lua"))||n(".luarc.json"))&&e("lang:lua"),(n("cpanfile")||n("Makefile.PL")||r.some(s=>s.endsWith(".pl")||s.endsWith(".pm")))&&e("lang:perl"),(n("DESCRIPTION")||n("renv.lock")||r.some(s=>s.endsWith(".Rproj")||s.endsWith(".Rmd")||s.endsWith(".R")))&&e("lang:r"),(n("Project.toml")||n("Manifest.toml")||r.some(s=>s.endsWith(".jl")))&&e("lang:julia"),(n("build.zig")||n("build.zig.zon")||r.some(s=>s.endsWith(".zig")))&&e("lang:zig"),r.some(s=>s.endsWith(".nimble")||s.endsWith(".nim"))&&e("lang:nim"),(n("shard.yml")||n("shard.lock")||r.some(s=>s.endsWith(".cr")))&&e("lang:crystal"),(n("v.mod")||r.some(s=>s.endsWith(".vsh")))&&e("lang:vlang"),r.some(s=>s.endsWith(".hx")||s.endsWith(".hxml"))&&e("lang:haxe"),(n("foundry.toml")||n("hardhat.config.js")||n("hardhat.config.ts")||r.some(s=>s.endsWith(".sol")))&&e("lang:solidity"),r.some(s=>s.endsWith(".f")||s.endsWith(".f90")||s.endsWith(".f95"))&&e("lang:fortran"),r.some(s=>s.endsWith(".cob")||s.endsWith(".cbl"))&&e("lang:cobol"),r.some(s=>s.endsWith(".asm"))&&e("lang:assembly"),r.some(s=>s.endsWith(".sh")||s.endsWith(".bash")||s.endsWith(".zsh"))&&e("lang:shell"),r.some(s=>s.endsWith(".ps1")||s.endsWith(".psm1"))&&e("lang:powershell"),r.some(s=>s.endsWith(".sql"))&&e("lang:sql"),r.some(s=>s.endsWith(".html")||s.endsWith(".htm"))&&e("lang:html"),r.some(s=>s.endsWith(".css"))&&e("lang:css"),r.some(s=>s.endsWith(".scss")||s.endsWith(".sass"))&&e("lang:scss"),r.some(s=>s.endsWith(".graphql")||s.endsWith(".gql"))&&e("lang:graphql"),r.some(s=>s.endsWith(".proto"))&&e("lang:protobuf");{if(a("react")&&e("fw:react"),a("next")&&e("fw:nextjs"),a("vue")&&e("fw:vue"),(a("nuxt")||a("nuxt3"))&&e("fw:nuxt"),a("@angular/core")&&e("fw:angular"),a("svelte")&&e("fw:svelte"),a("@sveltejs/kit")&&e("fw:sveltekit"),(a("@remix-run/react")||a("@remix-run/node"))&&e("fw:remix"),a("astro")&&e("fw:astro"),a("gatsby")&&e("fw:gatsby"),a("solid-js")&&e("fw:solid"),(a("@solidjs/start")||a("solid-start"))&&e("fw:solidstart"),(a("@builder.io/qwik")||a("@qwik.dev/core"))&&e("fw:qwik"),a("preact")&&e("fw:preact"),(a("lit")||a("lit-element"))&&e("fw:lit"),(a("ember-source")||a("ember-cli"))&&e("fw:ember"),a("htmx.org")&&e("fw:htmx"),a("vite")&&e("fw:vite"),a("webpack")&&e("fw:webpack"),a("express")&&e("fw:express"),a("fastify")&&e("fw:fastify"),a("@nestjs/core")&&e("fw:nestjs"),a("koa")&&e("fw:koa"),a("hono")&&e("fw:hono"),(a("@hapi/hapi")||a("hapi"))&&e("fw:hapi"),a("@adonisjs/core")&&e("fw:adonis"),(a("@trpc/server")||a("@trpc/client"))&&e("fw:trpc"),a("sails")&&e("fw:sails"),a("electron")&&e("fw:electron"),a("react-native")&&e("fw:react-native"),a("expo")&&e("fw:expo"),d("@ionic/")&&e("fw:ionic"),a("@capacitor/core")&&e("fw:capacitor"),n("requirements.txt")||n("pyproject.toml")||n("setup.py")||n("Pipfile")){let i=(c("requirements.txt")+c("pyproject.toml")+c("Pipfile")+c("setup.py")).toLowerCase();i.includes("fastapi")&&e("fw:fastapi"),i.includes("django")&&e("fw:django"),i.includes("flask")&&e("fw:flask"),i.includes("litestar")&&e("fw:litestar"),i.includes("starlette")&&e("fw:starlette"),i.includes("tornado")&&e("fw:tornado"),i.includes("sanic")&&e("fw:sanic"),i.includes("aiohttp")&&e("fw:aiohttp"),i.includes("pyramid")&&e("fw:pyramid"),i.includes("fasthtml")&&e("fw:fasthtml"),(i.includes("torch")||i.includes("pytorch"))&&e("fw:pytorch"),i.includes("tensorflow")&&e("fw:tensorflow"),(i.includes("jax")||i.includes("jaxlib"))&&e("fw:jax"),i.includes("keras")&&e("fw:keras"),(i.includes("scikit-learn")||i.includes("sklearn"))&&e("fw:scikit-learn"),i.includes("transformers")&&e("fw:transformers"),i.includes("langchain")&&e("fw:langchain"),(i.includes("llama-index")||i.includes("llama_index")||i.includes("llamaindex"))&&e("fw:llamaindex"),i.includes("pandas")&&e("fw:pandas"),i.includes("numpy")&&e("fw:numpy"),i.includes("streamlit")&&e("fw:streamlit"),i.includes("gradio")&&e("fw:gradio"),i.includes("fastai")&&e("fw:fastai");}if(n("go.mod")){let i=c("go.mod").toLowerCase();i.includes("gin-gonic/gin")&&e("fw:gin"),i.includes("labstack/echo")&&e("fw:echo"),i.includes("gofiber/fiber")&&e("fw:fiber"),i.includes("go-chi/chi")&&e("fw:chi"),(i.includes("gorilla/mux")||i.includes("gorilla/websocket"))&&e("fw:gorilla"),(i.includes("beego/beego")||i.includes("astaxie/beego"))&&e("fw:beego"),i.includes("gobuffalo/buffalo")&&e("fw:buffalo");}if(n("Cargo.toml")){let i=c("Cargo.toml").toLowerCase();i.includes("actix-web")&&e("fw:actix"),i.includes("axum")&&e("fw:axum"),i.includes("rocket")&&e("fw:rocket"),i.includes("warp")&&e("fw:warp"),i.includes("tonic")&&e("fw:tonic"),i.includes("leptos")&&e("fw:leptos"),i.includes("yew")&&e("fw:yew"),i.includes("tauri")&&e("fw:tauri"),i.includes("dioxus")&&e("fw:dioxus"),i.includes("bevy")&&e("fw:bevy");}if(n("pom.xml")||n("build.gradle")||n("build.gradle.kts")){let i=(c("pom.xml")+c("build.gradle")+c("build.gradle.kts")).toLowerCase();(i.includes("spring-boot")||i.includes("springframework"))&&e("fw:spring"),i.includes("quarkus")&&e("fw:quarkus"),i.includes("micronaut")&&e("fw:micronaut"),(i.includes("io.ktor")||i.includes("ktor-"))&&e("fw:ktor"),(i.includes("vertx")||i.includes("vert.x"))&&e("fw:vertx"),(i.includes("com.android")||i.includes("androidx"))&&e("fw:android"),(i.includes("androidx.compose")||i.includes("jetpack"))&&e("fw:jetpack-compose"),(i.includes("kotlin-multiplatform")||i.includes('kotlin("multiplatform")'))&&e("fw:kotlin-multiplatform");}if(n("Gemfile")){let i=c("Gemfile").toLowerCase();i.includes("rails")&&e("fw:rails"),i.includes("sinatra")&&e("fw:sinatra"),i.includes("hanami")&&e("fw:hanami");}if(n("composer.json")){let i=c("composer.json").toLowerCase();(i.includes("laravel/framework")||i.includes("laravel/laravel"))&&e("fw:laravel"),i.includes("symfony/")&&e("fw:symfony"),i.includes("drupal/")&&e("fw:drupal"),i.includes("codeigniter")&&e("fw:codeigniter"),i.includes("slim/slim")&&e("fw:slim");}(n("wp-config.php")||n("wp-load.php")||n("wp-content"))&&e("fw:wordpress"),n("pubspec.yaml")&&c("pubspec.yaml").toLowerCase().includes("flutter")&&e("fw:flutter");{let i=r.filter(b=>b.endsWith(".csproj"));if(i.length>0){let b=i.map(g=>c(g)).join(`
4
- `).toLowerCase();(b.includes("microsoft.net.sdk.web")||b.includes("microsoft.aspnetcore"))&&e("fw:aspnet"),b.includes("blazor")&&e("fw:blazor"),(b.includes("microsoft.net.sdk.maui")||b.includes("usemaui"))&&e("fw:maui");}}(n("ProjectSettings")||r.includes("Assembly-CSharp.csproj"))&&e("fw:unity"),n("project.godot")&&e("fw:godot");{let i=c("Package.swift").toLowerCase();i.includes("swiftui")&&e("fw:swiftui"),i.includes("uikit")&&e("fw:uikit");}let s=i=>r.some(b=>b===i||b.startsWith(i+"."));s("next.config")&&e("fw:nextjs"),s("nuxt.config")&&e("fw:nuxt"),s("astro.config")&&e("fw:astro"),s("svelte.config")&&e("fw:svelte"),s("remix.config")&&e("fw:remix"),s("gatsby-config")&&e("fw:gatsby"),s("vite.config")&&e("fw:vite"),s("vue.config")&&e("fw:vue"),s("qwik.config")&&e("fw:qwik"),n("angular.json")&&e("fw:angular"),s("capacitor.config")&&e("fw:capacitor"),s("ionic.config")&&e("fw:ionic"),n("app.json")&&c("app.json").toLowerCase().includes('"expo"')&&e("fw:expo");}{if((a("pg")||a("postgres")||a("pg-promise")||a("@vercel/postgres"))&&e("infra:postgres"),(a("mysql")||a("mysql2"))&&e("infra:mysql"),a("mariadb")&&e("infra:mariadb"),(a("redis")||a("ioredis"))&&e("infra:redis"),(a("mongodb")||a("mongoose"))&&e("infra:mongodb"),a("mongoose")&&e("infra:mongoose"),(a("better-sqlite3")||a("sqlite3")||a("sqlite"))&&e("infra:sqlite"),a("@libsql/client")&&e("infra:libsql"),a("cassandra-driver")&&e("infra:cassandra"),(a("@elastic/elasticsearch")||a("elasticsearch"))&&e("infra:elasticsearch"),a("@opensearch-project/opensearch")&&e("infra:opensearch"),(a("@clickhouse/client")||a("clickhouse"))&&e("infra:clickhouse"),(a("duckdb")||a("@duckdb/node-api"))&&e("infra:duckdb"),a("neo4j-driver")&&e("infra:neo4j"),a("@influxdata/influxdb-client")&&e("infra:influxdb"),a("snowflake-sdk")&&e("infra:snowflake"),a("@google-cloud/bigquery")&&e("infra:bigquery"),(a("firebase-admin")||a("@google-cloud/firestore"))&&e("infra:firestore"),(a("faunadb")||a("fauna"))&&e("infra:fauna"),(a("surrealdb")||a("surrealdb.js"))&&e("infra:surrealdb"),a("@qdrant/js-client-rest")&&e("infra:qdrant"),a("@pinecone-database/pinecone")&&e("infra:pinecone"),(a("weaviate-ts-client")||a("weaviate-client"))&&e("infra:weaviate"),a("chromadb")&&e("infra:chromadb"),a("@zilliz/milvus2-sdk-node")&&e("infra:milvus"),(a("@prisma/client")||a("prisma"))&&e("infra:prisma"),a("drizzle-orm")&&e("infra:drizzle"),a("typeorm")&&e("infra:typeorm"),(a("aws-sdk")||d("@aws-sdk/"))&&e("infra:aws"),(d("@google-cloud/")||a("googleapis"))&&e("infra:gcp"),d("@azure/")&&e("infra:azure"),(d("@cloudflare/")||a("wrangler"))&&e("infra:cloudflare"),(a("@vercel/node")||a("@vercel/kv")||a("@vercel/blob"))&&e("infra:vercel"),(a("firebase")||a("firebase-admin"))&&e("infra:firebase"),a("@supabase/supabase-js")&&e("infra:supabase"),a("@neondatabase/serverless")&&e("infra:neon"),a("@planetscale/database")&&e("infra:planetscale"),d("@upstash/")&&e("infra:upstash"),a("@tursodatabase/api")&&e("infra:turso"),a("modal")&&e("infra:modal"),a("replicate")&&e("infra:replicate"),(a("kafkajs")||a("node-rdkafka"))&&e("infra:kafka"),(a("amqplib")||a("rabbitmq-client"))&&e("infra:rabbitmq"),a("nats")&&e("infra:nats"),(d("@aws-sdk/client-sqs")||a("sqs-consumer"))&&e("infra:sqs"),a("@google-cloud/pubsub")&&e("infra:pubsub"),d("@temporalio/")&&e("infra:temporal"),(a("bullmq")||a("bull"))&&e("infra:bullmq"),d("@sentry/")&&e("infra:sentry"),(d("@datadog/")||a("dd-trace"))&&e("infra:datadog"),d("@opentelemetry/")&&e("infra:opentelemetry"),a("newrelic")&&e("infra:newrelic"),(a("posthog-node")||a("posthog-js"))&&e("infra:posthog"),d("@honeycombio/")&&e("infra:honeycomb"),a("prom-client")&&e("infra:prometheus"),(a("stripe")||a("@stripe/stripe-js"))&&e("infra:stripe"),d("@paddle/")&&e("infra:paddle"),d("@clerk/")&&e("infra:clerk"),(a("auth0")||d("@auth0/"))&&e("infra:auth0"),(a("next-auth")||d("@auth/"))&&e("infra:nextauth"),a("twilio")&&e("infra:twilio"),a("@sendgrid/mail")&&e("infra:sendgrid"),a("resend")&&e("infra:resend"),a("postmark")&&e("infra:postmark"),d("@pulumi/")&&e("infra:pulumi"),n("requirements.txt")||n("pyproject.toml")||n("setup.py")||n("Pipfile")){let i=(c("requirements.txt")+c("pyproject.toml")+c("Pipfile")+c("setup.py")).toLowerCase();(i.includes("psycopg")||i.includes("asyncpg"))&&e("infra:postgres"),(i.includes("pymysql")||i.includes("aiomysql")||i.includes("mysqlclient"))&&e("infra:mysql"),(i.includes("redis")||i.includes("aioredis"))&&e("infra:redis"),(i.includes("pymongo")||i.includes("motor")||i.includes("mongoengine"))&&e("infra:mongodb"),i.includes("elasticsearch")&&e("infra:elasticsearch"),i.includes("clickhouse")&&e("infra:clickhouse"),i.includes("duckdb")&&e("infra:duckdb"),i.includes("neo4j")&&e("infra:neo4j"),i.includes("snowflake")&&e("infra:snowflake"),i.includes("qdrant-client")&&e("infra:qdrant"),i.includes("pinecone")&&e("infra:pinecone"),i.includes("chromadb")&&e("infra:chromadb"),i.includes("pymilvus")&&e("infra:milvus"),i.includes("sqlalchemy")&&e("infra:sqlalchemy"),(i.includes("boto3")||i.includes("botocore"))&&e("infra:aws"),i.includes("google-cloud")&&e("infra:gcp"),i.includes("azure-")&&e("infra:azure"),i.includes("supabase")&&e("infra:supabase"),(i.includes("confluent-kafka")||i.includes("aiokafka")||i.includes("kafka-python"))&&e("infra:kafka"),(i.includes("pika")||i.includes("aio-pika"))&&e("infra:rabbitmq"),i.includes("temporalio")&&e("infra:temporal"),i.includes("sentry-sdk")&&e("infra:sentry"),(i.includes("ddtrace")||i.includes("datadog"))&&e("infra:datadog"),i.includes("opentelemetry")&&e("infra:opentelemetry"),i.includes("stripe")&&e("infra:stripe"),i.includes("twilio")&&e("infra:twilio"),i.includes("pulumi")&&e("infra:pulumi"),i.includes("ansible")&&e("infra:ansible");}if(n("go.mod")){let i=c("go.mod").toLowerCase();(i.includes("lib/pq")||i.includes("jackc/pgx"))&&e("infra:postgres"),i.includes("go-sql-driver/mysql")&&e("infra:mysql"),(i.includes("go-redis")||i.includes("redis/go-redis"))&&e("infra:redis"),i.includes("go.mongodb.org/mongo-driver")&&e("infra:mongodb"),i.includes("aws/aws-sdk-go")&&e("infra:aws"),i.includes("cloud.google.com/go")&&e("infra:gcp"),(i.includes("segmentio/kafka-go")||i.includes("sarama"))&&e("infra:kafka"),i.includes("getsentry/sentry-go")&&e("infra:sentry"),i.includes("go.opentelemetry.io")&&e("infra:opentelemetry"),i.includes("stripe/stripe-go")&&e("infra:stripe"),i.includes("hashicorp/terraform")&&e("infra:terraform"),i.includes("k8s.io/client-go")&&e("infra:kubernetes");}(n("Dockerfile")||n("docker-compose.yml")||n("docker-compose.yaml")||n("compose.yaml")||n("compose.yml")||n(".dockerignore"))&&e("infra:docker"),(n("Containerfile")||n("podman-compose.yml"))&&e("infra:podman"),r.some(i=>i.endsWith(".tf")||i===".terraform.lock.hcl")&&e("infra:terraform"),(n("Pulumi.yaml")||n("Pulumi.yml"))&&e("infra:pulumi"),(n("ansible.cfg")||n("playbook.yml")||n("playbook.yaml"))&&e("infra:ansible"),(n("kustomization.yaml")||n("kustomization.yml")||n("k8s")||n("kubernetes")||n("skaffold.yaml"))&&e("infra:kubernetes"),(n("Chart.yaml")||n("helmfile.yaml"))&&(e("infra:helm"),e("infra:kubernetes")),r.some(i=>i.endsWith(".nomad")||i.endsWith(".nomad.hcl"))&&e("infra:nomad"),(n("vercel.json")||n(".vercel"))&&e("infra:vercel"),(n("netlify.toml")||n(".netlify"))&&e("infra:netlify"),n("fly.toml")&&e("infra:fly"),(n("railway.json")||n("railway.toml"))&&e("infra:railway"),n("render.yaml")&&e("infra:render"),n("Procfile")&&e("infra:heroku"),(n("wrangler.toml")||n("wrangler.jsonc")||n("wrangler.json"))&&e("infra:cloudflare"),n("supabase")&&e("infra:supabase"),(n("firebase.json")||n(".firebaserc"))&&e("infra:firebase"),(n("serverless.yml")||n("serverless.yaml")||n("template.yaml")||n("samconfig.toml"))&&e("infra:aws"),(n("prisma")||n("schema.prisma"))&&e("infra:prisma"),(n("drizzle.config.ts")||n("drizzle.config.js"))&&e("infra:drizzle");let s=false;try{s=n(".github")&&h__namespace.existsSync(y__namespace.join(t,".github","workflows"));}catch{s=false;}s&&e("infra:github-actions"),(n(".gitlab-ci.yml")||n(".gitlab-ci.yaml"))&&e("infra:gitlab-ci"),n(".circleci")&&e("infra:circleci"),n("Jenkinsfile")&&e("infra:jenkins");{let i=(c("Dockerfile")+c("docker-compose.yml")+c("docker-compose.yaml")+c("compose.yaml")+c("compose.yml")).toLowerCase();i&&((i.includes("postgres")||i.includes("pgvector"))&&e("infra:postgres"),i.includes("timescale")&&e("infra:timescaledb"),i.includes("mysql")&&e("infra:mysql"),i.includes("mariadb")&&e("infra:mariadb"),i.includes("redis")&&e("infra:redis"),i.includes("mongo")&&e("infra:mongodb"),i.includes("cassandra")&&e("infra:cassandra"),i.includes("cockroach")&&e("infra:cockroachdb"),i.includes("clickhouse")&&e("infra:clickhouse"),i.includes("elasticsearch")&&e("infra:elasticsearch"),i.includes("neo4j")&&e("infra:neo4j"),i.includes("qdrant")&&e("infra:qdrant"),i.includes("rabbitmq")&&e("infra:rabbitmq"),(i.includes("kafka")||i.includes("redpanda"))&&e("infra:kafka"),i.includes("nats")&&e("infra:nats"),i.includes("grafana")&&e("infra:grafana"),(i.includes("prometheus")||i.includes("prom/"))&&e("infra:prometheus"));}}{let i=(...w)=>w.some(a),b=(c("requirements.txt")+c("pyproject.toml")+c("Pipfile")+c("setup.py")+c("environment.yml")).toLowerCase(),g=c("go.mod").toLowerCase(),m=c("Cargo.toml").toLowerCase(),l=w=>b.includes(w),I=w=>r.some(de=>de.toLowerCase().endsWith(w)),k=(...w)=>w.some(de=>n(de)),j=()=>Array.from(o).some(w=>w.startsWith("type:")),ue=()=>Array.from(o).some(w=>w.startsWith("fw:"));(a("@modelcontextprotocol/sdk")||l("modelcontextprotocol")||l("fastmcp")||g.includes("modelcontextprotocol")||k("mcp.json",".mcp.json"))&&e("type:mcp-server"),(i("langgraph","@langchain/langgraph","crewai","autogen","@mastra/core","@openai/agents","@langchain/core")||l("langgraph")||l("crewai")||l("autogen")||l("pyautogen")||l("smolagents")||l("haystack"))&&e("type:agent-framework"),(i("ai","openai","@anthropic-ai/sdk","@google/generative-ai","@ai-sdk/openai","@ai-sdk/anthropic","langchain","@huggingface/inference","cohere-ai","ollama","groq-sdk","@mistralai/mistralai")||l("openai")||l("anthropic")||l("langchain")||l("litellm")||l("google-generativeai")||l("cohere")||l("ollama"))&&e("type:ai-app"),(I(".sol")||k("hardhat.config.js","hardhat.config.ts","foundry.toml","truffle-config.js","Anchor.toml","Move.toml")||i("hardhat","ethers","web3","@solana/web3.js","wagmi","viem","@openzeppelin/contracts"))&&e("type:smart-contract"),(k("project.godot","ProjectSettings")||I(".unity")||I(".uproject")||i("phaser","kaplay","kaboom","excalibur","playcanvas")||m.includes("bevy")||m.includes("macroquad")||m.includes("ggez")||l("pygame")||l("arcade"))&&e("type:game");{let w=f("manifest.json");(w&&Object.prototype.hasOwnProperty.call(w,"manifest_version")||i("webextension-polyfill","@types/chrome","wxt","plasmo"))&&e("type:browser-extension");}(i("react-native","expo","nativescript")||n("pubspec.yaml")||I(".xcodeproj")||k("AndroidManifest.xml"))&&e("type:mobile-app"),(i("electron","@tauri-apps/api","@tauri-apps/cli","nw")||k("tauri.conf.json","src-tauri")||m.includes("tauri")||m.includes("egui")||l("pyqt5")||l("pyqt6")||l("pyside6")||l("kivy"))&&e("type:desktop-app"),(i("discord.js","telegraf","node-telegram-bot-api","@slack/bolt","probot","grammy")||l("discord.py")||l("python-telegram-bot")||l("slack-bolt")||l("slack_bolt")||l("aiogram")||l("pyrogram"))&&e("type:bot"),(k("dbt_project.yml","dagster.yaml")||i("@dagster-io/dagster","apache-airflow")||l("airflow")||l("dagster")||l("prefect")||l("dbt-core")||l("luigi")||l("kedro")||l("pyspark")||l("apache-beam"))&&e("type:data-pipeline"),(l("torch")||l("tensorflow")||l("keras")||l("jax")||l("scikit-learn")||l("sklearn")||l("xgboost")||l("lightgbm")||l("pytorch-lightning")||l("diffusers")||l("mlflow"))&&e("type:ml-model"),(I(".ipynb")||l("jupyter")||l("jupyterlab")||l("marimo")||n("notebooks"))&&e("type:notebook"),(k("mkdocs.yml","mkdocs.yaml","mint.json","docusaurus.config.js","docusaurus.config.ts","book.toml")||i("@docusaurus/core","vitepress","vuepress","nextra","@astrojs/starlight")||l("mkdocs")||l("sphinx"))&&e("type:documentation"),(k("hugo.toml","_config.yml",".eleventy.js","eleventy.config.js","astro.config.mjs","astro.config.ts","astro.config.js")||i("astro","gatsby","@11ty/eleventy","hexo","gridsome")||l("pelican"))&&e("type:static-site"),i("@medusajs/medusa","@saleor/sdk","@shopify/hydrogen","vendure","@vendure/core","snipcart","use-shopping-cart","swell-js")&&e("type:ecommerce"),(p.bin||i("commander","yargs","oclif","@oclif/core","cac","meow","inquirer","@clack/prompts","ink")||l("click")||l("typer")||l("docopt")||g.includes("spf13/cobra")||g.includes("urfave/cli")||m.includes("clap")||m.includes("structopt"))&&e("type:cli"),(k("pnpm-workspace.yaml","turbo.json","nx.json","lerna.json","rush.json")||Array.isArray(p.workspaces)||m.includes("[workspace]")||n("go.work"))&&e("type:monorepo");let T=i("next","react","vue","@angular/core","svelte","@sveltejs/kit","solid-js","nuxt","remix","@remix-run/react","preact","qwik"),R=i("express","fastify","@nestjs/core","koa","hapi","@hapi/hapi","hono")||l("fastapi")||l("django")||l("flask")||l("starlette")||l("sanic")||g.includes("gin-gonic/gin")||g.includes("labstack/echo")||g.includes("gofiber/fiber")||m.includes("axum")||m.includes("actix-web")||(c("pom.xml")+c("build.gradle")).toLowerCase().includes("spring-boot"),Ee=Array.from(o).some(w=>["infra:postgres","infra:mysql","infra:mongodb","infra:supabase","infra:neon"].includes(w)),Oe=i("next-auth","@clerk/nextjs","@auth0/auth0-react","passport","lucia","@workos-inc/node")||l("django-allauth")||l("flask-login"),Ae=i("stripe","@stripe/stripe-js","@paddle/paddle-js","@lemonsqueezy/lemonsqueezy.js")||l("stripe");(!T&&!R&&(p.main||p.exports||p.module||p.types||p.publishConfig)||n("Cargo.toml")&&!m.includes("[[bin]]")&&m.includes("[lib]")||k("LICENSE","LICENSE.md","LICENSE.txt")&&!T&&!R&&!j())&&!j()&&e("type:library"),T?(Ee&&(Oe||Ae)&&e("type:saas"),e("type:web-app")):R&&(Ee&&(Oe||Ae)&&e("type:saas"),e("type:api-service")),j()||(ue()?e("type:web-app"):k("Dockerfile","docker-compose.yml","compose.yaml")||r.some(w=>w.endsWith(".tf"))||k("Chart.yaml","kustomization.yaml","wrangler.toml","serverless.yml",".github")||i("@pulumi/pulumi","aws-cdk-lib","cdktf")?e("type:devops-tool"):n("package.json")&&(p.main||p.exports)&&e("type:library"));}return Array.from(o)}function He(t){let o={sponsorLabel:t.sponsorLabel,title:t.creative.title,body:t.creative.body,url:t.clickUrl};return t.creative.cta!==void 0&&(o.cta=t.creative.cta),o}function Ue(t){return {sponsorLabel:"",title:t.title,body:t.body,url:t.url}}function V(t){let o=He(t),e=t.creative;switch(e.format){case "image":case "gif":return {...o,body:e.textFallback??o.body};case "video":return {...o,body:e.textFallback??o.body,cta:o.cta??"\u25B6 Watch"};case "audio":return {...o,body:e.textFallback??o.body,cta:o.cta??"\u{1F50A} Listen"};default:return o}}function U(t=process.env){return y__namespace.join(N__namespace.homedir(),".config","opencrater")}function Z(t=process.env){return y__namespace.join(U(t),"state.json")}function X(){return {installId:crypto.randomUUID(),lastShownAt:0,optOut:false,disclosureShown:false,cachedConfig:null,configFetchedAt:0,pool:[],allowedPlacements:{},sessionTopics:[],integrations:[],devToken:null,computeRouting:null,computeCards:null}}function E(t){return typeof t=="number"&&Number.isFinite(t)}var Fe=new Set(["EPERM","EACCES","EBUSY","EEXIST"]);function qe(t){for(let o=0;;o++)try{return {text:h__namespace.readFileSync(t,"utf8")}}catch(e){let r=e.code??"";if(!(r==="ENOENT"||Fe.has(r)))return {locked:true};if(o>=4)return r==="ENOENT"?{missing:true}:{locked:true};try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(o+1));}catch{}}}function vt(t){if(typeof t!="object"||t===null)return null;let o=t;return !E(o.minIntervalSeconds)||!E(o.serveTimeoutMs)||!E(o.preloadPoolSize)||typeof o.killSwitch!="boolean"?null:{minIntervalSeconds:o.minIntervalSeconds,serveTimeoutMs:o.serveTimeoutMs,preloadPoolSize:o.preloadPoolSize,killSwitch:o.killSwitch,displayDurationSeconds:E(o.displayDurationSeconds)?o.displayDurationSeconds:25,minSdkVersion:typeof o.minSdkVersion=="string"?o.minSdkVersion:""}}function xt(t){if(!Array.isArray(t))return [];let o=[];for(let e of t){if(typeof e!="object"||e===null)continue;let r=e,n=r.blip;if(!E(r.renderBy)||typeof n!="object"||n===null||typeof n.impressionId!="string"||typeof n.clickUrl!="string"||typeof n.sponsorLabel!="string"||typeof n.creative!="object"||n.creative===null)continue;let c=n.creative;typeof c.title!="string"||typeof c.body!="string"||o.push({blip:{impressionId:n.impressionId,...typeof n.campaignId=="string"?{campaignId:n.campaignId}:{},clickUrl:n.clickUrl,sponsorLabel:n.sponsorLabel,creative:{format:"text",title:c.title,body:c.body,...typeof c.cta=="string"?{cta:c.cta}:{}}},renderBy:r.renderBy});}return o}function Ct(t){if(typeof t!="object"||t===null||Array.isArray(t))return {};let o={};for(let[e,r]of Object.entries(t)){if(!Array.isArray(r))continue;let n=r.filter(c=>typeof c=="string"&&c.length<=64);o[e]=n.slice(0,64);}return o}function Tt(t){if(!Array.isArray(t))return [];let o=[];for(let e of t){if(typeof e!="object"||e===null)continue;let r=e;if(!(typeof r.topic!="string"||!E(r.at))&&(o.push({topic:r.topic.slice(0,32),at:r.at}),o.length>=24))break}return o}function jt(t){if(!Array.isArray(t))return [];let o=[],e=new Set;for(let r of t){if(typeof r!="object"||r===null)continue;let n=r;if(typeof n.key!="string"||typeof n.package!="string"||n.key===""||n.package==="")continue;let c=`${n.package}\0${n.key}`;if(!e.has(c)&&(e.add(c),o.push({key:n.key,package:n.package}),o.length>=32))break}return o}function Rt(t){if(typeof t!="object"||t===null)return null;let o=t,e={};if(typeof o.savedEnv=="object"&&o.savedEnv!==null)for(let[r,n]of Object.entries(o.savedEnv))(typeof n=="string"||n===null)&&(e[r]=n);return {active:o.active===true,savedEnv:e}}function Et(t){if(typeof t!="object"||t===null)return null;let o=t,e=r=>E(r)&&r>=0?r:0;return {turns:e(o.turns),lastLimitAt:e(o.lastLimitAt),lastDepletedAt:e(o.lastDepletedAt),lastBackupAt:e(o.lastBackupAt)}}function Ot(t){let o=t.attrTagsAt,e=t.attrTagsCwd;return !E(o)||Date.now()-o>Y||typeof e!="string"||e.length===0||e.length>64?{}:{attrTags:Array.isArray(t.attrTags)?t.attrTags.filter(n=>typeof n=="string"&&n.length<=40).slice(0,48):[],attrTagsCwd:e,attrTagsAt:o}}function At(t){let o=X();if(typeof t!="object"||t===null)return o;let e=t;return {installId:typeof e.installId=="string"&&e.installId.length>0?e.installId:o.installId,lastShownAt:E(e.lastShownAt)&&e.lastShownAt>=0?e.lastShownAt:0,optOut:e.optOut===true,disclosureShown:e.disclosureShown===true,cachedConfig:vt(e.cachedConfig),allowedPlacements:Ct(e.allowedPlacements),sessionTopics:Tt(e.sessionTopics),integrations:jt(e.integrations),devToken:typeof e.devToken=="string"?e.devToken:null,computeRouting:Rt(e.computeRouting),computeCards:Et(e.computeCards),configFetchedAt:E(e.configFetchedAt)&&e.configFetchedAt>=0?e.configFetchedAt:0,pool:xt(e.pool),...Ot(e)}}function me(t=process.env){let o=Z(t),e=qe(o);if(e.text!==void 0)try{return At(JSON.parse(e.text))}catch{let r=X();try{C(r,t);}catch{}return r}if(e.missing){let r=X();try{C(r,t);}catch{}return r}return X()}function C(t,o=process.env,e={}){let r=Z(o),n=y__namespace.dirname(r);h__namespace.mkdirSync(n,{recursive:true});let c=qe(r),f=null;if(c.text!==void 0)try{f=JSON.parse(c.text);}catch{f=null;}if(f)typeof f.lastShownAt=="number"&&f.lastShownAt>t.lastShownAt&&(t={...t,lastShownAt:f.lastShownAt}),!e.allowClearToken&&typeof f.devToken=="string"&&t.devToken==null&&(t={...t,devToken:f.devToken}),typeof f.installId=="string"&&f.installId.length>0&&f.installId!==t.installId&&(t={...t,installId:f.installId});else if(!e.allowClearToken&&t.devToken==null&&c.text===void 0&&!c.missing)return;let p=y__namespace.join(n,`.state.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`);h__namespace.writeFileSync(p,JSON.stringify(t,null,2)+`
5
- `,"utf8");for(let u=0;;u++)try{h__namespace.renameSync(p,r);return}catch(a){let d=a.code??"";if(u>=4||!Fe.has(d)){try{h__namespace.rmSync(p,{force:!0});}catch{}if(u>=4)return;throw a}try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(u+1));}catch{}}}var _t=300*1e3;function It(){return y__namespace.join(U(),"blocked-ads.json")}function ge(){return y__namespace.join(U(),"recent-renders.json")}function Pt(){return y__namespace.join(U(),"reported-ads.json")}function Ge(t,o){let e={};for(let[r,n]of Object.entries(t))typeof n=="number"&&Number.isFinite(n)&&n>o&&(e[r]=n);return e}function Nt(t){try{let o=JSON.parse(h__namespace.readFileSync(It(),"utf8"));return Ge(o&&typeof o=="object"?o:{},t)}catch{return {}}}function $t(){try{let t=JSON.parse(h__namespace.readFileSync(Pt(),"utf8"));return t&&typeof t=="object"?t:{}}catch{return {}}}function Mt(t){return t?$t()[t]!==void 0:false}function Q(t,o=Date.now()){return t?Nt(o)[t]!==void 0||Mt(t):false}function ze(t){try{let o=JSON.parse(h__namespace.readFileSync(ge(),"utf8"));return Ge(o&&typeof o=="object"?o:{},t)}catch{return {}}}function ee(t,o=Date.now()){if(t)try{let e=ze(o);e[t]=o+_t,h__namespace.mkdirSync(y__namespace.dirname(ge()),{recursive:!0}),h__namespace.writeFileSync(ge(),JSON.stringify(e));}catch{}}function te(t,o=Date.now()){return t?ze(o)[t]!==void 0:false}function Lt(t,o){return t.filter(e=>e.renderBy>o)}function he(t,o){let e=Lt(t.pool,o),r=e.shift();return {blip:r?r.blip:null,pool:e}}var Dt=["claude_code","codex","antigravity","copilot_cli","grok_cli"];function be(t){return t.includes("opencrater-hook")||/opencrater[\\/][^"']*hook\.js/.test(t)}function Wt(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ht(t,o){return be(t)&&new RegExp(`--package ['"]?${Wt(o)}['"]?`).test(t)}function ke(t,o){return o?Ht(t,o):be(t)&&!/--package\b/.test(t)}function ne(t){return /^[A-Za-z0-9@_./:-]+$/.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}var oe='"$HOME/.config/opencrater/runtime/node_modules/opencrater/dist/hook.js"',Je="$env:USERPROFILE\\.config\\opencrater\\runtime\\node_modules\\opencrater\\dist\\hook.js";function B(t,o,e,r){let n=`--placement ${o}`;return e&&(n+=` --key ${ne(e)}`),r&&(n+=` --package ${ne(r)}`),n+=` --host ${t}`,`{ if [ -f ${oe} ]; then node ${oe} ${n}; else npx -y -p opencrater opencrater-hook ${n}; fi; } 2>/dev/null || true`}function Ut(t,o,e){if(process.platform!=="win32")return B("grok_cli",t,o,e);let r=`--placement ${t}`;o&&(r+=` --key ${o}`),e&&(r+=` --package ${e}`),r+=" --host grok_cli";let n=`${N__namespace.homedir()}\\.config\\opencrater\\runtime\\node_modules\\opencrater\\dist\\hook.js`;return `try { if (Test-Path "${n}") { node "${n}" ${r} } else { npx -y -p opencrater opencrater-hook ${r} } } catch {}`}function Bt(t,o,e){if(process.platform==="win32"){let n=`--placement ${t}`;o&&(n+=` --key ${o}`),e&&(n+=` --package ${e}`),n+=" --host antigravity";let c=`${N__namespace.homedir()}\\.config\\opencrater\\runtime\\node_modules\\opencrater\\dist\\hook.js`;return `( if exist "${c}" ( node "${c}" ${n} ) else ( npx -y -p opencrater opencrater-hook ${n} ) ) >NUL 2>&1 & echo {"decision":"allow"}`}let r=`--placement ${t}`;return o&&(r+=` --key ${ne(o)}`),e&&(r+=` --package ${ne(e)}`),r+=" --host antigravity",`{ if [ -f ${oe} ]; then node ${oe} ${r}; else npx -y -p opencrater opencrater-hook ${r}; fi; } >/dev/null 2>&1; echo '{"decision":"allow"}'`}function Ye(t,o,e,r){let n=`--placement ${o}`;return e&&(n+=` --key '${e}'`),r&&(n+=` --package '${r}'`),n+=` --host ${t}`,`try { if (Test-Path "${Je}") { node "${Je}" ${n} } else { npx -y -p opencrater opencrater-hook ${n} } } catch {}`}function Ft(t,o,e){if(process.platform!=="win32")return B("claude_code",t,o,e);let r=`--placement ${t}`;return o&&(r+=` --key ${o}`),e&&(r+=` --package ${e}`),r+=" --host claude_code",`node "${`${N__namespace.homedir()}\\.config\\opencrater\\runtime\\node_modules\\opencrater\\dist\\hook.js`}" ${r}; exit 0`}function ye(t,o,e,r){if(t==="grok_cli")return {type:"command",command:Ut(o,e,r),timeout:15};let c={type:"command",command:t==="claude_code"?Ft(o,e,r):B(t,o,e,r)};return t==="codex"&&(c.commandWindows=Ye(t,o,e,r)),c}function re(t,o){let e=N__namespace.homedir();switch(t){case "claude_code":{let r=o.CLAUDE_CONFIG_DIR;return r&&r.trim()!==""?r:y__namespace.join(e,".claude")}case "codex":{let r=o.CODEX_HOME;return r&&r.trim()!==""?r:y__namespace.join(e,".codex")}case "antigravity":return y__namespace.join(e,".gemini");case "copilot_cli":{let r=o.COPILOT_HOME;return r&&r.trim()!==""?r:y__namespace.join(e,".copilot")}case "grok_cli":{let r=o.GROK_HOME;return r&&r.trim()!==""?r:y__namespace.join(e,".grok")}default:return y__namespace.join(e,".opencrater-unknown")}}function q(t,o=process.env){let e=re(t,o);switch(t){case "claude_code":return y__namespace.join(e,"settings.json");case "codex":return y__namespace.join(e,"hooks.json");case "antigravity":return y__namespace.join(e,"config","hooks.json");case "copilot_cli":return y__namespace.join(e,"hooks","hooks.json");case "grok_cli":return y__namespace.join(e,"hooks","opencrater.json");default:return y__namespace.join(e,"hooks.json")}}var qt={claude_code:["claude"],codex:["codex"],antigravity:["agy"],copilot_cli:["copilot"],grok_cli:["grok"]};function Gt(t,o){if(t.length===0)return false;let e=(o.PATH??o.Path??"").split(y__namespace.delimiter).filter(Boolean),r=process.platform==="win32"?["",".exe",".cmd",".bat"]:[""];for(let n of e)for(let c of t)for(let f of r)try{if(h__namespace.existsSync(y__namespace.join(n,c+f)))return !0}catch{}return false}function zt(t,o=process.env){try{if(h__namespace.existsSync(re(t,o)))return !0}catch{}return Gt(qt[t]??[],o)}function we(t=process.env){return Dt.filter(o=>zt(o,t))}function ie(t){let o;try{o=h__namespace.readFileSync(t,"utf8");}catch{return {}}let e=JSON.parse(o);if(typeof e!="object"||e===null||Array.isArray(e))throw new Error(`${t} is not a JSON object`);return e}function se(t,o){let e=y__namespace.dirname(t);h__namespace.mkdirSync(e,{recursive:true});let r=y__namespace.join(e,`.${y__namespace.basename(t)}.${process.pid}.tmp`);h__namespace.writeFileSync(r,JSON.stringify(o,null,2)+`
6
- `,"utf8"),h__namespace.renameSync(r,t);}function Jt(t,o){return Array.isArray(t.hooks)&&t.hooks.some(e=>typeof e.command=="string"&&ke(e.command,o))}function Kt(t,o,e,r){let n=q(t),c=ie(n),f=c.hooks&&typeof c.hooks=="object"?c.hooks:{};if(r.every(u=>{let a=ye(t,u,o,e);return (Array.isArray(f[u])?f[u]:[]).some(d=>Array.isArray(d.hooks)&&d.hooks.some(s=>s.command===a.command&&s.commandWindows===a.commandWindows))}))return "nochange";for(let u of r){let d=(Array.isArray(f[u])?f[u]:[]).filter(i=>!Jt(i,e)),s=t==="grok_cli"?{hooks:[ye(t,u,o,e)]}:{matcher:"",hooks:[ye(t,u,o,e)]};d.push(s),f[u]=d;}return c.hooks=f,se(n,c),"wrote"}var Yt=15;function Vt(t){return t?`opencrater-${t}`:"opencrater-compute"}function Xt(t,o){if(!t||typeof t!="object")return false;for(let e of Object.values(t))for(let r of Array.isArray(e)?e:[])if(Array.isArray(r.hooks)&&r.hooks.some(n=>typeof n.command=="string"&&ke(n.command,o)))return true;return false}function Zt(t){try{let o=y__namespace.join(re("antigravity",t),"settings.json"),e;try{e=ie(o);}catch{return}let r=!1,n=e.hooks;if(n&&typeof n=="object"&&!Array.isArray(n)){let c=n;for(let f of Object.keys(c)){let p=Array.isArray(c[f])?c[f]:[],u=p.filter(a=>!(Array.isArray(a.hooks)&&a.hooks.some(d=>typeof d.command=="string"&&be(d.command))));u.length!==p.length&&(r=!0,u.length>0?c[f]=u:delete c[f]);}Object.keys(c).length===0&&(delete e.hooks,r=!0);}e["json-hooks-enabled"]===!0&&(delete e["json-hooks-enabled"],r=!0),r&&se(o,e);}catch{}}function Qt(t,o,e){let r=q("antigravity"),n=ie(r),c=Vt(o),f={};for(let a of e)f[a]=[{hooks:[{type:"command",command:Bt(a,t,o),timeout:Yt}]}];let p=JSON.stringify(f),u=false;JSON.stringify(n[c]??null)!==p&&(n[c]=f,u=true);for(let a of Object.keys(n))a!==c&&Xt(n[a],o)&&(delete n[a],u=true);return Zt(process.env),u?(se(r,n),"wrote"):"nochange"}var Ke=12;function en(t,o){return [t.bash,t.powershell,t.command].some(e=>typeof e=="string"&&ke(e,o))}function tn(t,o,e,r){let n=q(t),c=ie(n);typeof c.version!="number"&&(c.version=1);let f=c.hooks&&typeof c.hooks=="object"?c.hooks:{};if(r.every(u=>{let a=B(t,u,o,e);return (Array.isArray(f[u])?f[u]:[]).some(d=>d.bash===a&&d.timeoutSec===Ke)}))return "nochange";for(let u of r){let d=(Array.isArray(f[u])?f[u]:[]).filter(s=>!en(s,e));d.push({type:"command",bash:B(t,u,o,e),powershell:Ye(t,u,o,e),timeoutSec:Ke}),f[u]=d;}return c.hooks=f,se(n,c),"wrote"}function Ve(t){return [...Ie[t]]}function nn(t){let o=t;for(let e of ["claude","cursor"]){if(new RegExp(`^\\s*\\[compat\\.${e}\\]`,"m").test(o))continue;let r=o.length===0?"":o.endsWith(`
2
+ 'use strict';var child_process=require('child_process'),g=require('fs'),N=require('os'),y=require('path'),crypto=require('crypto');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 g__namespace=/*#__PURE__*/_interopNamespace(g);var N__namespace=/*#__PURE__*/_interopNamespace(N);var y__namespace=/*#__PURE__*/_interopNamespace(y);var M=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(o,e)=>(typeof require<"u"?require:o)[e]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var H={minIntervalSeconds:600,serveTimeoutMs:2500,preloadPoolSize:3,killSwitch:false,displayDurationSeconds:25,minSdkVersion:""},_e={claude_code:["SessionStart","Stop","SessionEnd","Notification"],codex:["Stop"],openclaw:[],antigravity:["Stop"],copilot_cli:["agentStop","sessionStart","sessionEnd","notification"],grok_cli:["SessionStart","Stop","SessionEnd","Notification"],generic:["SessionStart","Stop"]},Ie={claude_code:["SessionStart","Stop","SessionEnd","Notification","UserPromptSubmit","SubagentStart","SubagentStop","StopFailure","PreToolUse","PostToolUse","PostToolUseFailure","PostToolBatch","PermissionRequest","PermissionDenied","UserPromptExpansion","PreCompact","PostCompact","TaskCreated","TaskCompleted","Setup","TeammateIdle","Elicitation","ElicitationResult","ConfigChange","InstructionsLoaded","WorktreeCreate","WorktreeRemove","CwdChanged","FileChanged","MessageDisplay"],codex:["Stop","SessionStart","UserPromptSubmit","PreToolUse","PostToolUse","PermissionRequest","PreCompact","PostCompact"],openclaw:[],antigravity:["PreToolUse","PostToolUse","PreInvocation","PostInvocation","Stop"],copilot_cli:["agentStop","sessionStart","sessionEnd","notification","userPromptSubmitted","preToolUse","postToolUse","permissionRequest","errorOccurred","subagentStart","subagentStop"],grok_cli:["SessionStart","Stop","SessionEnd","Notification"],generic:["SessionStart","Stop"]};var _="1.4.7";var yt="https://api.opencrater.to";function K(t,o=process.env){let e=o.OPENCRATER_API_ORIGIN;return ((e&&e.trim()!==""?e:yt)).replace(/\/+$/,"")}function x(...t){try{if(process.env.OPENCRATER_DEBUG!=="1")return;console.error("[opencrater]",...t);try{let o=M("os"),e=M("fs"),r=M("path");e.appendFileSync(r.join(o.homedir(),".config","opencrater","hook.log"),`${new Date().toISOString()} [opencrater] ${t.map(n=>String(n)).join(" ")}
3
+ `);}catch{}}catch{}}function J(t){return typeof t=="number"&&Number.isFinite(t)}function bt(t){let o=H;if(typeof t!="object"||t===null)return {...o};let e=t;return {minIntervalSeconds:J(e.minIntervalSeconds)?e.minIntervalSeconds:o.minIntervalSeconds,serveTimeoutMs:J(e.serveTimeoutMs)?e.serveTimeoutMs:o.serveTimeoutMs,preloadPoolSize:J(e.preloadPoolSize)?e.preloadPoolSize:o.preloadPoolSize,killSwitch:e.killSwitch===true,displayDurationSeconds:J(e.displayDurationSeconds)?e.displayDurationSeconds:o.displayDurationSeconds,minSdkVersion:typeof e.minSdkVersion=="string"?e.minSdkVersion:o.minSdkVersion}}async function Pe(t,o,e,r,n){try{let c=await fetch(`${t}${o}`,{method:"POST",headers:{"content-type":"application/json",...n??{}},body:JSON.stringify(e),signal:AbortSignal.timeout(r)});return c.ok?await c.json():(x(`POST ${o} -> HTTP ${c.status}`),null)}catch(c){return x(`POST ${o} failed:`,c),null}}function Ne(t,o){let e=t.host??"generic";return {publisherKey:t.publisherKey,packageName:t.packageName,placement:t.placement,host:e,sdkVersion:_,installId:o.installId,os:process.platform,termProgram:process.env.TERM_PROGRAM??void 0,topics:o.topics&&o.topics.length>0?o.topics:void 0,tags:o.tags&&o.tags.length>0?o.tags:void 0}}function $e(t){if(typeof t!="object"||t===null)return null;let o=t;if(typeof o.fill!="boolean")return null;let e={fill:o.fill,fallback:o.fallback??null,config:bt(o.config),...Array.isArray(o.allowedPlacements)?{allowedPlacements:o.allowedPlacements.filter(r=>typeof r=="string")}:{}};return o.blip!==void 0&&o.blip!==null&&(e.blip=o.blip),typeof o.computeBalanceMicroUsd=="number"&&(e.computeBalanceMicroUsd=o.computeBalanceMicroUsd),typeof o.weeklyGrantMicroUsd=="number"&&(e.weeklyGrantMicroUsd=o.weeklyGrantMicroUsd),typeof o.pendingMicroUsd=="number"&&(e.pendingMicroUsd=o.pendingMicroUsd),e}async function Me(t,o){let e=await Pe(o.origin,"/v1/serve",Ne(t,o),o.timeoutMs);return $e(e)}async function Le(t,o,e){let r={...Ne(o,e),publisherKey:o.publisherKey??"",packageName:o.packageName??""},n=await Pe(e.origin,"/v1/dev/serve",r,e.timeoutMs,{authorization:`Bearer ${t}`});return $e(n)}var wt=48,Y=360*60*1e3;function De(t){return crypto.createHash("sha256").update(t).digest("hex").slice(0,16)}function We(t){let o=new Set,e=s=>{o.size<wt&&o.add(s);},r=[];try{r=g__namespace.readdirSync(t);}catch{return []}let n=s=>r.includes(s),c=s=>{try{return g__namespace.readFileSync(y__namespace.join(t,s),"utf8")}catch{return ""}},f=s=>{try{return JSON.parse(c(s))}catch{return null}},p=f("package.json")??{},u={...p.dependencies??{},...p.devDependencies??{},...p.peerDependencies??{}},a=s=>Object.prototype.hasOwnProperty.call(u,s),d=s=>Object.keys(u).some(i=>i===s||i.startsWith(s));n("package.json")&&(e("lang:javascript"),(a("typescript")||n("tsconfig.json"))&&e("lang:typescript")),(n("deno.json")||n("deno.jsonc"))&&e("lang:typescript"),(n("tsconfig.json")||n("tsconfig.base.json"))&&e("lang:typescript"),n("jsconfig.json")&&e("lang:javascript"),(n("bun.lockb")||n("bun.lock"))&&e("lang:javascript"),r.some(s=>s.endsWith(".ts")||s.endsWith(".tsx")||s.endsWith(".mts")||s.endsWith(".cts"))&&e("lang:typescript"),r.some(s=>s.endsWith(".js")||s.endsWith(".jsx")||s.endsWith(".mjs")||s.endsWith(".cjs"))&&e("lang:javascript"),(n("requirements.txt")||n("pyproject.toml")||n("setup.py")||n("Pipfile"))&&e("lang:python"),(n("setup.cfg")||n("Pipfile.lock")||n("poetry.lock")||n("uv.lock")||n("environment.yml"))&&e("lang:python"),r.some(s=>s.endsWith(".py")||s.endsWith(".pyi")||s.endsWith(".ipynb"))&&e("lang:python"),(n("go.mod")||n("go.sum")||n("go.work"))&&e("lang:go"),r.some(s=>s.endsWith(".go"))&&e("lang:go"),(n("Cargo.toml")||n("Cargo.lock"))&&e("lang:rust"),r.some(s=>s.endsWith(".rs"))&&e("lang:rust"),(n("pom.xml")||n("build.gradle"))&&e("lang:java"),r.some(s=>s.endsWith(".java"))&&e("lang:java"),(n("build.gradle.kts")||n("settings.gradle.kts"))&&e("lang:kotlin"),r.some(s=>s.endsWith(".kt")||s.endsWith(".kts"))&&e("lang:kotlin"),(n("build.sbt")||n(".scalafmt.conf"))&&e("lang:scala"),r.some(s=>s.endsWith(".scala")||s.endsWith(".sc"))&&e("lang:scala"),r.some(s=>s.endsWith(".groovy")||s.endsWith(".gradle"))&&e("lang:groovy"),(n("deps.edn")||n("project.clj")||n("shadow-cljs.edn"))&&e("lang:clojure"),r.some(s=>s.endsWith(".clj")||s.endsWith(".cljs")||s.endsWith(".cljc"))&&e("lang:clojure"),r.some(s=>s.endsWith(".csproj")||s.endsWith(".sln"))&&e("lang:csharp"),r.some(s=>s.endsWith(".fsproj"))&&e("lang:fsharp"),r.some(s=>s.endsWith(".cs"))&&e("lang:csharp"),r.some(s=>s.endsWith(".fs")||s.endsWith(".fsx")||s.endsWith(".fsi"))&&e("lang:fsharp"),r.some(s=>s.endsWith(".cpp")||s.endsWith(".cc")||s.endsWith(".cxx")||s.endsWith(".hpp")||s.endsWith(".hxx"))&&e("lang:cpp"),r.some(s=>s.endsWith(".c"))&&e("lang:c"),(n("composer.json")||n("composer.lock"))&&e("lang:php"),r.some(s=>s.endsWith(".php"))&&e("lang:php"),(n("Gemfile")||n("Gemfile.lock")||n(".ruby-version")||r.some(s=>s.endsWith(".gemspec")))&&e("lang:ruby"),r.some(s=>s.endsWith(".rb")||s==="Rakefile")&&e("lang:ruby"),(n("Package.swift")||n("Podfile")||r.some(s=>s.endsWith(".xcodeproj")||s.endsWith(".xcworkspace")))&&e("lang:swift"),r.some(s=>s.endsWith(".swift"))&&e("lang:swift"),r.some(s=>s.endsWith(".m")||s.endsWith(".mm"))&&e("lang:objective-c"),(n("pubspec.yaml")||n("pubspec.yml")||n("pubspec.lock"))&&e("lang:dart"),r.some(s=>s.endsWith(".dart"))&&e("lang:dart"),(n("mix.exs")||n("mix.lock"))&&e("lang:elixir"),r.some(s=>s.endsWith(".ex")||s.endsWith(".exs"))&&e("lang:elixir"),(n("rebar.config")||n("rebar.lock"))&&e("lang:erlang"),r.some(s=>s.endsWith(".erl")||s.endsWith(".hrl"))&&e("lang:erlang"),(n("gleam.toml")||r.some(s=>s.endsWith(".gleam")))&&e("lang:gleam"),(n("stack.yaml")||n("cabal.project")||r.some(s=>s.endsWith(".cabal")||s.endsWith(".hs")))&&e("lang:haskell"),(n("dune-project")||n("dune")||r.some(s=>s.endsWith(".ml")||s.endsWith(".mli")))&&e("lang:ocaml"),(r.some(s=>s.endsWith(".rockspec")||s.endsWith(".lua"))||n(".luarc.json"))&&e("lang:lua"),(n("cpanfile")||n("Makefile.PL")||r.some(s=>s.endsWith(".pl")||s.endsWith(".pm")))&&e("lang:perl"),(n("DESCRIPTION")||n("renv.lock")||r.some(s=>s.endsWith(".Rproj")||s.endsWith(".Rmd")||s.endsWith(".R")))&&e("lang:r"),(n("Project.toml")||n("Manifest.toml")||r.some(s=>s.endsWith(".jl")))&&e("lang:julia"),(n("build.zig")||n("build.zig.zon")||r.some(s=>s.endsWith(".zig")))&&e("lang:zig"),r.some(s=>s.endsWith(".nimble")||s.endsWith(".nim"))&&e("lang:nim"),(n("shard.yml")||n("shard.lock")||r.some(s=>s.endsWith(".cr")))&&e("lang:crystal"),(n("v.mod")||r.some(s=>s.endsWith(".vsh")))&&e("lang:vlang"),r.some(s=>s.endsWith(".hx")||s.endsWith(".hxml"))&&e("lang:haxe"),(n("foundry.toml")||n("hardhat.config.js")||n("hardhat.config.ts")||r.some(s=>s.endsWith(".sol")))&&e("lang:solidity"),r.some(s=>s.endsWith(".f")||s.endsWith(".f90")||s.endsWith(".f95"))&&e("lang:fortran"),r.some(s=>s.endsWith(".cob")||s.endsWith(".cbl"))&&e("lang:cobol"),r.some(s=>s.endsWith(".asm"))&&e("lang:assembly"),r.some(s=>s.endsWith(".sh")||s.endsWith(".bash")||s.endsWith(".zsh"))&&e("lang:shell"),r.some(s=>s.endsWith(".ps1")||s.endsWith(".psm1"))&&e("lang:powershell"),r.some(s=>s.endsWith(".sql"))&&e("lang:sql"),r.some(s=>s.endsWith(".html")||s.endsWith(".htm"))&&e("lang:html"),r.some(s=>s.endsWith(".css"))&&e("lang:css"),r.some(s=>s.endsWith(".scss")||s.endsWith(".sass"))&&e("lang:scss"),r.some(s=>s.endsWith(".graphql")||s.endsWith(".gql"))&&e("lang:graphql"),r.some(s=>s.endsWith(".proto"))&&e("lang:protobuf");{if(a("react")&&e("fw:react"),a("next")&&e("fw:nextjs"),a("vue")&&e("fw:vue"),(a("nuxt")||a("nuxt3"))&&e("fw:nuxt"),a("@angular/core")&&e("fw:angular"),a("svelte")&&e("fw:svelte"),a("@sveltejs/kit")&&e("fw:sveltekit"),(a("@remix-run/react")||a("@remix-run/node"))&&e("fw:remix"),a("astro")&&e("fw:astro"),a("gatsby")&&e("fw:gatsby"),a("solid-js")&&e("fw:solid"),(a("@solidjs/start")||a("solid-start"))&&e("fw:solidstart"),(a("@builder.io/qwik")||a("@qwik.dev/core"))&&e("fw:qwik"),a("preact")&&e("fw:preact"),(a("lit")||a("lit-element"))&&e("fw:lit"),(a("ember-source")||a("ember-cli"))&&e("fw:ember"),a("htmx.org")&&e("fw:htmx"),a("vite")&&e("fw:vite"),a("webpack")&&e("fw:webpack"),a("express")&&e("fw:express"),a("fastify")&&e("fw:fastify"),a("@nestjs/core")&&e("fw:nestjs"),a("koa")&&e("fw:koa"),a("hono")&&e("fw:hono"),(a("@hapi/hapi")||a("hapi"))&&e("fw:hapi"),a("@adonisjs/core")&&e("fw:adonis"),(a("@trpc/server")||a("@trpc/client"))&&e("fw:trpc"),a("sails")&&e("fw:sails"),a("electron")&&e("fw:electron"),a("react-native")&&e("fw:react-native"),a("expo")&&e("fw:expo"),d("@ionic/")&&e("fw:ionic"),a("@capacitor/core")&&e("fw:capacitor"),n("requirements.txt")||n("pyproject.toml")||n("setup.py")||n("Pipfile")){let i=(c("requirements.txt")+c("pyproject.toml")+c("Pipfile")+c("setup.py")).toLowerCase();i.includes("fastapi")&&e("fw:fastapi"),i.includes("django")&&e("fw:django"),i.includes("flask")&&e("fw:flask"),i.includes("litestar")&&e("fw:litestar"),i.includes("starlette")&&e("fw:starlette"),i.includes("tornado")&&e("fw:tornado"),i.includes("sanic")&&e("fw:sanic"),i.includes("aiohttp")&&e("fw:aiohttp"),i.includes("pyramid")&&e("fw:pyramid"),i.includes("fasthtml")&&e("fw:fasthtml"),(i.includes("torch")||i.includes("pytorch"))&&e("fw:pytorch"),i.includes("tensorflow")&&e("fw:tensorflow"),(i.includes("jax")||i.includes("jaxlib"))&&e("fw:jax"),i.includes("keras")&&e("fw:keras"),(i.includes("scikit-learn")||i.includes("sklearn"))&&e("fw:scikit-learn"),i.includes("transformers")&&e("fw:transformers"),i.includes("langchain")&&e("fw:langchain"),(i.includes("llama-index")||i.includes("llama_index")||i.includes("llamaindex"))&&e("fw:llamaindex"),i.includes("pandas")&&e("fw:pandas"),i.includes("numpy")&&e("fw:numpy"),i.includes("streamlit")&&e("fw:streamlit"),i.includes("gradio")&&e("fw:gradio"),i.includes("fastai")&&e("fw:fastai");}if(n("go.mod")){let i=c("go.mod").toLowerCase();i.includes("gin-gonic/gin")&&e("fw:gin"),i.includes("labstack/echo")&&e("fw:echo"),i.includes("gofiber/fiber")&&e("fw:fiber"),i.includes("go-chi/chi")&&e("fw:chi"),(i.includes("gorilla/mux")||i.includes("gorilla/websocket"))&&e("fw:gorilla"),(i.includes("beego/beego")||i.includes("astaxie/beego"))&&e("fw:beego"),i.includes("gobuffalo/buffalo")&&e("fw:buffalo");}if(n("Cargo.toml")){let i=c("Cargo.toml").toLowerCase();i.includes("actix-web")&&e("fw:actix"),i.includes("axum")&&e("fw:axum"),i.includes("rocket")&&e("fw:rocket"),i.includes("warp")&&e("fw:warp"),i.includes("tonic")&&e("fw:tonic"),i.includes("leptos")&&e("fw:leptos"),i.includes("yew")&&e("fw:yew"),i.includes("tauri")&&e("fw:tauri"),i.includes("dioxus")&&e("fw:dioxus"),i.includes("bevy")&&e("fw:bevy");}if(n("pom.xml")||n("build.gradle")||n("build.gradle.kts")){let i=(c("pom.xml")+c("build.gradle")+c("build.gradle.kts")).toLowerCase();(i.includes("spring-boot")||i.includes("springframework"))&&e("fw:spring"),i.includes("quarkus")&&e("fw:quarkus"),i.includes("micronaut")&&e("fw:micronaut"),(i.includes("io.ktor")||i.includes("ktor-"))&&e("fw:ktor"),(i.includes("vertx")||i.includes("vert.x"))&&e("fw:vertx"),(i.includes("com.android")||i.includes("androidx"))&&e("fw:android"),(i.includes("androidx.compose")||i.includes("jetpack"))&&e("fw:jetpack-compose"),(i.includes("kotlin-multiplatform")||i.includes('kotlin("multiplatform")'))&&e("fw:kotlin-multiplatform");}if(n("Gemfile")){let i=c("Gemfile").toLowerCase();i.includes("rails")&&e("fw:rails"),i.includes("sinatra")&&e("fw:sinatra"),i.includes("hanami")&&e("fw:hanami");}if(n("composer.json")){let i=c("composer.json").toLowerCase();(i.includes("laravel/framework")||i.includes("laravel/laravel"))&&e("fw:laravel"),i.includes("symfony/")&&e("fw:symfony"),i.includes("drupal/")&&e("fw:drupal"),i.includes("codeigniter")&&e("fw:codeigniter"),i.includes("slim/slim")&&e("fw:slim");}(n("wp-config.php")||n("wp-load.php")||n("wp-content"))&&e("fw:wordpress"),n("pubspec.yaml")&&c("pubspec.yaml").toLowerCase().includes("flutter")&&e("fw:flutter");{let i=r.filter(b=>b.endsWith(".csproj"));if(i.length>0){let b=i.map(h=>c(h)).join(`
4
+ `).toLowerCase();(b.includes("microsoft.net.sdk.web")||b.includes("microsoft.aspnetcore"))&&e("fw:aspnet"),b.includes("blazor")&&e("fw:blazor"),(b.includes("microsoft.net.sdk.maui")||b.includes("usemaui"))&&e("fw:maui");}}(n("ProjectSettings")||r.includes("Assembly-CSharp.csproj"))&&e("fw:unity"),n("project.godot")&&e("fw:godot");{let i=c("Package.swift").toLowerCase();i.includes("swiftui")&&e("fw:swiftui"),i.includes("uikit")&&e("fw:uikit");}let s=i=>r.some(b=>b===i||b.startsWith(i+"."));s("next.config")&&e("fw:nextjs"),s("nuxt.config")&&e("fw:nuxt"),s("astro.config")&&e("fw:astro"),s("svelte.config")&&e("fw:svelte"),s("remix.config")&&e("fw:remix"),s("gatsby-config")&&e("fw:gatsby"),s("vite.config")&&e("fw:vite"),s("vue.config")&&e("fw:vue"),s("qwik.config")&&e("fw:qwik"),n("angular.json")&&e("fw:angular"),s("capacitor.config")&&e("fw:capacitor"),s("ionic.config")&&e("fw:ionic"),n("app.json")&&c("app.json").toLowerCase().includes('"expo"')&&e("fw:expo");}{if((a("pg")||a("postgres")||a("pg-promise")||a("@vercel/postgres"))&&e("infra:postgres"),(a("mysql")||a("mysql2"))&&e("infra:mysql"),a("mariadb")&&e("infra:mariadb"),(a("redis")||a("ioredis"))&&e("infra:redis"),(a("mongodb")||a("mongoose"))&&e("infra:mongodb"),a("mongoose")&&e("infra:mongoose"),(a("better-sqlite3")||a("sqlite3")||a("sqlite"))&&e("infra:sqlite"),a("@libsql/client")&&e("infra:libsql"),a("cassandra-driver")&&e("infra:cassandra"),(a("@elastic/elasticsearch")||a("elasticsearch"))&&e("infra:elasticsearch"),a("@opensearch-project/opensearch")&&e("infra:opensearch"),(a("@clickhouse/client")||a("clickhouse"))&&e("infra:clickhouse"),(a("duckdb")||a("@duckdb/node-api"))&&e("infra:duckdb"),a("neo4j-driver")&&e("infra:neo4j"),a("@influxdata/influxdb-client")&&e("infra:influxdb"),a("snowflake-sdk")&&e("infra:snowflake"),a("@google-cloud/bigquery")&&e("infra:bigquery"),(a("firebase-admin")||a("@google-cloud/firestore"))&&e("infra:firestore"),(a("faunadb")||a("fauna"))&&e("infra:fauna"),(a("surrealdb")||a("surrealdb.js"))&&e("infra:surrealdb"),a("@qdrant/js-client-rest")&&e("infra:qdrant"),a("@pinecone-database/pinecone")&&e("infra:pinecone"),(a("weaviate-ts-client")||a("weaviate-client"))&&e("infra:weaviate"),a("chromadb")&&e("infra:chromadb"),a("@zilliz/milvus2-sdk-node")&&e("infra:milvus"),(a("@prisma/client")||a("prisma"))&&e("infra:prisma"),a("drizzle-orm")&&e("infra:drizzle"),a("typeorm")&&e("infra:typeorm"),(a("aws-sdk")||d("@aws-sdk/"))&&e("infra:aws"),(d("@google-cloud/")||a("googleapis"))&&e("infra:gcp"),d("@azure/")&&e("infra:azure"),(d("@cloudflare/")||a("wrangler"))&&e("infra:cloudflare"),(a("@vercel/node")||a("@vercel/kv")||a("@vercel/blob"))&&e("infra:vercel"),(a("firebase")||a("firebase-admin"))&&e("infra:firebase"),a("@supabase/supabase-js")&&e("infra:supabase"),a("@neondatabase/serverless")&&e("infra:neon"),a("@planetscale/database")&&e("infra:planetscale"),d("@upstash/")&&e("infra:upstash"),a("@tursodatabase/api")&&e("infra:turso"),a("modal")&&e("infra:modal"),a("replicate")&&e("infra:replicate"),(a("kafkajs")||a("node-rdkafka"))&&e("infra:kafka"),(a("amqplib")||a("rabbitmq-client"))&&e("infra:rabbitmq"),a("nats")&&e("infra:nats"),(d("@aws-sdk/client-sqs")||a("sqs-consumer"))&&e("infra:sqs"),a("@google-cloud/pubsub")&&e("infra:pubsub"),d("@temporalio/")&&e("infra:temporal"),(a("bullmq")||a("bull"))&&e("infra:bullmq"),d("@sentry/")&&e("infra:sentry"),(d("@datadog/")||a("dd-trace"))&&e("infra:datadog"),d("@opentelemetry/")&&e("infra:opentelemetry"),a("newrelic")&&e("infra:newrelic"),(a("posthog-node")||a("posthog-js"))&&e("infra:posthog"),d("@honeycombio/")&&e("infra:honeycomb"),a("prom-client")&&e("infra:prometheus"),(a("stripe")||a("@stripe/stripe-js"))&&e("infra:stripe"),d("@paddle/")&&e("infra:paddle"),d("@clerk/")&&e("infra:clerk"),(a("auth0")||d("@auth0/"))&&e("infra:auth0"),(a("next-auth")||d("@auth/"))&&e("infra:nextauth"),a("twilio")&&e("infra:twilio"),a("@sendgrid/mail")&&e("infra:sendgrid"),a("resend")&&e("infra:resend"),a("postmark")&&e("infra:postmark"),d("@pulumi/")&&e("infra:pulumi"),n("requirements.txt")||n("pyproject.toml")||n("setup.py")||n("Pipfile")){let i=(c("requirements.txt")+c("pyproject.toml")+c("Pipfile")+c("setup.py")).toLowerCase();(i.includes("psycopg")||i.includes("asyncpg"))&&e("infra:postgres"),(i.includes("pymysql")||i.includes("aiomysql")||i.includes("mysqlclient"))&&e("infra:mysql"),(i.includes("redis")||i.includes("aioredis"))&&e("infra:redis"),(i.includes("pymongo")||i.includes("motor")||i.includes("mongoengine"))&&e("infra:mongodb"),i.includes("elasticsearch")&&e("infra:elasticsearch"),i.includes("clickhouse")&&e("infra:clickhouse"),i.includes("duckdb")&&e("infra:duckdb"),i.includes("neo4j")&&e("infra:neo4j"),i.includes("snowflake")&&e("infra:snowflake"),i.includes("qdrant-client")&&e("infra:qdrant"),i.includes("pinecone")&&e("infra:pinecone"),i.includes("chromadb")&&e("infra:chromadb"),i.includes("pymilvus")&&e("infra:milvus"),i.includes("sqlalchemy")&&e("infra:sqlalchemy"),(i.includes("boto3")||i.includes("botocore"))&&e("infra:aws"),i.includes("google-cloud")&&e("infra:gcp"),i.includes("azure-")&&e("infra:azure"),i.includes("supabase")&&e("infra:supabase"),(i.includes("confluent-kafka")||i.includes("aiokafka")||i.includes("kafka-python"))&&e("infra:kafka"),(i.includes("pika")||i.includes("aio-pika"))&&e("infra:rabbitmq"),i.includes("temporalio")&&e("infra:temporal"),i.includes("sentry-sdk")&&e("infra:sentry"),(i.includes("ddtrace")||i.includes("datadog"))&&e("infra:datadog"),i.includes("opentelemetry")&&e("infra:opentelemetry"),i.includes("stripe")&&e("infra:stripe"),i.includes("twilio")&&e("infra:twilio"),i.includes("pulumi")&&e("infra:pulumi"),i.includes("ansible")&&e("infra:ansible");}if(n("go.mod")){let i=c("go.mod").toLowerCase();(i.includes("lib/pq")||i.includes("jackc/pgx"))&&e("infra:postgres"),i.includes("go-sql-driver/mysql")&&e("infra:mysql"),(i.includes("go-redis")||i.includes("redis/go-redis"))&&e("infra:redis"),i.includes("go.mongodb.org/mongo-driver")&&e("infra:mongodb"),i.includes("aws/aws-sdk-go")&&e("infra:aws"),i.includes("cloud.google.com/go")&&e("infra:gcp"),(i.includes("segmentio/kafka-go")||i.includes("sarama"))&&e("infra:kafka"),i.includes("getsentry/sentry-go")&&e("infra:sentry"),i.includes("go.opentelemetry.io")&&e("infra:opentelemetry"),i.includes("stripe/stripe-go")&&e("infra:stripe"),i.includes("hashicorp/terraform")&&e("infra:terraform"),i.includes("k8s.io/client-go")&&e("infra:kubernetes");}(n("Dockerfile")||n("docker-compose.yml")||n("docker-compose.yaml")||n("compose.yaml")||n("compose.yml")||n(".dockerignore"))&&e("infra:docker"),(n("Containerfile")||n("podman-compose.yml"))&&e("infra:podman"),r.some(i=>i.endsWith(".tf")||i===".terraform.lock.hcl")&&e("infra:terraform"),(n("Pulumi.yaml")||n("Pulumi.yml"))&&e("infra:pulumi"),(n("ansible.cfg")||n("playbook.yml")||n("playbook.yaml"))&&e("infra:ansible"),(n("kustomization.yaml")||n("kustomization.yml")||n("k8s")||n("kubernetes")||n("skaffold.yaml"))&&e("infra:kubernetes"),(n("Chart.yaml")||n("helmfile.yaml"))&&(e("infra:helm"),e("infra:kubernetes")),r.some(i=>i.endsWith(".nomad")||i.endsWith(".nomad.hcl"))&&e("infra:nomad"),(n("vercel.json")||n(".vercel"))&&e("infra:vercel"),(n("netlify.toml")||n(".netlify"))&&e("infra:netlify"),n("fly.toml")&&e("infra:fly"),(n("railway.json")||n("railway.toml"))&&e("infra:railway"),n("render.yaml")&&e("infra:render"),n("Procfile")&&e("infra:heroku"),(n("wrangler.toml")||n("wrangler.jsonc")||n("wrangler.json"))&&e("infra:cloudflare"),n("supabase")&&e("infra:supabase"),(n("firebase.json")||n(".firebaserc"))&&e("infra:firebase"),(n("serverless.yml")||n("serverless.yaml")||n("template.yaml")||n("samconfig.toml"))&&e("infra:aws"),(n("prisma")||n("schema.prisma"))&&e("infra:prisma"),(n("drizzle.config.ts")||n("drizzle.config.js"))&&e("infra:drizzle");let s=false;try{s=n(".github")&&g__namespace.existsSync(y__namespace.join(t,".github","workflows"));}catch{s=false;}s&&e("infra:github-actions"),(n(".gitlab-ci.yml")||n(".gitlab-ci.yaml"))&&e("infra:gitlab-ci"),n(".circleci")&&e("infra:circleci"),n("Jenkinsfile")&&e("infra:jenkins");{let i=(c("Dockerfile")+c("docker-compose.yml")+c("docker-compose.yaml")+c("compose.yaml")+c("compose.yml")).toLowerCase();i&&((i.includes("postgres")||i.includes("pgvector"))&&e("infra:postgres"),i.includes("timescale")&&e("infra:timescaledb"),i.includes("mysql")&&e("infra:mysql"),i.includes("mariadb")&&e("infra:mariadb"),i.includes("redis")&&e("infra:redis"),i.includes("mongo")&&e("infra:mongodb"),i.includes("cassandra")&&e("infra:cassandra"),i.includes("cockroach")&&e("infra:cockroachdb"),i.includes("clickhouse")&&e("infra:clickhouse"),i.includes("elasticsearch")&&e("infra:elasticsearch"),i.includes("neo4j")&&e("infra:neo4j"),i.includes("qdrant")&&e("infra:qdrant"),i.includes("rabbitmq")&&e("infra:rabbitmq"),(i.includes("kafka")||i.includes("redpanda"))&&e("infra:kafka"),i.includes("nats")&&e("infra:nats"),i.includes("grafana")&&e("infra:grafana"),(i.includes("prometheus")||i.includes("prom/"))&&e("infra:prometheus"));}}{let i=(...w)=>w.some(a),b=(c("requirements.txt")+c("pyproject.toml")+c("Pipfile")+c("setup.py")+c("environment.yml")).toLowerCase(),h=c("go.mod").toLowerCase(),m=c("Cargo.toml").toLowerCase(),l=w=>b.includes(w),T=w=>r.some(de=>de.toLowerCase().endsWith(w)),k=(...w)=>w.some(de=>n(de)),R=()=>Array.from(o).some(w=>w.startsWith("type:")),ue=()=>Array.from(o).some(w=>w.startsWith("fw:"));(a("@modelcontextprotocol/sdk")||l("modelcontextprotocol")||l("fastmcp")||h.includes("modelcontextprotocol")||k("mcp.json",".mcp.json"))&&e("type:mcp-server"),(i("langgraph","@langchain/langgraph","crewai","autogen","@mastra/core","@openai/agents","@langchain/core")||l("langgraph")||l("crewai")||l("autogen")||l("pyautogen")||l("smolagents")||l("haystack"))&&e("type:agent-framework"),(i("ai","openai","@anthropic-ai/sdk","@google/generative-ai","@ai-sdk/openai","@ai-sdk/anthropic","langchain","@huggingface/inference","cohere-ai","ollama","groq-sdk","@mistralai/mistralai")||l("openai")||l("anthropic")||l("langchain")||l("litellm")||l("google-generativeai")||l("cohere")||l("ollama"))&&e("type:ai-app"),(T(".sol")||k("hardhat.config.js","hardhat.config.ts","foundry.toml","truffle-config.js","Anchor.toml","Move.toml")||i("hardhat","ethers","web3","@solana/web3.js","wagmi","viem","@openzeppelin/contracts"))&&e("type:smart-contract"),(k("project.godot","ProjectSettings")||T(".unity")||T(".uproject")||i("phaser","kaplay","kaboom","excalibur","playcanvas")||m.includes("bevy")||m.includes("macroquad")||m.includes("ggez")||l("pygame")||l("arcade"))&&e("type:game");{let w=f("manifest.json");(w&&Object.prototype.hasOwnProperty.call(w,"manifest_version")||i("webextension-polyfill","@types/chrome","wxt","plasmo"))&&e("type:browser-extension");}(i("react-native","expo","nativescript")||n("pubspec.yaml")||T(".xcodeproj")||k("AndroidManifest.xml"))&&e("type:mobile-app"),(i("electron","@tauri-apps/api","@tauri-apps/cli","nw")||k("tauri.conf.json","src-tauri")||m.includes("tauri")||m.includes("egui")||l("pyqt5")||l("pyqt6")||l("pyside6")||l("kivy"))&&e("type:desktop-app"),(i("discord.js","telegraf","node-telegram-bot-api","@slack/bolt","probot","grammy")||l("discord.py")||l("python-telegram-bot")||l("slack-bolt")||l("slack_bolt")||l("aiogram")||l("pyrogram"))&&e("type:bot"),(k("dbt_project.yml","dagster.yaml")||i("@dagster-io/dagster","apache-airflow")||l("airflow")||l("dagster")||l("prefect")||l("dbt-core")||l("luigi")||l("kedro")||l("pyspark")||l("apache-beam"))&&e("type:data-pipeline"),(l("torch")||l("tensorflow")||l("keras")||l("jax")||l("scikit-learn")||l("sklearn")||l("xgboost")||l("lightgbm")||l("pytorch-lightning")||l("diffusers")||l("mlflow"))&&e("type:ml-model"),(T(".ipynb")||l("jupyter")||l("jupyterlab")||l("marimo")||n("notebooks"))&&e("type:notebook"),(k("mkdocs.yml","mkdocs.yaml","mint.json","docusaurus.config.js","docusaurus.config.ts","book.toml")||i("@docusaurus/core","vitepress","vuepress","nextra","@astrojs/starlight")||l("mkdocs")||l("sphinx"))&&e("type:documentation"),(k("hugo.toml","_config.yml",".eleventy.js","eleventy.config.js","astro.config.mjs","astro.config.ts","astro.config.js")||i("astro","gatsby","@11ty/eleventy","hexo","gridsome")||l("pelican"))&&e("type:static-site"),i("@medusajs/medusa","@saleor/sdk","@shopify/hydrogen","vendure","@vendure/core","snipcart","use-shopping-cart","swell-js")&&e("type:ecommerce"),(p.bin||i("commander","yargs","oclif","@oclif/core","cac","meow","inquirer","@clack/prompts","ink")||l("click")||l("typer")||l("docopt")||h.includes("spf13/cobra")||h.includes("urfave/cli")||m.includes("clap")||m.includes("structopt"))&&e("type:cli"),(k("pnpm-workspace.yaml","turbo.json","nx.json","lerna.json","rush.json")||Array.isArray(p.workspaces)||m.includes("[workspace]")||n("go.work"))&&e("type:monorepo");let j=i("next","react","vue","@angular/core","svelte","@sveltejs/kit","solid-js","nuxt","remix","@remix-run/react","preact","qwik"),E=i("express","fastify","@nestjs/core","koa","hapi","@hapi/hapi","hono")||l("fastapi")||l("django")||l("flask")||l("starlette")||l("sanic")||h.includes("gin-gonic/gin")||h.includes("labstack/echo")||h.includes("gofiber/fiber")||m.includes("axum")||m.includes("actix-web")||(c("pom.xml")+c("build.gradle")).toLowerCase().includes("spring-boot"),Ee=Array.from(o).some(w=>["infra:postgres","infra:mysql","infra:mongodb","infra:supabase","infra:neon"].includes(w)),Oe=i("next-auth","@clerk/nextjs","@auth0/auth0-react","passport","lucia","@workos-inc/node")||l("django-allauth")||l("flask-login"),Ae=i("stripe","@stripe/stripe-js","@paddle/paddle-js","@lemonsqueezy/lemonsqueezy.js")||l("stripe");(!j&&!E&&(p.main||p.exports||p.module||p.types||p.publishConfig)||n("Cargo.toml")&&!m.includes("[[bin]]")&&m.includes("[lib]")||k("LICENSE","LICENSE.md","LICENSE.txt")&&!j&&!E&&!R())&&!R()&&e("type:library"),j?(Ee&&(Oe||Ae)&&e("type:saas"),e("type:web-app")):E&&(Ee&&(Oe||Ae)&&e("type:saas"),e("type:api-service")),R()||(ue()?e("type:web-app"):k("Dockerfile","docker-compose.yml","compose.yaml")||r.some(w=>w.endsWith(".tf"))||k("Chart.yaml","kustomization.yaml","wrangler.toml","serverless.yml",".github")||i("@pulumi/pulumi","aws-cdk-lib","cdktf")?e("type:devops-tool"):n("package.json")&&(p.main||p.exports)&&e("type:library"));}return Array.from(o)}function He(t){let o={sponsorLabel:t.sponsorLabel,title:t.creative.title,body:t.creative.body,url:t.clickUrl};return t.creative.cta!==void 0&&(o.cta=t.creative.cta),o}function Ue(t){return {sponsorLabel:"",title:t.title,body:t.body,url:t.url}}function V(t){let o=He(t),e=t.creative;switch(e.format){case "image":case "gif":return {...o,body:e.textFallback??o.body};case "video":return {...o,body:e.textFallback??o.body,cta:o.cta??"\u25B6 Watch"};case "audio":return {...o,body:e.textFallback??o.body,cta:o.cta??"\u{1F50A} Listen"};default:return o}}function U(t=process.env){return y__namespace.join(N__namespace.homedir(),".config","opencrater")}function Z(t=process.env){return y__namespace.join(U(t),"state.json")}function X(){return {installId:crypto.randomUUID(),lastShownAt:0,optOut:false,disclosureShown:false,cachedConfig:null,configFetchedAt:0,pool:[],allowedPlacements:{},sessionTopics:[],integrations:[],devToken:null,computeRouting:null,computeCards:null}}function O(t){return typeof t=="number"&&Number.isFinite(t)}var Fe=new Set(["EPERM","EACCES","EBUSY","EEXIST"]);function qe(t){for(let o=0;;o++)try{return {text:g__namespace.readFileSync(t,"utf8")}}catch(e){let r=e.code??"";if(!(r==="ENOENT"||Fe.has(r)))return {locked:true};if(o>=4)return r==="ENOENT"?{missing:true}:{locked:true};try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(o+1));}catch{}}}function vt(t){if(typeof t!="object"||t===null)return null;let o=t;return !O(o.minIntervalSeconds)||!O(o.serveTimeoutMs)||!O(o.preloadPoolSize)||typeof o.killSwitch!="boolean"?null:{minIntervalSeconds:o.minIntervalSeconds,serveTimeoutMs:o.serveTimeoutMs,preloadPoolSize:o.preloadPoolSize,killSwitch:o.killSwitch,displayDurationSeconds:O(o.displayDurationSeconds)?o.displayDurationSeconds:25,minSdkVersion:typeof o.minSdkVersion=="string"?o.minSdkVersion:""}}function xt(t){if(!Array.isArray(t))return [];let o=[];for(let e of t){if(typeof e!="object"||e===null)continue;let r=e,n=r.blip;if(!O(r.renderBy)||typeof n!="object"||n===null||typeof n.impressionId!="string"||typeof n.clickUrl!="string"||typeof n.sponsorLabel!="string"||typeof n.creative!="object"||n.creative===null)continue;let c=n.creative;typeof c.title!="string"||typeof c.body!="string"||o.push({blip:{impressionId:n.impressionId,...typeof n.campaignId=="string"?{campaignId:n.campaignId}:{},clickUrl:n.clickUrl,sponsorLabel:n.sponsorLabel,creative:{format:"text",title:c.title,body:c.body,...typeof c.cta=="string"?{cta:c.cta}:{}}},renderBy:r.renderBy});}return o}function Ct(t){if(typeof t!="object"||t===null||Array.isArray(t))return {};let o={};for(let[e,r]of Object.entries(t)){if(!Array.isArray(r))continue;let n=r.filter(c=>typeof c=="string"&&c.length<=64);o[e]=n.slice(0,64);}return o}function Tt(t){if(!Array.isArray(t))return [];let o=[];for(let e of t){if(typeof e!="object"||e===null)continue;let r=e;if(!(typeof r.topic!="string"||!O(r.at))&&(o.push({topic:r.topic.slice(0,32),at:r.at}),o.length>=24))break}return o}function jt(t){if(!Array.isArray(t))return [];let o=[],e=new Set;for(let r of t){if(typeof r!="object"||r===null)continue;let n=r;if(typeof n.key!="string"||typeof n.package!="string"||n.key===""||n.package==="")continue;let c=`${n.package}\0${n.key}`;if(!e.has(c)&&(e.add(c),o.push({key:n.key,package:n.package}),o.length>=32))break}return o}function Rt(t){if(typeof t!="object"||t===null)return null;let o=t,e={};if(typeof o.savedEnv=="object"&&o.savedEnv!==null)for(let[r,n]of Object.entries(o.savedEnv))(typeof n=="string"||n===null)&&(e[r]=n);return {active:o.active===true,savedEnv:e}}function Et(t){if(typeof t!="object"||t===null)return null;let o=t,e=r=>O(r)&&r>=0?r:0;return {turns:e(o.turns),lastLimitAt:e(o.lastLimitAt),lastDepletedAt:e(o.lastDepletedAt),lastBackupAt:e(o.lastBackupAt)}}function Ot(t){let o=t.attrTagsAt,e=t.attrTagsCwd;return !O(o)||Date.now()-o>Y||typeof e!="string"||e.length===0||e.length>64?{}:{attrTags:Array.isArray(t.attrTags)?t.attrTags.filter(n=>typeof n=="string"&&n.length<=40).slice(0,48):[],attrTagsCwd:e,attrTagsAt:o}}function At(t){let o=X();if(typeof t!="object"||t===null)return o;let e=t;return {installId:typeof e.installId=="string"&&e.installId.length>0?e.installId:o.installId,lastShownAt:O(e.lastShownAt)&&e.lastShownAt>=0?e.lastShownAt:0,optOut:e.optOut===true,disclosureShown:e.disclosureShown===true,cachedConfig:vt(e.cachedConfig),allowedPlacements:Ct(e.allowedPlacements),sessionTopics:Tt(e.sessionTopics),integrations:jt(e.integrations),devToken:typeof e.devToken=="string"?e.devToken:null,computeRouting:Rt(e.computeRouting),computeCards:Et(e.computeCards),configFetchedAt:O(e.configFetchedAt)&&e.configFetchedAt>=0?e.configFetchedAt:0,pool:xt(e.pool),...Ot(e)}}function me(t=process.env){let o=Z(t),e=qe(o);if(e.text!==void 0)try{return At(JSON.parse(e.text))}catch{let r=X();try{C(r,t);}catch{}return r}if(e.missing){let r=X();try{C(r,t);}catch{}return r}return X()}function C(t,o=process.env,e={}){let r=Z(o),n=y__namespace.dirname(r);g__namespace.mkdirSync(n,{recursive:true});let c=qe(r),f=null;if(c.text!==void 0)try{f=JSON.parse(c.text);}catch{f=null;}if(f)typeof f.lastShownAt=="number"&&f.lastShownAt>t.lastShownAt&&(t={...t,lastShownAt:f.lastShownAt}),!e.allowClearToken&&typeof f.devToken=="string"&&t.devToken==null&&(t={...t,devToken:f.devToken}),typeof f.installId=="string"&&f.installId.length>0&&f.installId!==t.installId&&(t={...t,installId:f.installId});else if(!e.allowClearToken&&t.devToken==null&&c.text===void 0&&!c.missing)return;let p=y__namespace.join(n,`.state.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`);g__namespace.writeFileSync(p,JSON.stringify(t,null,2)+`
5
+ `,"utf8");for(let u=0;;u++)try{g__namespace.renameSync(p,r);return}catch(a){let d=a.code??"";if(u>=4||!Fe.has(d)){try{g__namespace.rmSync(p,{force:!0});}catch{}if(u>=4)return;throw a}try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(u+1));}catch{}}}var _t=300*1e3;function It(){return y__namespace.join(U(),"blocked-ads.json")}function ge(){return y__namespace.join(U(),"recent-renders.json")}function Pt(){return y__namespace.join(U(),"reported-ads.json")}function Ge(t,o){let e={};for(let[r,n]of Object.entries(t))typeof n=="number"&&Number.isFinite(n)&&n>o&&(e[r]=n);return e}function Nt(t){try{let o=JSON.parse(g__namespace.readFileSync(It(),"utf8"));return Ge(o&&typeof o=="object"?o:{},t)}catch{return {}}}function $t(){try{let t=JSON.parse(g__namespace.readFileSync(Pt(),"utf8"));return t&&typeof t=="object"?t:{}}catch{return {}}}function Mt(t){return t?$t()[t]!==void 0:false}function Q(t,o=Date.now()){return t?Nt(o)[t]!==void 0||Mt(t):false}function ze(t){try{let o=JSON.parse(g__namespace.readFileSync(ge(),"utf8"));return Ge(o&&typeof o=="object"?o:{},t)}catch{return {}}}function ee(t,o=Date.now()){if(t)try{let e=ze(o);e[t]=o+_t,g__namespace.mkdirSync(y__namespace.dirname(ge()),{recursive:!0}),g__namespace.writeFileSync(ge(),JSON.stringify(e));}catch{}}function te(t,o=Date.now()){return t?ze(o)[t]!==void 0:false}function Lt(t,o){return t.filter(e=>e.renderBy>o)}function he(t,o){let e=Lt(t.pool,o),r=e.shift();return {blip:r?r.blip:null,pool:e}}var Dt=["claude_code","codex","antigravity","copilot_cli","grok_cli"];function be(t){return t.includes("opencrater-hook")||/opencrater[\\/][^"']*hook\.js/.test(t)}function Wt(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ht(t,o){return be(t)&&new RegExp(`--package ['"]?${Wt(o)}['"]?`).test(t)}function ke(t,o){return o?Ht(t,o):be(t)&&!/--package\b/.test(t)}function ne(t){return /^[A-Za-z0-9@_./:-]+$/.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}var oe='"$HOME/.config/opencrater/runtime/node_modules/opencrater/dist/hook.js"',Je="$env:USERPROFILE\\.config\\opencrater\\runtime\\node_modules\\opencrater\\dist\\hook.js";function B(t,o,e,r){let n=`--placement ${o}`;return e&&(n+=` --key ${ne(e)}`),r&&(n+=` --package ${ne(r)}`),n+=` --host ${t}`,`{ if [ -f ${oe} ]; then node ${oe} ${n}; else npx -y -p opencrater opencrater-hook ${n}; fi; } 2>/dev/null || true`}function Ut(t,o,e){if(process.platform!=="win32")return B("grok_cli",t,o,e);let r=`--placement ${t}`;o&&(r+=` --key ${o}`),e&&(r+=` --package ${e}`),r+=" --host grok_cli";let n=`${N__namespace.homedir()}\\.config\\opencrater\\runtime\\node_modules\\opencrater\\dist\\hook.js`;return `try { if (Test-Path "${n}") { node "${n}" ${r} } else { npx -y -p opencrater opencrater-hook ${r} } } catch {}`}function Bt(t,o,e){if(process.platform==="win32"){let n=`--placement ${t}`;o&&(n+=` --key ${o}`),e&&(n+=` --package ${e}`),n+=" --host antigravity";let c=`${N__namespace.homedir()}\\.config\\opencrater\\runtime\\node_modules\\opencrater\\dist\\hook.js`;return `( if exist "${c}" ( node "${c}" ${n} ) else ( npx -y -p opencrater opencrater-hook ${n} ) ) >NUL 2>&1 & echo {"decision":"allow"}`}let r=`--placement ${t}`;return o&&(r+=` --key ${ne(o)}`),e&&(r+=` --package ${ne(e)}`),r+=" --host antigravity",`{ if [ -f ${oe} ]; then node ${oe} ${r}; else npx -y -p opencrater opencrater-hook ${r}; fi; } >/dev/null 2>&1; echo '{"decision":"allow"}'`}function Ye(t,o,e,r){let n=`--placement ${o}`;return e&&(n+=` --key '${e}'`),r&&(n+=` --package '${r}'`),n+=` --host ${t}`,`try { if (Test-Path "${Je}") { node "${Je}" ${n} } else { npx -y -p opencrater opencrater-hook ${n} } } catch {}`}function Ft(t,o,e){if(process.platform!=="win32")return B("claude_code",t,o,e);let r=`--placement ${t}`;return o&&(r+=` --key ${o}`),e&&(r+=` --package ${e}`),r+=" --host claude_code",`node "${`${N__namespace.homedir()}\\.config\\opencrater\\runtime\\node_modules\\opencrater\\dist\\hook.js`}" ${r}; exit 0`}function ye(t,o,e,r){if(t==="grok_cli")return {type:"command",command:Ut(o,e,r),timeout:15};let c={type:"command",command:t==="claude_code"?Ft(o,e,r):B(t,o,e,r)};return t==="codex"&&(c.commandWindows=Ye(t,o,e,r)),c}function re(t,o){let e=N__namespace.homedir();switch(t){case "claude_code":{let r=o.CLAUDE_CONFIG_DIR;return r&&r.trim()!==""?r:y__namespace.join(e,".claude")}case "codex":{let r=o.CODEX_HOME;return r&&r.trim()!==""?r:y__namespace.join(e,".codex")}case "antigravity":return y__namespace.join(e,".gemini");case "copilot_cli":{let r=o.COPILOT_HOME;return r&&r.trim()!==""?r:y__namespace.join(e,".copilot")}case "grok_cli":{let r=o.GROK_HOME;return r&&r.trim()!==""?r:y__namespace.join(e,".grok")}default:return y__namespace.join(e,".opencrater-unknown")}}function q(t,o=process.env){let e=re(t,o);switch(t){case "claude_code":return y__namespace.join(e,"settings.json");case "codex":return y__namespace.join(e,"hooks.json");case "antigravity":return y__namespace.join(e,"config","hooks.json");case "copilot_cli":return y__namespace.join(e,"hooks","hooks.json");case "grok_cli":return y__namespace.join(e,"hooks","opencrater.json");default:return y__namespace.join(e,"hooks.json")}}var qt={claude_code:["claude"],codex:["codex"],antigravity:["agy"],copilot_cli:["copilot"],grok_cli:["grok"]};function Gt(t,o){if(t.length===0)return false;let e=(o.PATH??o.Path??"").split(y__namespace.delimiter).filter(Boolean),r=process.platform==="win32"?["",".exe",".cmd",".bat"]:[""];for(let n of e)for(let c of t)for(let f of r)try{if(g__namespace.existsSync(y__namespace.join(n,c+f)))return !0}catch{}return false}function zt(t,o=process.env){try{if(g__namespace.existsSync(re(t,o)))return !0}catch{}return Gt(qt[t]??[],o)}function we(t=process.env){return Dt.filter(o=>zt(o,t))}function ie(t){let o;try{o=g__namespace.readFileSync(t,"utf8");}catch{return {}}let e=JSON.parse(o);if(typeof e!="object"||e===null||Array.isArray(e))throw new Error(`${t} is not a JSON object`);return e}function se(t,o){let e=y__namespace.dirname(t);g__namespace.mkdirSync(e,{recursive:true});let r=y__namespace.join(e,`.${y__namespace.basename(t)}.${process.pid}.tmp`);g__namespace.writeFileSync(r,JSON.stringify(o,null,2)+`
6
+ `,"utf8"),g__namespace.renameSync(r,t);}function Jt(t,o){return Array.isArray(t.hooks)&&t.hooks.some(e=>typeof e.command=="string"&&ke(e.command,o))}function Kt(t,o,e,r){let n=q(t),c=ie(n),f=c.hooks&&typeof c.hooks=="object"?c.hooks:{};if(r.every(u=>{let a=ye(t,u,o,e);return (Array.isArray(f[u])?f[u]:[]).some(d=>Array.isArray(d.hooks)&&d.hooks.some(s=>s.command===a.command&&s.commandWindows===a.commandWindows))}))return "nochange";for(let u of r){let d=(Array.isArray(f[u])?f[u]:[]).filter(i=>!Jt(i,e)),s=t==="grok_cli"?{hooks:[ye(t,u,o,e)]}:{matcher:"",hooks:[ye(t,u,o,e)]};d.push(s),f[u]=d;}return c.hooks=f,se(n,c),"wrote"}var Yt=15;function Vt(t){return t?`opencrater-${t}`:"opencrater-compute"}function Xt(t,o){if(!t||typeof t!="object")return false;for(let e of Object.values(t))for(let r of Array.isArray(e)?e:[])if(Array.isArray(r.hooks)&&r.hooks.some(n=>typeof n.command=="string"&&ke(n.command,o)))return true;return false}function Zt(t){try{let o=y__namespace.join(re("antigravity",t),"settings.json"),e;try{e=ie(o);}catch{return}let r=!1,n=e.hooks;if(n&&typeof n=="object"&&!Array.isArray(n)){let c=n;for(let f of Object.keys(c)){let p=Array.isArray(c[f])?c[f]:[],u=p.filter(a=>!(Array.isArray(a.hooks)&&a.hooks.some(d=>typeof d.command=="string"&&be(d.command))));u.length!==p.length&&(r=!0,u.length>0?c[f]=u:delete c[f]);}Object.keys(c).length===0&&(delete e.hooks,r=!0);}e["json-hooks-enabled"]===!0&&(delete e["json-hooks-enabled"],r=!0),r&&se(o,e);}catch{}}function Qt(t,o,e){let r=q("antigravity"),n=ie(r),c=Vt(o),f={};for(let a of e)f[a]=[{hooks:[{type:"command",command:Bt(a,t,o),timeout:Yt}]}];let p=JSON.stringify(f),u=false;JSON.stringify(n[c]??null)!==p&&(n[c]=f,u=true);for(let a of Object.keys(n))a!==c&&Xt(n[a],o)&&(delete n[a],u=true);return Zt(process.env),u?(se(r,n),"wrote"):"nochange"}var Ke=12;function en(t,o){return [t.bash,t.powershell,t.command].some(e=>typeof e=="string"&&ke(e,o))}function tn(t,o,e,r){let n=q(t),c=ie(n);typeof c.version!="number"&&(c.version=1);let f=c.hooks&&typeof c.hooks=="object"?c.hooks:{};if(r.every(u=>{let a=B(t,u,o,e);return (Array.isArray(f[u])?f[u]:[]).some(d=>d.bash===a&&d.timeoutSec===Ke)}))return "nochange";for(let u of r){let d=(Array.isArray(f[u])?f[u]:[]).filter(s=>!en(s,e));d.push({type:"command",bash:B(t,u,o,e),powershell:Ye(t,u,o,e),timeoutSec:Ke}),f[u]=d;}return c.hooks=f,se(n,c),"wrote"}function Ve(t){return [...Ie[t]]}function nn(t){let o=t;for(let e of ["claude","cursor"]){if(new RegExp(`^\\s*\\[compat\\.${e}\\]`,"m").test(o))continue;let r=o.length===0?"":o.endsWith(`
7
7
  `)?`
8
8
  `:`
9
9
 
10
10
  `;o+=`${r}[compat.${e}]
11
11
  hooks = false
12
- `;}return o}function on(t){try{let o=y__namespace.join(re("grok_cli",t),"config.toml"),e="";try{e=h__namespace.readFileSync(o,"utf8");}catch{}let r=nn(e);if(r===e)return;h__namespace.mkdirSync(y__namespace.dirname(o),{recursive:!0}),h__namespace.writeFileSync(o,r,"utf8");}catch{}}function rn(t,o,e){let r=Ve(t);return r.length===0?"nochange":(t==="grok_cli"&&on(process.env),t==="copilot_cli"?tn(t,o,e,r):t==="antigravity"?Qt(o,e,r):Kt(t,o,e,r))}function Se(t,o,e=process.env){return we(e).map(r=>{try{let n=rn(r,t,o);return {host:r,status:n,events:Ve(r)}}catch(n){return {host:r,status:"error",events:[],error:n.message}}})}function an(){return y__namespace.join(N__namespace.homedir(),".config","opencrater","runtime")}function cn(t){return ["install","--prefix",t,"opencrater@latest","--silent","--no-audit","--no-fund"]}function ve(t=an()){child_process.spawn("npm",cn(t),process.platform==="win32"?{detached:false,stdio:"ignore",windowsHide:true,shell:true}:{detached:true,stdio:"ignore"}).unref();}var et={atLimit:false,resetAt:null};function tt(t,o=N__namespace.homedir()){try{if(t==="claude_code")return ln(o);if(t==="codex")return fn(o)}catch{}return et}function ln(t){let o=h__namespace.readFileSync(y__namespace.join(t,".claude.json"),"utf8"),e=JSON.parse(o),r=e.hasAvailableSubscription===false||e.cachedExtraUsageDisabledReason==="out_of_credits",n=null,p=e.cachedGrowthBookFeatures?.tengu_saffron_lattice?.planLimitsEndDate;if(typeof p=="string"){let u=Date.parse(p);Number.isFinite(u)&&(n=u);}return {atLimit:r,resetAt:n}}function fn(t){return h__namespace.accessSync(y__namespace.join(t,".codex","auth.json")),et}function nt(t,o){return t==="copilot_cli"?o==="agentStop":o==="Stop"}var ot=36e5,un=30*6e4,dn=30*6e4,pn=4*ot,mn=3,ae="https://opencrater.to/dashboard";function G(t){return `${Math.round(t/1e3).toLocaleString()} tokens`}function gn(t){let o=t/1e3;return o>0&&o<10?`${(Math.round(o*10)/10).toFixed(1)} tokens`:`${Math.round(o).toLocaleString()} tokens`}function hn(t){switch(t){case "claude_code":return {name:"Claude Code",launch:"opencrater claude",resume:"opencrater claude -c"};case "codex":return {name:"Codex",launch:"opencrater codex",resume:"opencrater codex -c"};case "grok_cli":return {name:"Grok",launch:"opencrater grok",resume:"opencrater grok -c"};default:return null}}var ce="opencrater claude";function yn(t,o){if(!t||t<=o)return "";let e=t-o,r=e>=864e5?`${Math.floor(e/864e5)}d`:`${Math.max(1,Math.floor(e/ot))}h`,n=new Date(t).toISOString().slice(0,10);return ` Your host limit resets in ${r} (${n}).`}function rt(t){let{balanceMicroUsd:o,pendingMicroUsd:e,onGateway:r,turnEnd:n,hostName:c,host:f,cc:p,now:u}=t;if(o===null)return null;let a=hn(c),d=e&&e>0?` (+${gn(e)} pending)`:"";return o<=0?u-(p.lastDepletedAt??0)<dn?null:{kind:"depleted",card:{sponsorLabel:"OpenCrater",title:"Compute used up",body:`Keep coding in any CLI to earn more compute, then switch back to ${a?.name??"your plan"}.`+yn(f.resetAt,u),url:ae,cta:"Earn more"}}:r?!n||(p.turns??0)%mn!==0?null:{kind:"hud",card:{sponsorLabel:"OpenCrater",title:"Running on OpenCrater compute",body:`${G(o)} compute available${d}.`,url:ae,cta:"Wallet"}}:f.atLimit?u-(p.lastLimitAt??0)<un?null:{kind:"limit",card:{sponsorLabel:"OpenCrater",title:"Hit your limit? You've got compute",body:a?`${G(o)} of OpenCrater compute is ready. Continue this ${a.name} session now: ${a.resume}`:`${G(o)} of OpenCrater compute is ready. Run your coding agent on it: ${ce}`,url:ae,cta:a?a.resume:ce}}:u-(p.lastBackupAt??0)>=pn?{kind:"backup",card:{sponsorLabel:"OpenCrater",title:"Backup compute ready",body:a?`${G(o)} of OpenCrater compute waiting${d}. When you hit your limit: ${a.resume}`:`${G(o)} of OpenCrater compute waiting${d}. Spend it any time: ${ce}`,url:ae,cta:a?a.resume:ce}}:null}var Sn=["CI","CONTINUOUS_INTEGRATION","GITHUB_ACTIONS","GITLAB_CI","CIRCLECI","TRAVIS","BUILDKITE","JENKINS_URL","TEAMCITY_VERSION","TF_BUILD","APPVEYOR","CODEBUILD_BUILD_ID","DRONE","NETLIFY","VERCEL"];function Ce(t){return t!==void 0&&t!==""&&t!=="0"&&t.toLowerCase()!=="false"}function vn(t){return Ce(t.OPENCRATER_DISABLE)||Ce(t.TSN_DISABLE)}function xn(t){return Sn.some(o=>Ce(t[o]))}function fe(t){return t?{...H,...t}:H}function ut(t,o={}){if(vn(t.env))return "env_disabled";if(t.state.optOut)return "opt_out";let e=fe(t.state.cachedConfig);if(e.killSwitch)return "kill_switch";if(xn(t.env))return "ci";if(!o.skipTTY&&false);if(!o.skipFrequency){let r=e.minIntervalSeconds*1e3;if(t.state.lastShownAt>0&&t.now-t.state.lastShownAt<r)return "frequency"}return null}var Cn=new Set(["the","and","for","but","not","you","all","any","can","this","that","with","have","will","your","from","they","what","when","where","how","why","make","fix","add","update","remove","create","delete","change","error","errors","bug","bugs","file","files","code","test","tests","run","running","build","please","help","want","need","should","would","could","into","about","then","here","there","now","new","use","using","used","work","working","works","check","show","see","look","get","set","let","lets","dont","cant","issue"]);function Tn(t){if(t.includes("/")||t.includes("\\")||t.includes("@")||t.includes("://"))return true;let o=t.toLowerCase();return !!(/^(sk|pk|rk|ock|ghp|gho|ghs|xox|akia|eyj|npm|glpat)[-_]/.test(o)||t.length>=16&&/^[0-9a-f]+$/i.test(t)||t.length>=20&&/^[A-Za-z0-9+/=_-]+$/.test(t)&&/[A-Z]/.test(t)&&/[0-9]/.test(t))}function jn(t,o=12){let e=[];for(let r of t.slice(0,2e3).split(/\s+/))if(!(!r||Tn(r)))for(let n of r.split(/[^A-Za-z0-9+#.]+|(?<=[a-z0-9])(?=[A-Z])/)){let c=n.replace(/^[.]+|[.]+$/g,"").toLowerCase();if(!(c.length<3||c.length>24)&&!(/^\d+$/.test(c)||Cn.has(c))&&!e.includes(c)&&(e.push(c),e.length>=o))return e}return e}function Te(t){let o=[];typeof t.prompt=="string"&&o.push(t.prompt);let e=t.cwd;if(typeof e=="string"&&e.length>0){let r=e.replace(/[\\/]+$/,""),n=r.split(/[\\/]/).pop()??"",c=(process.env.HOME??process.env.USERPROFILE??"").replace(/[\\/]+$/,""),f=process.env.USER??process.env.USERNAME??"";r!==c&&n!==f&&n.length>0&&o.push(n.replace(/[-_]/g," "));}return jn(o.join(" "))}function je(t,o,e){let r=new Map;for(let{topic:n,at:c}of t)e-c<216e5&&r.set(n,c);for(let n of o)r.set(n,e);return [...r.entries()].map(([n,c])=>({topic:n,at:c})).sort((n,c)=>c.at-n.at).slice(0,24)}function dt(t,o){return t.filter(({at:e})=>o-e<216e5).sort((e,r)=>r.at-e.at).slice(0,12).map(({topic:e})=>e)}var On=false,An=process.platform==="win32"?8e3:3200,_n=150,In=2800,Re="claude_code";function Pn(t){let o={host:"claude_code"};for(let e=0;e<t.length;e++){let r=t[e],n=t[e+1];switch(r){case "--placement":n!==void 0&&(o.placement=n,e++);break;case "--key":n!==void 0&&(o.key=n,e++);break;case "--package":n!==void 0&&(o.package=n,e++);break;case "--host":(n==="claude_code"||n==="codex"||n==="openclaw"||n==="antigravity"||n==="copilot_cli"||n==="grok_cli"||n==="generic")&&(o.host=n,e++);break;}}return o}function Nn(t){return new Promise(o=>{if(process.stdin.isTTY){o("");return}let e="",r=false,n=()=>{r||(r=true,o(e));},c=setTimeout(n,t);c.unref?.(),process.stdin.setEncoding("utf8"),process.stdin.on("data",f=>{e+=f;}),process.stdin.on("end",()=>{clearTimeout(c),n();}),process.stdin.on("error",()=>{clearTimeout(c),n();});})}var $n="\\\\.\\CONOUT$";function Mn(t){return !t||t==="?"||t==="??"||t==="-"?null:t.startsWith("/")?t:`/dev/${t}`}function Ln(t){let o=t.match(/^\s*(\d+)\s+(\S+)/);return o?{ppid:Number(o[1]),tty:o[2]}:null}function Dn(t){if(!Number.isInteger(t)||t<=0)return null;let o=t>>8&4095,e=t&255|t>>12&1048320;return o>=136&&o<=143?`/dev/pts/${(o-136)*256+e}`:o===4?e<64?`/dev/tty${e}`:`/dev/ttyS${e-64}`:null}function Wn(t){let o=t.lastIndexOf(")");if(o<0)return null;let e=t.slice(o+1).trim().split(/\s+/),r=Number(e[1]),n=Number(e[4]);return !Number.isInteger(r)||!Number.isInteger(n)?null:{ppid:r,ttyNr:n}}function Hn(t){try{let o=Wn(h__namespace.readFileSync(`/proc/${t}/stat`,"utf8"));if(o)return {ppid:o.ppid,ttyPath:Dn(o.ttyNr)}}catch{}try{let o=child_process.spawnSync("ps",["-o","ppid=,tty=","-p",String(t)],{encoding:"utf8",timeout:1500}).stdout?.trim();if(!o)return null;let e=Ln(o);return e?{ppid:e.ppid,ttyPath:Mn(e.tty)}:null}catch{return null}}function Un(){if(process.platform==="win32")return {path:$n,ownerPid:null};let t=process.pid;for(let o=0;o<12&&t>1;o++){let e=Hn(t);if(!e)return null;if(e.ttyPath)return {path:e.ttyPath,ownerPid:t};t=e.ppid;}return null}function Bn(t){return t==="win32"?{detached:false,stdio:"ignore",windowsHide:false}:{detached:true,stdio:"ignore",windowsHide:false}}async function z(t,o,e,r,n,c){try{let f=y__namespace.join(__dirname,"paint.js"),p,u;if(c&&r){let g=K();c.kind==="dev"?(p=`${g}/v1/dev/impression`,u=c.token):p=`${g}/v1/events/impression`;}let a=fe(o.cachedConfig),d=Math.min(Math.max(a.displayDurationSeconds??25,3),120),s={...t,format:e?.format,mediaUrl:e?.mediaUrl,mediaPixelUrl:e?.mediaPixelUrl,audioUrl:e?.audioUrl,impressionId:r,campaignId:n,apiOrigin:K(),reportImpressionUrl:p,reportImpressionAuth:u,durationMs:d*1e3,disclosure:!o.disclosureShown,host:Re},i={...process.env,OPENCRATER_PAINT:JSON.stringify(s)};if(!i.OPENCRATER_TTY){let g=Un();g&&(i.OPENCRATER_TTY=g.path,g.ownerPid!==null&&(i.OPENCRATER_HOST_PID=String(g.ownerPid)));}let b=child_process.spawn(process.execPath,[f],{...Bn(process.platform),env:i});process.platform==="win32"?await new Promise(g=>{let m=!1,l=()=>{m||(m=!0,g());};b.on("exit",l),b.on("error",l),setTimeout(l,7500);}):b.unref();}catch{}return {...o,lastShownAt:Date.now(),disclosureShown:true}}function pt(t){if(process.platform!=="win32")return false;try{let o=y__namespace.join(N__namespace.homedir(),".config","opencrater","painter.lock"),e=JSON.parse(h__namespace.readFileSync(o,"utf8"));if(typeof e.startedAt!="number"||Date.now()-e.startedAt>t+1500)return !1;if(typeof e.pid=="number")try{process.kill(e.pid,0);}catch(r){if(r.code==="ESRCH")return !1}return !0}catch{return false}}var Fn=8e3;function mt(){let t=y__namespace.join(N__namespace.homedir(),".config","opencrater","render.lock");try{let o=h__namespace.statSync(t);if(Date.now()-o.mtimeMs<Fn)return !1;h__namespace.unlinkSync(t);}catch{}try{return h__namespace.mkdirSync(y__namespace.join(N__namespace.homedir(),".config","opencrater"),{recursive:!0}),h__namespace.writeFileSync(t,String(process.pid),{flag:"wx"}),!0}catch{return false}}function qn(t,o,e,r){if(!o)return true;let n=t.allowedPlacements[`${o}:${e}`];return n?n.includes(r):o==="opencrater"?_e[e].includes(r):true}var Gn=1440*60*1e3;function zn(){try{let t=y__namespace.join(N__namespace.homedir(),".config","opencrater","runtime"),o=y__namespace.join(t,"node_modules","opencrater","dist","hook.js"),e=y__namespace.join(t,".last-update");if(h__namespace.existsSync(o)){try{if(Date.now()-h__namespace.statSync(e).mtimeMs<Gn)return}catch{}try{h__namespace.writeFileSync(e,String(Date.now()));}catch{return}}else {let r=y__namespace.join(t,".installing");try{h__namespace.mkdirSync(t,{recursive:!0});let n=h__namespace.statSync(r);if(Date.now()-n.mtimeMs<600*1e3)return}catch{}h__namespace.writeFileSync(r,String(Date.now()));}ve(t);}catch{}}function gt(t,o){if(!o)return false;let e=f=>f.split(/[-+]/)[0].split(".").map(p=>parseInt(p,10)||0),r=e(t),n=e(o),c=Math.max(r.length,n.length);for(let f=0;f<c;f++){let p=r[f]??0,u=n[f]??0;if(p!==u)return p<u}return false}function ht(){try{let t=y__namespace.join(N__namespace.homedir(),".config","opencrater","runtime"),o=y__namespace.join(t,".last-update"),e=y__namespace.join(t,".force-update");try{if(Date.now()-h__namespace.statSync(e).mtimeMs<600*1e3)return}catch{}h__namespace.mkdirSync(t,{recursive:!0}),h__namespace.writeFileSync(e,String(Date.now()));try{h__namespace.rmSync(o,{force:!0});}catch{}ve(t);}catch{}}function Jn(){try{let t=y__namespace.join(N__namespace.homedir(),".config","opencrater");h__namespace.mkdirSync(t,{recursive:!0}),h__namespace.writeFileSync(y__namespace.join(t,"activity.signal"),String(Date.now()));}catch{}}var Kn=1440*60*1e3;function Yn(){try{let t=y__namespace.join(N__namespace.homedir(),".config","opencrater"),o=y__namespace.join(t,".last-host-check"),e=y__namespace.join(t,".known-hosts"),r=y__namespace.join(t,".wired-version"),n=we().sort(),c=[];try{let d=JSON.parse(h__namespace.readFileSync(e,"utf8"));Array.isArray(d)&&(c=d.filter(s=>typeof s=="string"));}catch{}let f=n.some(d=>!c.includes(d)),p="";try{p=h__namespace.readFileSync(r,"utf8").trim();}catch{}if(!f&&!(p!==A))try{if(Date.now()-h__namespace.statSync(o).mtimeMs<Kn)return}catch{}h__namespace.mkdirSync(t,{recursive:!0});try{h__namespace.writeFileSync(o,String(Date.now()));}catch{return}let a=me();try{h__namespace.writeFileSync(e,JSON.stringify(n)),h__namespace.writeFileSync(r,A);}catch{}if(a.optOut)return;if(a.devToken)try{Se();}catch{}for(let d of a.integrations)try{Se(d.key,d.package);}catch{}}catch{}}async function Vn(){let t=Pn(process.argv.slice(2));if(Re=t.host,process.env.GROK_HOOK_EVENT&&Re!=="grok_cli")return;Jn(),zn(),Yn();let o=await Nn(_n),e={};if(o)try{e=JSON.parse(o);let m=e.hook_event_name;!t.placement&&typeof m=="string"&&(t.placement=m);}catch{}let r=t.placement??"SessionStart",n=me();x(`state=${Z()} devToken=${n.devToken?"present":"MISSING"}`,`host=${t.host} placement=${r}`);let c=ut({env:process.env,state:n,now:Date.now()},{skipTTY:true});if(c!==null){if(c==="frequency"){let m=Te(e);m.length>0&&C({...n,sessionTopics:je(n.sessionTopics,m,Date.now())});}x("hook suppressed:",c);return}if(n={...n,sessionTopics:je(n.sessionTopics,Te(e),Date.now())},!qn(n,t.package,t.host,r)){C(n),x("hook gated: placement",r,"not selected for",t.package);return}let f=fe(n.cachedConfig),p=K(),u=typeof e?.cwd=="string"&&e.cwd||process.cwd(),a=De(u),d=n.attrTags??[];if(n.attrTagsCwd!==a||!n.attrTagsAt||Date.now()-n.attrTagsAt>Y){try{d=We(u);}catch{d=[];}n={...n,attrTags:d,attrTagsCwd:a,attrTagsAt:Date.now()};}let s={origin:p,timeoutMs:Math.min(f.serveTimeoutMs,In),installId:n.installId,topics:dt(n.sessionTopics,Date.now()),tags:d};if(n.devToken){let m=await Le(n.devToken,{publisherKey:t.key??"",packageName:t.package??"",placement:r,host:t.host},s);if(m){if(n={...n,cachedConfig:m.config,configFetchedAt:Date.now()},gt(A,m.config.minSdkVersion)&&ht(),On);let l=t.host??"claude_code",I=nt(l,r),k=n.computeCards??{turns:0,lastLimitAt:0,lastDepletedAt:0,lastBackupAt:0};I&&(k.turns+=1);let j=rt({balanceMicroUsd:typeof m.computeBalanceMicroUsd=="number"?m.computeBalanceMicroUsd:null,weeklyGrantMicroUsd:typeof m.weeklyGrantMicroUsd=="number"?m.weeklyGrantMicroUsd:null,pendingMicroUsd:typeof m.pendingMicroUsd=="number"?m.pendingMicroUsd:null,onGateway:(process.env.ANTHROPIC_BASE_URL??"").includes("/gateway")||process.env.OPENCRATER_ON_GATEWAY==="1",turnEnd:I,hostName:l,host:tt(l),cc:k,now:Date.now()}),ue=(m.config.displayDurationSeconds??25)*1e3,T=m.fill&&m.blip&&!Q(m.blip.campaignId)&&!te(m.blip.campaignId)?m.blip:null;if((j||T)&&!pt(ue)&&mt())if(j){let R=Date.now();j.kind==="limit"?k.lastLimitAt=R:j.kind==="depleted"?k.lastDepletedAt=R:j.kind==="backup"&&(k.lastBackupAt=R),n=await z({...j.card,label:"OpenCrater"},n);}else T&&(ee(T.campaignId),n=await z(V(T),n,T.creative,T.impressionId,T.campaignId,n.devToken?{kind:"dev",token:n.devToken}:void 0));n={...n,computeCards:k};}C(n);return}let{blip:i,pool:b}=he(n,Date.now());for(;i&&(Q(i.campaignId)||te(i.campaignId));)x("hook: pooled blip skipped \u2014 campaign inside a local cooldown"),{blip:i,pool:b}=he({pool:b},Date.now());if((i||t.key)&&pt((f.displayDurationSeconds??25)*1e3)){C(n),x("hook: a card is already on screen \u2014 not rendering another");return}if((i||t.key)&&!mt()){C(n),x("hook: render slot already claimed by a concurrent fire");return}if(i){ee(i.campaignId),n=await z(V(i),{...n,pool:b},i.creative,i.impressionId,i.campaignId,{kind:"publisher"}),C(n);return}if(b.length!==n.pool.length&&(n={...n,pool:b}),!t.key||!t.package){C(n),x("hook: pool empty and no --key/--package; nothing to render");return}let g=await Me({publisherKey:t.key,packageName:t.package,placement:r,host:t.host},s);if(!g){C(n);return}if(n={...n,cachedConfig:g.config,configFetchedAt:Date.now()},gt(A,g.config.minSdkVersion)&&(x(`SDK ${A} below floor ${g.config.minSdkVersion} \u2014 forcing runtime update`),ht()),t.package&&g.allowedPlacements&&(n={...n,allowedPlacements:{...n.allowedPlacements,[`${t.package}:${t.host}`]:g.allowedPlacements}}),g.fill&&g.blip){if(Q(g.blip.campaignId)||te(g.blip.campaignId)){x("hook: served blip suppressed \u2014 campaign inside a local cooldown"),C(n);return}ee(g.blip.campaignId),n=await z(V(g.blip),n,g.blip.creative,g.blip.impressionId,g.blip.campaignId,{kind:"publisher"}),C(n);return}g.fallback&&(n=await z(Ue(g.fallback),n)),C(n);}if(typeof M<"u"&&typeof module<"u"&&M.main===module){let t=setTimeout(()=>process.exit(0),An);Vn().catch(o=>x(`opencrater-hook v${A} error:`,o)).finally(()=>{clearTimeout(t),process.exit(0);});}
12
+ `;}return o}function on(t){try{let o=y__namespace.join(re("grok_cli",t),"config.toml"),e="";try{e=g__namespace.readFileSync(o,"utf8");}catch{}let r=nn(e);if(r===e)return;g__namespace.mkdirSync(y__namespace.dirname(o),{recursive:!0}),g__namespace.writeFileSync(o,r,"utf8");}catch{}}function rn(t,o,e){let r=Ve(t);return r.length===0?"nochange":(t==="grok_cli"&&on(process.env),t==="copilot_cli"?tn(t,o,e,r):t==="antigravity"?Qt(o,e,r):Kt(t,o,e,r))}function Se(t,o,e=process.env){return we(e).map(r=>{try{let n=rn(r,t,o);return {host:r,status:n,events:Ve(r)}}catch(n){return {host:r,status:"error",events:[],error:n.message}}})}function an(){return y__namespace.join(N__namespace.homedir(),".config","opencrater","runtime")}function cn(t){return ["install","--prefix",t,"opencrater@latest","--silent","--no-audit","--no-fund"]}function ve(t=an()){child_process.spawn("npm",cn(t),process.platform==="win32"?{detached:false,stdio:"ignore",windowsHide:true,shell:true}:{detached:true,stdio:"ignore"}).unref();}var et={atLimit:false,resetAt:null};function tt(t,o=N__namespace.homedir()){try{if(t==="claude_code")return ln(o);if(t==="codex")return fn(o)}catch{}return et}function ln(t){let o=g__namespace.readFileSync(y__namespace.join(t,".claude.json"),"utf8"),e=JSON.parse(o),r=e.hasAvailableSubscription===false||e.cachedExtraUsageDisabledReason==="out_of_credits",n=null,p=e.cachedGrowthBookFeatures?.tengu_saffron_lattice?.planLimitsEndDate;if(typeof p=="string"){let u=Date.parse(p);Number.isFinite(u)&&(n=u);}return {atLimit:r,resetAt:n}}function fn(t){return g__namespace.accessSync(y__namespace.join(t,".codex","auth.json")),et}function nt(t,o){return t==="copilot_cli"?o==="agentStop":o==="Stop"}var ot=36e5,un=30*6e4,dn=30*6e4,pn=4*ot,mn=3,ae="https://opencrater.to/dashboard";function G(t){return `${Math.round(t/1e3).toLocaleString()} tokens`}function gn(t){let o=t/1e3;return o>0&&o<10?`${(Math.round(o*10)/10).toFixed(1)} tokens`:`${Math.round(o).toLocaleString()} tokens`}function hn(t){switch(t){case "claude_code":return {name:"Claude Code",launch:"opencrater claude",resume:"opencrater claude -c"};case "codex":return {name:"Codex",launch:"opencrater codex",resume:"opencrater codex -c"};case "grok_cli":return {name:"Grok",launch:"opencrater grok",resume:"opencrater grok -c"};default:return null}}var ce="opencrater claude";function yn(t,o){if(!t||t<=o)return "";let e=t-o,r=e>=864e5?`${Math.floor(e/864e5)}d`:`${Math.max(1,Math.floor(e/ot))}h`,n=new Date(t).toISOString().slice(0,10);return ` Your host limit resets in ${r} (${n}).`}function rt(t){let{balanceMicroUsd:o,pendingMicroUsd:e,onGateway:r,turnEnd:n,hostName:c,host:f,cc:p,now:u}=t;if(o===null)return null;let a=hn(c),d=e&&e>0?` (+${gn(e)} pending)`:"";return o<=0?u-(p.lastDepletedAt??0)<dn?null:{kind:"depleted",card:{sponsorLabel:"OpenCrater",title:"Compute used up",body:`Keep coding in any CLI to earn more compute, then switch back to ${a?.name??"your plan"}.`+yn(f.resetAt,u),url:ae,cta:"Earn more"}}:r?!n||(p.turns??0)%mn!==0?null:{kind:"hud",card:{sponsorLabel:"OpenCrater",title:"Running on OpenCrater compute",body:`${G(o)} compute available${d}.`,url:ae,cta:"Wallet"}}:f.atLimit?u-(p.lastLimitAt??0)<un?null:{kind:"limit",card:{sponsorLabel:"OpenCrater",title:"Hit your limit? You've got compute",body:a?`${G(o)} of OpenCrater compute is ready. Continue this ${a.name} session now: ${a.resume}`:`${G(o)} of OpenCrater compute is ready. Run your coding agent on it: ${ce}`,url:ae,cta:a?a.resume:ce}}:u-(p.lastBackupAt??0)>=pn?{kind:"backup",card:{sponsorLabel:"OpenCrater",title:"Backup compute ready",body:a?`${G(o)} of OpenCrater compute waiting${d}. When you hit your limit: ${a.resume}`:`${G(o)} of OpenCrater compute waiting${d}. Spend it any time: ${ce}`,url:ae,cta:a?a.resume:ce}}:null}var Sn=["CI","CONTINUOUS_INTEGRATION","GITHUB_ACTIONS","GITLAB_CI","CIRCLECI","TRAVIS","BUILDKITE","JENKINS_URL","TEAMCITY_VERSION","TF_BUILD","APPVEYOR","CODEBUILD_BUILD_ID","DRONE","NETLIFY","VERCEL"];function Ce(t){return t!==void 0&&t!==""&&t!=="0"&&t.toLowerCase()!=="false"}function vn(t){return Ce(t.OPENCRATER_DISABLE)||Ce(t.TSN_DISABLE)}function xn(t){return Sn.some(o=>Ce(t[o]))}function fe(t){return t?{...H,...t}:H}function ut(t,o={}){if(vn(t.env))return "env_disabled";if(t.state.optOut)return "opt_out";let e=fe(t.state.cachedConfig);if(e.killSwitch)return "kill_switch";if(xn(t.env))return "ci";if(!o.skipTTY&&false);if(!o.skipFrequency){let r=e.minIntervalSeconds*1e3;if(t.state.lastShownAt>0&&t.now-t.state.lastShownAt<r)return "frequency"}return null}var Cn=new Set(["the","and","for","but","not","you","all","any","can","this","that","with","have","will","your","from","they","what","when","where","how","why","make","fix","add","update","remove","create","delete","change","error","errors","bug","bugs","file","files","code","test","tests","run","running","build","please","help","want","need","should","would","could","into","about","then","here","there","now","new","use","using","used","work","working","works","check","show","see","look","get","set","let","lets","dont","cant","issue"]);function Tn(t){if(t.includes("/")||t.includes("\\")||t.includes("@")||t.includes("://"))return true;let o=t.toLowerCase();return !!(/^(sk|pk|rk|ock|ghp|gho|ghs|xox|akia|eyj|npm|glpat)[-_]/.test(o)||t.length>=16&&/^[0-9a-f]+$/i.test(t)||t.length>=20&&/^[A-Za-z0-9+/=_-]+$/.test(t)&&/[A-Z]/.test(t)&&/[0-9]/.test(t))}function jn(t,o=12){let e=[];for(let r of t.slice(0,2e3).split(/\s+/))if(!(!r||Tn(r)))for(let n of r.split(/[^A-Za-z0-9+#.]+|(?<=[a-z0-9])(?=[A-Z])/)){let c=n.replace(/^[.]+|[.]+$/g,"").toLowerCase();if(!(c.length<3||c.length>24)&&!(/^\d+$/.test(c)||Cn.has(c))&&!e.includes(c)&&(e.push(c),e.length>=o))return e}return e}function Te(t){let o=[];typeof t.prompt=="string"&&o.push(t.prompt);let e=t.cwd;if(typeof e=="string"&&e.length>0){let r=e.replace(/[\\/]+$/,""),n=r.split(/[\\/]/).pop()??"",c=(process.env.HOME??process.env.USERPROFILE??"").replace(/[\\/]+$/,""),f=process.env.USER??process.env.USERNAME??"";r!==c&&n!==f&&n.length>0&&o.push(n.replace(/[-_]/g," "));}return jn(o.join(" "))}function je(t,o,e){let r=new Map;for(let{topic:n,at:c}of t)e-c<216e5&&r.set(n,c);for(let n of o)r.set(n,e);return [...r.entries()].map(([n,c])=>({topic:n,at:c})).sort((n,c)=>c.at-n.at).slice(0,24)}function dt(t,o){return t.filter(({at:e})=>o-e<216e5).sort((e,r)=>r.at-e.at).slice(0,12).map(({topic:e})=>e)}var On=false,An=process.platform==="win32"?8e3:3200,_n=150,In=2800,Re="claude_code";function Pn(t){let o={host:"claude_code"};for(let e=0;e<t.length;e++){let r=t[e],n=t[e+1];switch(r){case "--placement":n!==void 0&&(o.placement=n,e++);break;case "--key":n!==void 0&&(o.key=n,e++);break;case "--package":n!==void 0&&(o.package=n,e++);break;case "--host":(n==="claude_code"||n==="codex"||n==="openclaw"||n==="antigravity"||n==="copilot_cli"||n==="grok_cli"||n==="generic")&&(o.host=n,e++);break;}}return o}function Nn(t){return new Promise(o=>{if(process.stdin.isTTY){o("");return}let e="",r=false,n=()=>{r||(r=true,o(e));},c=setTimeout(n,t);c.unref?.(),process.stdin.setEncoding("utf8"),process.stdin.on("data",f=>{e+=f;}),process.stdin.on("end",()=>{clearTimeout(c),n();}),process.stdin.on("error",()=>{clearTimeout(c),n();});})}var $n="\\\\.\\CONOUT$";function Mn(t){return !t||t==="?"||t==="??"||t==="-"?null:t.startsWith("/")?t:`/dev/${t}`}function Ln(t){let o=t.match(/^\s*(\d+)\s+(\S+)/);return o?{ppid:Number(o[1]),tty:o[2]}:null}function Dn(t){if(!Number.isInteger(t)||t<=0)return null;let o=t>>8&4095,e=t&255|t>>12&1048320;return o>=136&&o<=143?`/dev/pts/${(o-136)*256+e}`:o===4?e<64?`/dev/tty${e}`:`/dev/ttyS${e-64}`:null}function Wn(t){let o=t.lastIndexOf(")");if(o<0)return null;let e=t.slice(o+1).trim().split(/\s+/),r=Number(e[1]),n=Number(e[4]);return !Number.isInteger(r)||!Number.isInteger(n)?null:{ppid:r,ttyNr:n}}function Hn(t){try{let o=Wn(g__namespace.readFileSync(`/proc/${t}/stat`,"utf8"));if(o)return {ppid:o.ppid,ttyPath:Dn(o.ttyNr)}}catch{}try{let o=child_process.spawnSync("ps",["-o","ppid=,tty=","-p",String(t)],{encoding:"utf8",timeout:1500}).stdout?.trim();if(!o)return null;let e=Ln(o);return e?{ppid:e.ppid,ttyPath:Mn(e.tty)}:null}catch{return null}}function Un(){if(process.platform==="win32")return {path:$n,ownerPid:null};let t=process.pid;for(let o=0;o<12&&t>1;o++){let e=Hn(t);if(!e)return null;if(e.ttyPath)return {path:e.ttyPath,ownerPid:t};t=e.ppid;}return null}function Bn(t){return t==="win32"?{detached:false,stdio:"ignore",windowsHide:false}:{detached:true,stdio:"ignore",windowsHide:false}}async function z(t,o,e,r,n,c,f){try{let p=y__namespace.join(__dirname,"paint.js"),u,a;if(c&&r){let m=K();c.kind==="dev"?(u=`${m}/v1/dev/impression`,a=c.token):u=`${m}/v1/events/impression`;}let d=fe(o.cachedConfig),s=Math.min(Math.max(d.displayDurationSeconds??25,3),120),i={...t,format:e?.format,mediaUrl:e?.mediaUrl,mediaPixelUrl:e?.mediaPixelUrl,audioUrl:e?.audioUrl,impressionId:r,campaignId:n,apiOrigin:K(),reportImpressionUrl:u,reportImpressionAuth:a,renderToken:f,durationMs:s*1e3,disclosure:!o.disclosureShown,host:Re},b={...process.env,OPENCRATER_PAINT:JSON.stringify(i)};if(!b.OPENCRATER_TTY){let m=Un();m&&(b.OPENCRATER_TTY=m.path,m.ownerPid!==null&&(b.OPENCRATER_HOST_PID=String(m.ownerPid)));}let h=child_process.spawn(process.execPath,[p],{...Bn(process.platform),env:b});process.platform==="win32"?await new Promise(m=>{let l=!1,T=()=>{l||(l=!0,m());};h.on("exit",T),h.on("error",T),setTimeout(T,7500);}):h.unref();}catch{}return {...o,lastShownAt:Date.now(),disclosureShown:true}}function pt(t){if(process.platform!=="win32")return false;try{let o=y__namespace.join(N__namespace.homedir(),".config","opencrater","painter.lock"),e=JSON.parse(g__namespace.readFileSync(o,"utf8"));if(typeof e.startedAt!="number"||Date.now()-e.startedAt>t+1500)return !1;if(typeof e.pid=="number")try{process.kill(e.pid,0);}catch(r){if(r.code==="ESRCH")return !1}return !0}catch{return false}}var Fn=8e3;function mt(){let t=y__namespace.join(N__namespace.homedir(),".config","opencrater","render.lock");try{let o=g__namespace.statSync(t);if(Date.now()-o.mtimeMs<Fn)return !1;g__namespace.unlinkSync(t);}catch{}try{return g__namespace.mkdirSync(y__namespace.join(N__namespace.homedir(),".config","opencrater"),{recursive:!0}),g__namespace.writeFileSync(t,String(process.pid),{flag:"wx"}),!0}catch{return false}}function qn(t,o,e,r){if(!o)return true;let n=t.allowedPlacements[`${o}:${e}`];return n?n.includes(r):o==="opencrater"?_e[e].includes(r):true}var Gn=1440*60*1e3;function zn(){try{let t=y__namespace.join(N__namespace.homedir(),".config","opencrater","runtime"),o=y__namespace.join(t,"node_modules","opencrater","dist","hook.js"),e=y__namespace.join(t,".last-update");if(g__namespace.existsSync(o)){try{if(Date.now()-g__namespace.statSync(e).mtimeMs<Gn)return}catch{}try{g__namespace.writeFileSync(e,String(Date.now()));}catch{return}}else {let r=y__namespace.join(t,".installing");try{g__namespace.mkdirSync(t,{recursive:!0});let n=g__namespace.statSync(r);if(Date.now()-n.mtimeMs<600*1e3)return}catch{}g__namespace.writeFileSync(r,String(Date.now()));}ve(t);}catch{}}function gt(t,o){if(!o)return false;let e=f=>f.split(/[-+]/)[0].split(".").map(p=>parseInt(p,10)||0),r=e(t),n=e(o),c=Math.max(r.length,n.length);for(let f=0;f<c;f++){let p=r[f]??0,u=n[f]??0;if(p!==u)return p<u}return false}function ht(){try{let t=y__namespace.join(N__namespace.homedir(),".config","opencrater","runtime"),o=y__namespace.join(t,".last-update"),e=y__namespace.join(t,".force-update");try{if(Date.now()-g__namespace.statSync(e).mtimeMs<600*1e3)return}catch{}g__namespace.mkdirSync(t,{recursive:!0}),g__namespace.writeFileSync(e,String(Date.now()));try{g__namespace.rmSync(o,{force:!0});}catch{}ve(t);}catch{}}function Jn(){try{let t=y__namespace.join(N__namespace.homedir(),".config","opencrater");g__namespace.mkdirSync(t,{recursive:!0}),g__namespace.writeFileSync(y__namespace.join(t,"activity.signal"),String(Date.now()));}catch{}}var Kn=1440*60*1e3;function Yn(){try{let t=y__namespace.join(N__namespace.homedir(),".config","opencrater"),o=y__namespace.join(t,".last-host-check"),e=y__namespace.join(t,".known-hosts"),r=y__namespace.join(t,".wired-version"),n=we().sort(),c=[];try{let d=JSON.parse(g__namespace.readFileSync(e,"utf8"));Array.isArray(d)&&(c=d.filter(s=>typeof s=="string"));}catch{}let f=n.some(d=>!c.includes(d)),p="";try{p=g__namespace.readFileSync(r,"utf8").trim();}catch{}if(!f&&!(p!==_))try{if(Date.now()-g__namespace.statSync(o).mtimeMs<Kn)return}catch{}g__namespace.mkdirSync(t,{recursive:!0});try{g__namespace.writeFileSync(o,String(Date.now()));}catch{return}let a=me();try{g__namespace.writeFileSync(e,JSON.stringify(n)),g__namespace.writeFileSync(r,_);}catch{}if(a.optOut)return;if(a.devToken)try{Se();}catch{}for(let d of a.integrations)try{Se(d.key,d.package);}catch{}}catch{}}async function Vn(){let t=Pn(process.argv.slice(2));if(Re=t.host,process.env.GROK_HOOK_EVENT&&Re!=="grok_cli")return;Jn(),zn(),Yn();let o=await Nn(_n),e={};if(o)try{e=JSON.parse(o);let m=e.hook_event_name;!t.placement&&typeof m=="string"&&(t.placement=m);}catch{}let r=t.placement??"SessionStart",n=me();x(`state=${Z()} devToken=${n.devToken?"present":"MISSING"}`,`host=${t.host} placement=${r}`);let c=ut({env:process.env,state:n,now:Date.now()},{skipTTY:true});if(c!==null){if(c==="frequency"){let m=Te(e);m.length>0&&C({...n,sessionTopics:je(n.sessionTopics,m,Date.now())});}x("hook suppressed:",c);return}if(n={...n,sessionTopics:je(n.sessionTopics,Te(e),Date.now())},!qn(n,t.package,t.host,r)){C(n),x("hook gated: placement",r,"not selected for",t.package);return}let f=fe(n.cachedConfig),p=K(),u=typeof e?.cwd=="string"&&e.cwd||process.cwd(),a=De(u),d=n.attrTags??[];if(n.attrTagsCwd!==a||!n.attrTagsAt||Date.now()-n.attrTagsAt>Y){try{d=We(u);}catch{d=[];}n={...n,attrTags:d,attrTagsCwd:a,attrTagsAt:Date.now()};}let s={origin:p,timeoutMs:Math.min(f.serveTimeoutMs,In),installId:n.installId,topics:dt(n.sessionTopics,Date.now()),tags:d};if(n.devToken){let m=await Le(n.devToken,{publisherKey:t.key??"",packageName:t.package??"",placement:r,host:t.host},s);if(m){if(n={...n,cachedConfig:m.config,configFetchedAt:Date.now()},gt(_,m.config.minSdkVersion)&&ht(),On);let l=t.host??"claude_code",T=nt(l,r),k=n.computeCards??{turns:0,lastLimitAt:0,lastDepletedAt:0,lastBackupAt:0};T&&(k.turns+=1);let R=rt({balanceMicroUsd:typeof m.computeBalanceMicroUsd=="number"?m.computeBalanceMicroUsd:null,weeklyGrantMicroUsd:typeof m.weeklyGrantMicroUsd=="number"?m.weeklyGrantMicroUsd:null,pendingMicroUsd:typeof m.pendingMicroUsd=="number"?m.pendingMicroUsd:null,onGateway:(process.env.ANTHROPIC_BASE_URL??"").includes("/gateway")||process.env.OPENCRATER_ON_GATEWAY==="1",turnEnd:T,hostName:l,host:tt(l),cc:k,now:Date.now()}),ue=(m.config.displayDurationSeconds??25)*1e3,j=m.fill&&m.blip&&!Q(m.blip.campaignId)&&!te(m.blip.campaignId)?m.blip:null;if((R||j)&&!pt(ue)&&mt())if(R){let E=Date.now();R.kind==="limit"?k.lastLimitAt=E:R.kind==="depleted"?k.lastDepletedAt=E:R.kind==="backup"&&(k.lastBackupAt=E),n=await z({...R.card,label:"OpenCrater"},n);}else j&&(ee(j.campaignId),n=await z(V(j),n,j.creative,j.impressionId,j.campaignId,n.devToken?{kind:"dev",token:n.devToken}:void 0,j.renderToken));n={...n,computeCards:k};}C(n);return}let{blip:i,pool:b}=he(n,Date.now());for(;i&&(Q(i.campaignId)||te(i.campaignId));)x("hook: pooled blip skipped \u2014 campaign inside a local cooldown"),{blip:i,pool:b}=he({pool:b},Date.now());if((i||t.key)&&pt((f.displayDurationSeconds??25)*1e3)){C(n),x("hook: a card is already on screen \u2014 not rendering another");return}if((i||t.key)&&!mt()){C(n),x("hook: render slot already claimed by a concurrent fire");return}if(i){ee(i.campaignId),n=await z(V(i),{...n,pool:b},i.creative,i.impressionId,i.campaignId,{kind:"publisher"},i.renderToken),C(n);return}if(b.length!==n.pool.length&&(n={...n,pool:b}),!t.key||!t.package){C(n),x("hook: pool empty and no --key/--package; nothing to render");return}let h=await Me({publisherKey:t.key,packageName:t.package,placement:r,host:t.host},s);if(!h){C(n);return}if(n={...n,cachedConfig:h.config,configFetchedAt:Date.now()},gt(_,h.config.minSdkVersion)&&(x(`SDK ${_} below floor ${h.config.minSdkVersion} \u2014 forcing runtime update`),ht()),t.package&&h.allowedPlacements&&(n={...n,allowedPlacements:{...n.allowedPlacements,[`${t.package}:${t.host}`]:h.allowedPlacements}}),h.fill&&h.blip){if(Q(h.blip.campaignId)||te(h.blip.campaignId)){x("hook: served blip suppressed \u2014 campaign inside a local cooldown"),C(n);return}ee(h.blip.campaignId),n=await z(V(h.blip),n,h.blip.creative,h.blip.impressionId,h.blip.campaignId,{kind:"publisher"},h.blip.renderToken),C(n);return}h.fallback&&(n=await z(Ue(h.fallback),n)),C(n);}if(typeof M<"u"&&typeof module<"u"&&M.main===module){let t=setTimeout(()=>process.exit(0),An);Vn().catch(o=>x(`opencrater-hook v${_} error:`,o)).finally(()=>{clearTimeout(t),process.exit(0);});}
13
13
  exports.decodeTtyNr=Dn;exports.painterSpawnOptions=Bn;exports.parseArgs=Pn;exports.parseProcStat=Wn;exports.parsePsLine=Ln;exports.resolveTtyPath=Un;exports.ttyNameToDevPath=Mn;
package/dist/index.d.mts CHANGED
@@ -26,6 +26,11 @@ interface Blip {
26
26
  clickUrl: string;
27
27
  sponsorLabel: string;
28
28
  creative: Creative;
29
+ /** Render-proof from the serve response: HMAC binding this impression to the
30
+ * serve that issued it. Echoed back on the impression + engagement reports so
31
+ * the server can verify they came from a real serve. Optional — older servers
32
+ * don't return it; when absent the SDK simply omits it from reports. */
33
+ renderToken?: string;
29
34
  }
30
35
  /** Publisher funding fallback rendered when no campaign fills. */
31
36
  interface Fallback {
@@ -232,7 +237,7 @@ declare function renderBlip(blip: Blip, opts?: MediaRenderOptions): Promise<stri
232
237
 
233
238
  /** Keep in sync with package.json (bundled, so we avoid a runtime fs read).
234
239
  * AUTO-GENERATED by scripts/sync-version.mjs on `npm version`. */
235
- declare const SDK_VERSION = "1.4.5";
240
+ declare const SDK_VERSION = "1.4.7";
236
241
 
237
242
  /** Public API. Every method is fail-silent: it never throws. */
238
243
  declare const sponsor: {
package/dist/index.d.ts CHANGED
@@ -26,6 +26,11 @@ interface Blip {
26
26
  clickUrl: string;
27
27
  sponsorLabel: string;
28
28
  creative: Creative;
29
+ /** Render-proof from the serve response: HMAC binding this impression to the
30
+ * serve that issued it. Echoed back on the impression + engagement reports so
31
+ * the server can verify they came from a real serve. Optional — older servers
32
+ * don't return it; when absent the SDK simply omits it from reports. */
33
+ renderToken?: string;
29
34
  }
30
35
  /** Publisher funding fallback rendered when no campaign fills. */
31
36
  interface Fallback {
@@ -232,7 +237,7 @@ declare function renderBlip(blip: Blip, opts?: MediaRenderOptions): Promise<stri
232
237
 
233
238
  /** Keep in sync with package.json (bundled, so we avoid a runtime fs read).
234
239
  * AUTO-GENERATED by scripts/sync-version.mjs on `npm version`. */
235
- declare const SDK_VERSION = "1.4.5";
240
+ declare const SDK_VERSION = "1.4.7";
236
241
 
237
242
  /** Public API. Every method is fail-silent: it never throws. */
238
243
  declare const sponsor: {
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
- 'use strict';var crypto=require('crypto'),m=require('fs'),ie=require('os'),S=require('path');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 m__namespace=/*#__PURE__*/_interopNamespace(m);var ie__namespace=/*#__PURE__*/_interopNamespace(ie);var S__namespace=/*#__PURE__*/_interopNamespace(S);var q=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(n,t)=>(typeof require<"u"?require:n)[t]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var w={minIntervalSeconds:600,serveTimeoutMs:2500,preloadPoolSize:3,killSwitch:false,displayDurationSeconds:25,minSdkVersion:""};var le=["SessionStart","SessionEnd","Stop","PostToolUse","Notification"];var N="1.4.5";var ce="https://api.opencrater.to";function K(e,n=process.env){let t=n.OPENCRATER_API_ORIGIN;return (e??(t&&t.trim()!==""?t:ce)).replace(/\/+$/,"")}function c(...e){try{if(process.env.OPENCRATER_DEBUG!=="1")return;console.error("[opencrater]",...e);try{let n=q("os"),t=q("fs"),o=q("path");t.appendFileSync(o.join(n.homedir(),".config","opencrater","hook.log"),`${new Date().toISOString()} [opencrater] ${e.map(i=>String(i)).join(" ")}
2
- `);}catch{}}catch{}}function R(e){return typeof e=="number"&&Number.isFinite(e)}function V(e){let n=w;if(typeof e!="object"||e===null)return {...n};let t=e;return {minIntervalSeconds:R(t.minIntervalSeconds)?t.minIntervalSeconds:n.minIntervalSeconds,serveTimeoutMs:R(t.serveTimeoutMs)?t.serveTimeoutMs:n.serveTimeoutMs,preloadPoolSize:R(t.preloadPoolSize)?t.preloadPoolSize:n.preloadPoolSize,killSwitch:t.killSwitch===true,displayDurationSeconds:R(t.displayDurationSeconds)?t.displayDurationSeconds:n.displayDurationSeconds,minSdkVersion:typeof t.minSdkVersion=="string"?t.minSdkVersion:n.minSdkVersion}}async function D(e,n,t,o,i){try{let r=await fetch(`${e}${n}`,{method:"POST",headers:{"content-type":"application/json",...i??{}},body:JSON.stringify(t),signal:AbortSignal.timeout(o)});return r.ok?await r.json():(c(`POST ${n} -> HTTP ${r.status}`),null)}catch(r){return c(`POST ${n} failed:`,r),null}}function J(e,n){let t=e.host??"generic";return {publisherKey:e.publisherKey,packageName:e.packageName,placement:e.placement,host:t,sdkVersion:N,installId:n.installId,os:process.platform,termProgram:process.env.TERM_PROGRAM??void 0,topics:n.topics&&n.topics.length>0?n.topics:void 0,tags:n.tags&&n.tags.length>0?n.tags:void 0}}function fe(e){if(typeof e!="object"||e===null)return null;let n=e;if(typeof n.fill!="boolean")return null;let t={fill:n.fill,fallback:n.fallback??null,config:V(n.config),...Array.isArray(n.allowedPlacements)?{allowedPlacements:n.allowedPlacements.filter(o=>typeof o=="string")}:{}};return n.blip!==void 0&&n.blip!==null&&(t.blip=n.blip),typeof n.computeBalanceMicroUsd=="number"&&(t.computeBalanceMicroUsd=n.computeBalanceMicroUsd),typeof n.weeklyGrantMicroUsd=="number"&&(t.weeklyGrantMicroUsd=n.weeklyGrantMicroUsd),typeof n.pendingMicroUsd=="number"&&(t.pendingMicroUsd=n.pendingMicroUsd),t}async function F(e,n){let t=await D(n.origin,"/v1/serve",J(e,n),n.timeoutMs);return fe(t)}async function X(e,n,t){let o=await D(t.origin,"/v1/serve/batch",{...J(e,t),count:n},t.timeoutMs);if(typeof o!="object"||o===null)return null;let i=o;return Array.isArray(i.blips)?{blips:i.blips,fallback:i.fallback??null,config:V(i.config),...Array.isArray(i.allowedPlacements)?{allowedPlacements:i.allowedPlacements.filter(r=>typeof r=="string")}:{}}:null}function $(e,n){return D(n.origin,"/v1/events/impression",{impressionId:e},n.timeoutMs).then(()=>{}).catch(()=>{})}var ue=new RegExp("\x1B\\[[0-9;]*m|\x1B\\]8;;[^\x07\x1B]*(?:\x07|\x1B\\\\)","g"),k={dim:"\x1B[2m",bold:"\x1B[1m",reset:"\x1B[0m"},de=60,pe=24,me="\u2139 This project is supported by Blips via OpenCrater. Opt out: `npx opencrater off` or OPENCRATER_DISABLE=1";function ge(e){return e.replace(ue,"").length}function y(e,n){return n<=0?"":e.length<=n?e:n===1?"\u2026":e.slice(0,n-1).trimEnd()+"\u2026"}function he(e,n,t){let o=e.split(/\s+/).filter(l=>l.length>0),i=[],r="";for(let l of o){let u=r===""?l:`${r} ${l}`;if(u.length<=n)r=u;else if(r!==""&&i.push(r),r=l.length>n?y(l,n):l,i.length>=t)break}r!==""&&i.length<t&&i.push(r),i.length>t&&(i.length=t);let s=i.join(" "),a=i.length-1,f=i[a];return f!==void 0&&s.length<o.join(" ").length&&(i[a]=y(`${f}\u2026`,n)),i}function I(e=process.env,n=!!process.stdout.isTTY){if(!n)return false;if(e.FORCE_HYPERLINK!==void 0&&e.FORCE_HYPERLINK!=="0")return true;let t=e.TERM_PROGRAM??"";return !!(["iTerm.app","WezTerm","ghostty","Hyper","vscode","Tabby"].includes(t)||e.KITTY_WINDOW_ID||e.WT_SESSION||Number(e.VTE_VERSION??"0")>=5e3)}function P(e=process.env,n=!!process.stdout.isTTY){return !(e.NO_COLOR!==void 0&&e.NO_COLOR!==""||!n||(e.TERM??"")==="dumb")}function ye(e,n){return `\x1B]8;;${e}\x07${n}\x1B]8;;\x07`}function E(e){let n={sponsorLabel:e.sponsorLabel,title:e.creative.title,body:e.creative.body,url:e.clickUrl};return e.creative.cta!==void 0&&(n.cta=e.creative.cta),n}function Z(e){return {sponsorLabel:"",title:e.title,body:e.body,url:e.url}}function h(e,n={}){let t=n.width??process.stdout.columns??80,i=Math.max(pe,Math.min(t,de))-4,r=n.color??P(),s=n.hyperlinks??I(),a=(g,M)=>r?`${M}${g}${k.reset}`:g,f=e.label?y(e.label,i):e.sponsorLabel?y(`Sponsored Blips \xB7 ${e.sponsorLabel}`,i):"Sponsored Blips",l=[];l.push(a(f,k.dim)),e.title!==e.sponsorLabel&&l.push(a(y(e.title,i),k.bold));for(let g of he(e.body,i,2))l.push(g);let u="\u2192 ";if(s){let g=y(e.cta??e.url,i-u.length);l.push(u+a(ye(e.url,g),k.dim));}else e.cta&&l.push(y(e.cta,i)),l.push(u+a(y(e.url,i-u.length),k.dim));let T=`\u256D${"\u2500".repeat(i+2)}\u256E`,j=`\u2570${"\u2500".repeat(i+2)}\u256F`,L=l.map(g=>{let M=" ".repeat(Math.max(0,i-ge(g)));return `\u2502 ${g}${M} \u2502`}),b=[];return n.disclosure&&b.push(a(me,k.dim)),b.push(T,...L,j),b.join(`
1
+ 'use strict';var crypto=require('crypto'),m=require('fs'),ie=require('os'),S=require('path');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 m__namespace=/*#__PURE__*/_interopNamespace(m);var ie__namespace=/*#__PURE__*/_interopNamespace(ie);var S__namespace=/*#__PURE__*/_interopNamespace(S);var q=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(n,t)=>(typeof require<"u"?require:n)[t]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var w={minIntervalSeconds:600,serveTimeoutMs:2500,preloadPoolSize:3,killSwitch:false,displayDurationSeconds:25,minSdkVersion:""};var le=["SessionStart","SessionEnd","Stop","PostToolUse","Notification"];var N="1.4.7";var ce="https://api.opencrater.to";function K(e,n=process.env){let t=n.OPENCRATER_API_ORIGIN;return (e??(t&&t.trim()!==""?t:ce)).replace(/\/+$/,"")}function c(...e){try{if(process.env.OPENCRATER_DEBUG!=="1")return;console.error("[opencrater]",...e);try{let n=q("os"),t=q("fs"),o=q("path");t.appendFileSync(o.join(n.homedir(),".config","opencrater","hook.log"),`${new Date().toISOString()} [opencrater] ${e.map(i=>String(i)).join(" ")}
2
+ `);}catch{}}catch{}}function R(e){return typeof e=="number"&&Number.isFinite(e)}function V(e){let n=w;if(typeof e!="object"||e===null)return {...n};let t=e;return {minIntervalSeconds:R(t.minIntervalSeconds)?t.minIntervalSeconds:n.minIntervalSeconds,serveTimeoutMs:R(t.serveTimeoutMs)?t.serveTimeoutMs:n.serveTimeoutMs,preloadPoolSize:R(t.preloadPoolSize)?t.preloadPoolSize:n.preloadPoolSize,killSwitch:t.killSwitch===true,displayDurationSeconds:R(t.displayDurationSeconds)?t.displayDurationSeconds:n.displayDurationSeconds,minSdkVersion:typeof t.minSdkVersion=="string"?t.minSdkVersion:n.minSdkVersion}}async function D(e,n,t,o,i){try{let r=await fetch(`${e}${n}`,{method:"POST",headers:{"content-type":"application/json",...i??{}},body:JSON.stringify(t),signal:AbortSignal.timeout(o)});return r.ok?await r.json():(c(`POST ${n} -> HTTP ${r.status}`),null)}catch(r){return c(`POST ${n} failed:`,r),null}}function J(e,n){let t=e.host??"generic";return {publisherKey:e.publisherKey,packageName:e.packageName,placement:e.placement,host:t,sdkVersion:N,installId:n.installId,os:process.platform,termProgram:process.env.TERM_PROGRAM??void 0,topics:n.topics&&n.topics.length>0?n.topics:void 0,tags:n.tags&&n.tags.length>0?n.tags:void 0}}function fe(e){if(typeof e!="object"||e===null)return null;let n=e;if(typeof n.fill!="boolean")return null;let t={fill:n.fill,fallback:n.fallback??null,config:V(n.config),...Array.isArray(n.allowedPlacements)?{allowedPlacements:n.allowedPlacements.filter(o=>typeof o=="string")}:{}};return n.blip!==void 0&&n.blip!==null&&(t.blip=n.blip),typeof n.computeBalanceMicroUsd=="number"&&(t.computeBalanceMicroUsd=n.computeBalanceMicroUsd),typeof n.weeklyGrantMicroUsd=="number"&&(t.weeklyGrantMicroUsd=n.weeklyGrantMicroUsd),typeof n.pendingMicroUsd=="number"&&(t.pendingMicroUsd=n.pendingMicroUsd),t}async function F(e,n){let t=await D(n.origin,"/v1/serve",J(e,n),n.timeoutMs);return fe(t)}async function X(e,n,t){let o=await D(t.origin,"/v1/serve/batch",{...J(e,t),count:n},t.timeoutMs);if(typeof o!="object"||o===null)return null;let i=o;return Array.isArray(i.blips)?{blips:i.blips,fallback:i.fallback??null,config:V(i.config),...Array.isArray(i.allowedPlacements)?{allowedPlacements:i.allowedPlacements.filter(r=>typeof r=="string")}:{}}:null}function $(e,n,t){return D(n.origin,"/v1/events/impression",{impressionId:e,...t?{renderToken:t}:{}},n.timeoutMs).then(()=>{}).catch(()=>{})}var ue=new RegExp("\x1B\\[[0-9;]*m|\x1B\\]8;;[^\x07\x1B]*(?:\x07|\x1B\\\\)","g"),k={dim:"\x1B[2m",bold:"\x1B[1m",reset:"\x1B[0m"},de=60,pe=24,me="\u2139 This project is supported by Blips via OpenCrater. Opt out: `npx opencrater off` or OPENCRATER_DISABLE=1";function ge(e){return e.replace(ue,"").length}function y(e,n){return n<=0?"":e.length<=n?e:n===1?"\u2026":e.slice(0,n-1).trimEnd()+"\u2026"}function he(e,n,t){let o=e.split(/\s+/).filter(l=>l.length>0),i=[],r="";for(let l of o){let u=r===""?l:`${r} ${l}`;if(u.length<=n)r=u;else if(r!==""&&i.push(r),r=l.length>n?y(l,n):l,i.length>=t)break}r!==""&&i.length<t&&i.push(r),i.length>t&&(i.length=t);let s=i.join(" "),a=i.length-1,f=i[a];return f!==void 0&&s.length<o.join(" ").length&&(i[a]=y(`${f}\u2026`,n)),i}function I(e=process.env,n=!!process.stdout.isTTY){if(!n)return false;if(e.FORCE_HYPERLINK!==void 0&&e.FORCE_HYPERLINK!=="0")return true;let t=e.TERM_PROGRAM??"";return !!(["iTerm.app","WezTerm","ghostty","Hyper","vscode","Tabby"].includes(t)||e.KITTY_WINDOW_ID||e.WT_SESSION||Number(e.VTE_VERSION??"0")>=5e3)}function P(e=process.env,n=!!process.stdout.isTTY){return !(e.NO_COLOR!==void 0&&e.NO_COLOR!==""||!n||(e.TERM??"")==="dumb")}function ye(e,n){return `\x1B]8;;${e}\x07${n}\x1B]8;;\x07`}function E(e){let n={sponsorLabel:e.sponsorLabel,title:e.creative.title,body:e.creative.body,url:e.clickUrl};return e.creative.cta!==void 0&&(n.cta=e.creative.cta),n}function Z(e){return {sponsorLabel:"",title:e.title,body:e.body,url:e.url}}function h(e,n={}){let t=n.width??process.stdout.columns??80,i=Math.max(pe,Math.min(t,de))-4,r=n.color??P(),s=n.hyperlinks??I(),a=(g,M)=>r?`${M}${g}${k.reset}`:g,f=e.label?y(e.label,i):e.sponsorLabel?y(`Sponsored Blips \xB7 ${e.sponsorLabel}`,i):"Sponsored Blips",l=[];l.push(a(f,k.dim)),e.title!==e.sponsorLabel&&l.push(a(y(e.title,i),k.bold));for(let g of he(e.body,i,2))l.push(g);let u="\u2192 ";if(s){let g=y(e.cta??e.url,i-u.length);l.push(u+a(ye(e.url,g),k.dim));}else e.cta&&l.push(y(e.cta,i)),l.push(u+a(y(e.url,i-u.length),k.dim));let T=`\u256D${"\u2500".repeat(i+2)}\u256E`,j=`\u2570${"\u2500".repeat(i+2)}\u256F`,L=l.map(g=>{let M=" ".repeat(Math.max(0,i-ge(g)));return `\u2502 ${g}${M} \u2502`}),b=[];return n.disclosure&&b.push(a(me,k.dim)),b.push(T,...L,j),b.join(`
3
3
  `)+`
4
4
  `}function Q(e){return e!==void 0&&e!==""}function U(e=process.env,n=!!process.stdout.isTTY){if(!n)return "none";let t=e.TERM??"";if(Q(e.TMUX)||t.startsWith("tmux")||t.startsWith("screen"))return "none";let o=e.TERM_PROGRAM??"";return o==="iTerm.app"||e.LC_TERMINAL==="iTerm2"||o==="WezTerm"?"iterm2":t==="xterm-kitty"||Q(e.KITTY_WINDOW_ID)?"kitty":"none"}var v="\x1B",be="\x07",we=2e3,ke=2*1024*1024,Se=new Set(["image/png","image/jpeg","image/gif","image/webp"]),O=4096;async function ve(e,n=fetch,t={}){let o=t.timeoutMs??we,i=t.maxBytes??ke;try{let r=await n(e,{signal:AbortSignal.timeout(o)});if(!r.ok)return c(`media: HTTP ${r.status} for ${e}`),null;let s=(r.headers.get("content-type")??"").split(";")[0].trim().toLowerCase();if(!Se.has(s))return c(`media: disallowed content-type "${s}" for ${e}`),null;let a=Number(r.headers.get("content-length")??"0");if(Number.isFinite(a)&&a>i)return c(`media: content-length ${a} exceeds ${i} for ${e}`),null;let f=r.body;if(f&&typeof f.getReader=="function"){let u=f.getReader(),T=[],j=0;for(;;){let{done:L,value:b}=await u.read();if(L)break;if(b!==void 0){if(j+=b.byteLength,j>i)return await u.cancel().catch(()=>{}),c(`media: stream exceeded ${i} bytes for ${e}`),null;T.push(b);}}return Buffer.concat(T)}let l=Buffer.from(await r.arrayBuffer());return l.byteLength>i?(c(`media: body ${l.byteLength} bytes exceeds ${i} for ${e}`),null):l}catch(r){return c(`media: fetch failed for ${e}:`,r),null}}function xe(e){let n=e.toString("base64");return `${v}]1337;File=inline=1;size=${e.byteLength};width=auto:${n}${be}`}function Ce(e){let n=e.toString("base64");if(n.length<=O)return `${v}_Gf=100,a=T;${n}${v}\\`;let t=[];for(let o=0;o<n.length;o+=O){let i=n.slice(o,o+O),s=`m=${o+O>=n.length?0:1}`,a=o===0?`f=100,a=T,${s}`:s;t.push(`${v}_G${a};${i}${v}\\`);}return t.join("")}function A(e){let n=E(e),t=e.creative;switch(t.format){case "image":case "gif":return {...n,body:t.textFallback??n.body};case "video":return {...n,body:t.textFallback??n.body,cta:n.cta??"\u25B6 Watch"};case "audio":return {...n,body:t.textFallback??n.body,cta:n.cta??"\u{1F50A} Listen"};default:return n}}async function z(e,n={}){try{let t=e.creative;if(t.format!=="image"&&t.format!=="gif")return h(A(e),n);let o=n.protocol??U();if(o==="none"||t.mediaUrl===void 0||t.mediaUrl==="")return h(A(e),n);let i={};n.timeoutMs!==void 0&&(i.timeoutMs=n.timeoutMs),n.maxBytes!==void 0&&(i.maxBytes=n.maxBytes);let r=await ve(t.mediaUrl,n.fetchImpl??fetch,i);return r===null||r.byteLength===0?h(A(e),n):(o==="kitty"?Ce(r):xe(r))+`
5
5
  `+h(E(e),n)}catch(t){return c("media: render failed, falling back to text:",t),h(E(e),n)}}function Te(e,n){return e.filter(t=>t.renderBy>n)}function ee(e,n,t=18e5){return e.filter(o=>o&&typeof o.impressionId=="string"&&typeof o.clickUrl=="string"&&o.creative&&typeof o.creative.title=="string").map(o=>({blip:o,renderBy:n+t}))}function ne(e,n){let t=Te(e.pool,n),o=t.shift();return {blip:o?o.blip:null,pool:t}}var te=360*60*1e3;function Ie(e=process.env){return S__namespace.join(ie__namespace.homedir(),".config","opencrater")}function oe(e=process.env){return S__namespace.join(Ie(e),"state.json")}function W(){return {installId:crypto.randomUUID(),lastShownAt:0,optOut:false,disclosureShown:false,cachedConfig:null,configFetchedAt:0,pool:[],allowedPlacements:{},sessionTopics:[],integrations:[],devToken:null,computeRouting:null,computeCards:null}}function d(e){return typeof e=="number"&&Number.isFinite(e)}var re=new Set(["EPERM","EACCES","EBUSY","EEXIST"]);function se(e){for(let n=0;;n++)try{return {text:m__namespace.readFileSync(e,"utf8")}}catch(t){let o=t.code??"";if(!(o==="ENOENT"||re.has(o)))return {locked:true};if(n>=4)return o==="ENOENT"?{missing:true}:{locked:true};try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(n+1));}catch{}}}function Pe(e){if(typeof e!="object"||e===null)return null;let n=e;return !d(n.minIntervalSeconds)||!d(n.serveTimeoutMs)||!d(n.preloadPoolSize)||typeof n.killSwitch!="boolean"?null:{minIntervalSeconds:n.minIntervalSeconds,serveTimeoutMs:n.serveTimeoutMs,preloadPoolSize:n.preloadPoolSize,killSwitch:n.killSwitch,displayDurationSeconds:d(n.displayDurationSeconds)?n.displayDurationSeconds:25,minSdkVersion:typeof n.minSdkVersion=="string"?n.minSdkVersion:""}}function Ee(e){if(!Array.isArray(e))return [];let n=[];for(let t of e){if(typeof t!="object"||t===null)continue;let o=t,i=o.blip;if(!d(o.renderBy)||typeof i!="object"||i===null||typeof i.impressionId!="string"||typeof i.clickUrl!="string"||typeof i.sponsorLabel!="string"||typeof i.creative!="object"||i.creative===null)continue;let r=i.creative;typeof r.title!="string"||typeof r.body!="string"||n.push({blip:{impressionId:i.impressionId,...typeof i.campaignId=="string"?{campaignId:i.campaignId}:{},clickUrl:i.clickUrl,sponsorLabel:i.sponsorLabel,creative:{format:"text",title:r.title,body:r.body,...typeof r.cta=="string"?{cta:r.cta}:{}}},renderBy:o.renderBy});}return n}function Oe(e){if(typeof e!="object"||e===null||Array.isArray(e))return {};let n={};for(let[t,o]of Object.entries(e)){if(!Array.isArray(o))continue;let i=o.filter(r=>typeof r=="string"&&r.length<=64);n[t]=i.slice(0,64);}return n}function Ae(e){if(!Array.isArray(e))return [];let n=[];for(let t of e){if(typeof t!="object"||t===null)continue;let o=t;if(!(typeof o.topic!="string"||!d(o.at))&&(n.push({topic:o.topic.slice(0,32),at:o.at}),n.length>=24))break}return n}function We(e){if(!Array.isArray(e))return [];let n=[],t=new Set;for(let o of e){if(typeof o!="object"||o===null)continue;let i=o;if(typeof i.key!="string"||typeof i.package!="string"||i.key===""||i.package==="")continue;let r=`${i.package}\0${i.key}`;if(!t.has(r)&&(t.add(r),n.push({key:i.key,package:i.package}),n.length>=32))break}return n}function Be(e){if(typeof e!="object"||e===null)return null;let n=e,t={};if(typeof n.savedEnv=="object"&&n.savedEnv!==null)for(let[o,i]of Object.entries(n.savedEnv))(typeof i=="string"||i===null)&&(t[o]=i);return {active:n.active===true,savedEnv:t}}function _e(e){if(typeof e!="object"||e===null)return null;let n=e,t=o=>d(o)&&o>=0?o:0;return {turns:t(n.turns),lastLimitAt:t(n.lastLimitAt),lastDepletedAt:t(n.lastDepletedAt),lastBackupAt:t(n.lastBackupAt)}}function Le(e){let n=e.attrTagsAt,t=e.attrTagsCwd;return !d(n)||Date.now()-n>te||typeof t!="string"||t.length===0||t.length>64?{}:{attrTags:Array.isArray(e.attrTags)?e.attrTags.filter(i=>typeof i=="string"&&i.length<=40).slice(0,48):[],attrTagsCwd:t,attrTagsAt:n}}function Me(e){let n=W();if(typeof e!="object"||e===null)return n;let t=e;return {installId:typeof t.installId=="string"&&t.installId.length>0?t.installId:n.installId,lastShownAt:d(t.lastShownAt)&&t.lastShownAt>=0?t.lastShownAt:0,optOut:t.optOut===true,disclosureShown:t.disclosureShown===true,cachedConfig:Pe(t.cachedConfig),allowedPlacements:Oe(t.allowedPlacements),sessionTopics:Ae(t.sessionTopics),integrations:We(t.integrations),devToken:typeof t.devToken=="string"?t.devToken:null,computeRouting:Be(t.computeRouting),computeCards:_e(t.computeCards),configFetchedAt:d(t.configFetchedAt)&&t.configFetchedAt>=0?t.configFetchedAt:0,pool:Ee(t.pool),...Le(t)}}function x(e=process.env){let n=oe(e),t=se(n);if(t.text!==void 0)try{return Me(JSON.parse(t.text))}catch{let o=W();try{p(o,e);}catch{}return o}if(t.missing){let o=W();try{p(o,e);}catch{}return o}return W()}function p(e,n=process.env,t={}){let o=oe(n),i=S__namespace.dirname(o);m__namespace.mkdirSync(i,{recursive:true});let r=se(o),s=null;if(r.text!==void 0)try{s=JSON.parse(r.text);}catch{s=null;}if(s)typeof s.lastShownAt=="number"&&s.lastShownAt>e.lastShownAt&&(e={...e,lastShownAt:s.lastShownAt}),!t.allowClearToken&&typeof s.devToken=="string"&&e.devToken==null&&(e={...e,devToken:s.devToken}),typeof s.installId=="string"&&s.installId.length>0&&s.installId!==e.installId&&(e={...e,installId:s.installId});else if(!t.allowClearToken&&e.devToken==null&&r.text===void 0&&!r.missing)return;let a=S__namespace.join(i,`.state.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`);m__namespace.writeFileSync(a,JSON.stringify(e,null,2)+`
6
- `,"utf8");for(let f=0;;f++)try{m__namespace.renameSync(a,o);return}catch(l){let u=l.code??"";if(f>=4||!re.has(u)){try{m__namespace.rmSync(a,{force:!0});}catch{}if(f>=4)return;throw l}try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(f+1));}catch{}}}var qe=["CI","CONTINUOUS_INTEGRATION","GITHUB_ACTIONS","GITLAB_CI","CIRCLECI","TRAVIS","BUILDKITE","JENKINS_URL","TEAMCITY_VERSION","TF_BUILD","APPVEYOR","CODEBUILD_BUILD_ID","DRONE","NETLIFY","VERCEL"];function Y(e){return e!==void 0&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}function Ne(e){return Y(e.OPENCRATER_DISABLE)||Y(e.TSN_DISABLE)}function De(e){return qe.some(n=>Y(e[n]))}function H(e){return e?{...w,...e}:w}function C(e,n={}){if(Ne(e.env))return "env_disabled";if(e.state.optOut)return "opt_out";let t=H(e.state.cachedConfig);if(t.killSwitch)return "kill_switch";if(De(e.env))return "ci";if(!n.skipTTY&&!e.isTTY)return "not_tty";if(!n.skipFrequency){let o=t.minIntervalSeconds*1e3;if(e.state.lastShownAt>0&&e.now-e.state.lastShownAt<o)return "frequency"}return null}async function B(e){try{return await e()}catch(n){return c("suppressed error:",n),null}}function _(e,n){let t=H(n.cachedConfig);return {origin:K(e.apiOrigin),timeoutMs:t.serveTimeoutMs,installId:n.installId,config:t}}function Fe(e,n){let t=!n.disclosureShown,o=h(e,{width:process.stdout.columns??80,color:P(),hyperlinks:I(),disclosure:t});return process.stdout.write(o),{...n,lastShownAt:Date.now(),disclosureShown:true}}async function ae(e,n){let t=await z(e,{width:process.stdout.columns??80,color:P(),hyperlinks:I(),disclosure:!n.disclosureShown});return process.stdout.write(t),{...n,lastShownAt:Date.now(),disclosureShown:true}}async function $e(e){let n=x(),t=C({env:process.env,isTTY:!!process.stdout.isTTY,state:n,now:Date.now()},{skipFrequency:true});if(t!==null)return c("fetch suppressed:",t),null;let o=_(e,n),i=await F(e,o);return i?(p({...n,cachedConfig:i.config,configFetchedAt:Date.now()}),i.fill&&i.blip?i.blip:null):null}async function Ue(e){let n=x(),t=C({env:process.env,isTTY:!!process.stdout.isTTY,state:n,now:Date.now()});if(t!==null)return c("suppressed:",t),false;let o=_(e,n),i=await F(e,o);return i?(n={...n,cachedConfig:i.config,configFetchedAt:Date.now()},i.fill&&i.blip?(n=await ae(i.blip,n),p(n),$(i.blip.impressionId,o),true):i.fallback?(n=Fe(Z(i.fallback),n),p(n),true):(p(n),false)):false}async function ze(e){let n=x(),t=C({env:process.env,isTTY:!!process.stdout.isTTY,state:n,now:Date.now()},{skipTTY:true,skipFrequency:true});if(t!==null)return c("preload suppressed:",t),0;let o=_(e,n),i=Math.max(1,o.config.preloadPoolSize),r=await X(e,i,o);if(!r)return 0;let s=Date.now(),a=ee(r.blips,s);return p({...n,pool:a,cachedConfig:r.config,configFetchedAt:s}),a.length}async function Ge(e){let n=x(),t=Date.now(),o=C({env:process.env,isTTY:!!process.stdout.isTTY,state:n,now:t});if(o!==null)return c("renderFromPool suppressed:",o),false;let{blip:i,pool:r}=ne(n,t);if(!i)return p({...n,pool:r}),false;let s=await ae(i,{...n,pool:r});p(s);let a=_(e,n);return $(i.impressionId,a),true}var kn={show(e){return B(()=>Ue(e)).then(n=>n??false)},fetch(e){return B(()=>$e(e))},preload(e){return B(()=>ze(e)).then(n=>n??0)},renderFromPool(e){return B(()=>Ge(e)).then(n=>n??false)}};exports.DEFAULT_CONFIG=w;exports.HOOK_CATALOG=le;exports.SDK_VERSION=N;exports.detectImageProtocol=U;exports.renderBlip=z;exports.renderCard=h;exports.sponsor=kn;exports.textCardForBlip=A;
6
+ `,"utf8");for(let f=0;;f++)try{m__namespace.renameSync(a,o);return}catch(l){let u=l.code??"";if(f>=4||!re.has(u)){try{m__namespace.rmSync(a,{force:!0});}catch{}if(f>=4)return;throw l}try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(f+1));}catch{}}}var qe=["CI","CONTINUOUS_INTEGRATION","GITHUB_ACTIONS","GITLAB_CI","CIRCLECI","TRAVIS","BUILDKITE","JENKINS_URL","TEAMCITY_VERSION","TF_BUILD","APPVEYOR","CODEBUILD_BUILD_ID","DRONE","NETLIFY","VERCEL"];function Y(e){return e!==void 0&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}function Ne(e){return Y(e.OPENCRATER_DISABLE)||Y(e.TSN_DISABLE)}function De(e){return qe.some(n=>Y(e[n]))}function H(e){return e?{...w,...e}:w}function C(e,n={}){if(Ne(e.env))return "env_disabled";if(e.state.optOut)return "opt_out";let t=H(e.state.cachedConfig);if(t.killSwitch)return "kill_switch";if(De(e.env))return "ci";if(!n.skipTTY&&!e.isTTY)return "not_tty";if(!n.skipFrequency){let o=t.minIntervalSeconds*1e3;if(e.state.lastShownAt>0&&e.now-e.state.lastShownAt<o)return "frequency"}return null}async function B(e){try{return await e()}catch(n){return c("suppressed error:",n),null}}function _(e,n){let t=H(n.cachedConfig);return {origin:K(e.apiOrigin),timeoutMs:t.serveTimeoutMs,installId:n.installId,config:t}}function Fe(e,n){let t=!n.disclosureShown,o=h(e,{width:process.stdout.columns??80,color:P(),hyperlinks:I(),disclosure:t});return process.stdout.write(o),{...n,lastShownAt:Date.now(),disclosureShown:true}}async function ae(e,n){let t=await z(e,{width:process.stdout.columns??80,color:P(),hyperlinks:I(),disclosure:!n.disclosureShown});return process.stdout.write(t),{...n,lastShownAt:Date.now(),disclosureShown:true}}async function $e(e){let n=x(),t=C({env:process.env,isTTY:!!process.stdout.isTTY,state:n,now:Date.now()},{skipFrequency:true});if(t!==null)return c("fetch suppressed:",t),null;let o=_(e,n),i=await F(e,o);return i?(p({...n,cachedConfig:i.config,configFetchedAt:Date.now()}),i.fill&&i.blip?i.blip:null):null}async function Ue(e){let n=x(),t=C({env:process.env,isTTY:!!process.stdout.isTTY,state:n,now:Date.now()});if(t!==null)return c("suppressed:",t),false;let o=_(e,n),i=await F(e,o);return i?(n={...n,cachedConfig:i.config,configFetchedAt:Date.now()},i.fill&&i.blip?(n=await ae(i.blip,n),p(n),$(i.blip.impressionId,o,i.blip.renderToken),true):i.fallback?(n=Fe(Z(i.fallback),n),p(n),true):(p(n),false)):false}async function ze(e){let n=x(),t=C({env:process.env,isTTY:!!process.stdout.isTTY,state:n,now:Date.now()},{skipTTY:true,skipFrequency:true});if(t!==null)return c("preload suppressed:",t),0;let o=_(e,n),i=Math.max(1,o.config.preloadPoolSize),r=await X(e,i,o);if(!r)return 0;let s=Date.now(),a=ee(r.blips,s);return p({...n,pool:a,cachedConfig:r.config,configFetchedAt:s}),a.length}async function Ge(e){let n=x(),t=Date.now(),o=C({env:process.env,isTTY:!!process.stdout.isTTY,state:n,now:t});if(o!==null)return c("renderFromPool suppressed:",o),false;let{blip:i,pool:r}=ne(n,t);if(!i)return p({...n,pool:r}),false;let s=await ae(i,{...n,pool:r});p(s);let a=_(e,n);return $(i.impressionId,a,i.renderToken),true}var kn={show(e){return B(()=>Ue(e)).then(n=>n??false)},fetch(e){return B(()=>$e(e))},preload(e){return B(()=>ze(e)).then(n=>n??0)},renderFromPool(e){return B(()=>Ge(e)).then(n=>n??false)}};exports.DEFAULT_CONFIG=w;exports.HOOK_CATALOG=le;exports.SDK_VERSION=N;exports.detectImageProtocol=U;exports.renderBlip=z;exports.renderCard=h;exports.sponsor=kn;exports.textCardForBlip=A;
package/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import {randomUUID}from'crypto';import*as m from'fs';import*as ie from'os';import*as S from'path';var q=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(n,t)=>(typeof require<"u"?require:n)[t]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var w={minIntervalSeconds:600,serveTimeoutMs:2500,preloadPoolSize:3,killSwitch:false,displayDurationSeconds:25,minSdkVersion:""};var le=["SessionStart","SessionEnd","Stop","PostToolUse","Notification"];var N="1.4.5";var ce="https://api.opencrater.to";function K(e,n=process.env){let t=n.OPENCRATER_API_ORIGIN;return (e??(t&&t.trim()!==""?t:ce)).replace(/\/+$/,"")}function c(...e){try{if(process.env.OPENCRATER_DEBUG!=="1")return;console.error("[opencrater]",...e);try{let n=q("os"),t=q("fs"),o=q("path");t.appendFileSync(o.join(n.homedir(),".config","opencrater","hook.log"),`${new Date().toISOString()} [opencrater] ${e.map(i=>String(i)).join(" ")}
2
- `);}catch{}}catch{}}function R(e){return typeof e=="number"&&Number.isFinite(e)}function V(e){let n=w;if(typeof e!="object"||e===null)return {...n};let t=e;return {minIntervalSeconds:R(t.minIntervalSeconds)?t.minIntervalSeconds:n.minIntervalSeconds,serveTimeoutMs:R(t.serveTimeoutMs)?t.serveTimeoutMs:n.serveTimeoutMs,preloadPoolSize:R(t.preloadPoolSize)?t.preloadPoolSize:n.preloadPoolSize,killSwitch:t.killSwitch===true,displayDurationSeconds:R(t.displayDurationSeconds)?t.displayDurationSeconds:n.displayDurationSeconds,minSdkVersion:typeof t.minSdkVersion=="string"?t.minSdkVersion:n.minSdkVersion}}async function D(e,n,t,o,i){try{let r=await fetch(`${e}${n}`,{method:"POST",headers:{"content-type":"application/json",...i??{}},body:JSON.stringify(t),signal:AbortSignal.timeout(o)});return r.ok?await r.json():(c(`POST ${n} -> HTTP ${r.status}`),null)}catch(r){return c(`POST ${n} failed:`,r),null}}function J(e,n){let t=e.host??"generic";return {publisherKey:e.publisherKey,packageName:e.packageName,placement:e.placement,host:t,sdkVersion:N,installId:n.installId,os:process.platform,termProgram:process.env.TERM_PROGRAM??void 0,topics:n.topics&&n.topics.length>0?n.topics:void 0,tags:n.tags&&n.tags.length>0?n.tags:void 0}}function fe(e){if(typeof e!="object"||e===null)return null;let n=e;if(typeof n.fill!="boolean")return null;let t={fill:n.fill,fallback:n.fallback??null,config:V(n.config),...Array.isArray(n.allowedPlacements)?{allowedPlacements:n.allowedPlacements.filter(o=>typeof o=="string")}:{}};return n.blip!==void 0&&n.blip!==null&&(t.blip=n.blip),typeof n.computeBalanceMicroUsd=="number"&&(t.computeBalanceMicroUsd=n.computeBalanceMicroUsd),typeof n.weeklyGrantMicroUsd=="number"&&(t.weeklyGrantMicroUsd=n.weeklyGrantMicroUsd),typeof n.pendingMicroUsd=="number"&&(t.pendingMicroUsd=n.pendingMicroUsd),t}async function F(e,n){let t=await D(n.origin,"/v1/serve",J(e,n),n.timeoutMs);return fe(t)}async function X(e,n,t){let o=await D(t.origin,"/v1/serve/batch",{...J(e,t),count:n},t.timeoutMs);if(typeof o!="object"||o===null)return null;let i=o;return Array.isArray(i.blips)?{blips:i.blips,fallback:i.fallback??null,config:V(i.config),...Array.isArray(i.allowedPlacements)?{allowedPlacements:i.allowedPlacements.filter(r=>typeof r=="string")}:{}}:null}function $(e,n){return D(n.origin,"/v1/events/impression",{impressionId:e},n.timeoutMs).then(()=>{}).catch(()=>{})}var ue=new RegExp("\x1B\\[[0-9;]*m|\x1B\\]8;;[^\x07\x1B]*(?:\x07|\x1B\\\\)","g"),k={dim:"\x1B[2m",bold:"\x1B[1m",reset:"\x1B[0m"},de=60,pe=24,me="\u2139 This project is supported by Blips via OpenCrater. Opt out: `npx opencrater off` or OPENCRATER_DISABLE=1";function ge(e){return e.replace(ue,"").length}function y(e,n){return n<=0?"":e.length<=n?e:n===1?"\u2026":e.slice(0,n-1).trimEnd()+"\u2026"}function he(e,n,t){let o=e.split(/\s+/).filter(l=>l.length>0),i=[],r="";for(let l of o){let u=r===""?l:`${r} ${l}`;if(u.length<=n)r=u;else if(r!==""&&i.push(r),r=l.length>n?y(l,n):l,i.length>=t)break}r!==""&&i.length<t&&i.push(r),i.length>t&&(i.length=t);let s=i.join(" "),a=i.length-1,f=i[a];return f!==void 0&&s.length<o.join(" ").length&&(i[a]=y(`${f}\u2026`,n)),i}function I(e=process.env,n=!!process.stdout.isTTY){if(!n)return false;if(e.FORCE_HYPERLINK!==void 0&&e.FORCE_HYPERLINK!=="0")return true;let t=e.TERM_PROGRAM??"";return !!(["iTerm.app","WezTerm","ghostty","Hyper","vscode","Tabby"].includes(t)||e.KITTY_WINDOW_ID||e.WT_SESSION||Number(e.VTE_VERSION??"0")>=5e3)}function P(e=process.env,n=!!process.stdout.isTTY){return !(e.NO_COLOR!==void 0&&e.NO_COLOR!==""||!n||(e.TERM??"")==="dumb")}function ye(e,n){return `\x1B]8;;${e}\x07${n}\x1B]8;;\x07`}function E(e){let n={sponsorLabel:e.sponsorLabel,title:e.creative.title,body:e.creative.body,url:e.clickUrl};return e.creative.cta!==void 0&&(n.cta=e.creative.cta),n}function Z(e){return {sponsorLabel:"",title:e.title,body:e.body,url:e.url}}function h(e,n={}){let t=n.width??process.stdout.columns??80,i=Math.max(pe,Math.min(t,de))-4,r=n.color??P(),s=n.hyperlinks??I(),a=(g,M)=>r?`${M}${g}${k.reset}`:g,f=e.label?y(e.label,i):e.sponsorLabel?y(`Sponsored Blips \xB7 ${e.sponsorLabel}`,i):"Sponsored Blips",l=[];l.push(a(f,k.dim)),e.title!==e.sponsorLabel&&l.push(a(y(e.title,i),k.bold));for(let g of he(e.body,i,2))l.push(g);let u="\u2192 ";if(s){let g=y(e.cta??e.url,i-u.length);l.push(u+a(ye(e.url,g),k.dim));}else e.cta&&l.push(y(e.cta,i)),l.push(u+a(y(e.url,i-u.length),k.dim));let T=`\u256D${"\u2500".repeat(i+2)}\u256E`,j=`\u2570${"\u2500".repeat(i+2)}\u256F`,L=l.map(g=>{let M=" ".repeat(Math.max(0,i-ge(g)));return `\u2502 ${g}${M} \u2502`}),b=[];return n.disclosure&&b.push(a(me,k.dim)),b.push(T,...L,j),b.join(`
1
+ import {randomUUID}from'crypto';import*as m from'fs';import*as ie from'os';import*as S from'path';var q=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(n,t)=>(typeof require<"u"?require:n)[t]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var w={minIntervalSeconds:600,serveTimeoutMs:2500,preloadPoolSize:3,killSwitch:false,displayDurationSeconds:25,minSdkVersion:""};var le=["SessionStart","SessionEnd","Stop","PostToolUse","Notification"];var N="1.4.7";var ce="https://api.opencrater.to";function K(e,n=process.env){let t=n.OPENCRATER_API_ORIGIN;return (e??(t&&t.trim()!==""?t:ce)).replace(/\/+$/,"")}function c(...e){try{if(process.env.OPENCRATER_DEBUG!=="1")return;console.error("[opencrater]",...e);try{let n=q("os"),t=q("fs"),o=q("path");t.appendFileSync(o.join(n.homedir(),".config","opencrater","hook.log"),`${new Date().toISOString()} [opencrater] ${e.map(i=>String(i)).join(" ")}
2
+ `);}catch{}}catch{}}function R(e){return typeof e=="number"&&Number.isFinite(e)}function V(e){let n=w;if(typeof e!="object"||e===null)return {...n};let t=e;return {minIntervalSeconds:R(t.minIntervalSeconds)?t.minIntervalSeconds:n.minIntervalSeconds,serveTimeoutMs:R(t.serveTimeoutMs)?t.serveTimeoutMs:n.serveTimeoutMs,preloadPoolSize:R(t.preloadPoolSize)?t.preloadPoolSize:n.preloadPoolSize,killSwitch:t.killSwitch===true,displayDurationSeconds:R(t.displayDurationSeconds)?t.displayDurationSeconds:n.displayDurationSeconds,minSdkVersion:typeof t.minSdkVersion=="string"?t.minSdkVersion:n.minSdkVersion}}async function D(e,n,t,o,i){try{let r=await fetch(`${e}${n}`,{method:"POST",headers:{"content-type":"application/json",...i??{}},body:JSON.stringify(t),signal:AbortSignal.timeout(o)});return r.ok?await r.json():(c(`POST ${n} -> HTTP ${r.status}`),null)}catch(r){return c(`POST ${n} failed:`,r),null}}function J(e,n){let t=e.host??"generic";return {publisherKey:e.publisherKey,packageName:e.packageName,placement:e.placement,host:t,sdkVersion:N,installId:n.installId,os:process.platform,termProgram:process.env.TERM_PROGRAM??void 0,topics:n.topics&&n.topics.length>0?n.topics:void 0,tags:n.tags&&n.tags.length>0?n.tags:void 0}}function fe(e){if(typeof e!="object"||e===null)return null;let n=e;if(typeof n.fill!="boolean")return null;let t={fill:n.fill,fallback:n.fallback??null,config:V(n.config),...Array.isArray(n.allowedPlacements)?{allowedPlacements:n.allowedPlacements.filter(o=>typeof o=="string")}:{}};return n.blip!==void 0&&n.blip!==null&&(t.blip=n.blip),typeof n.computeBalanceMicroUsd=="number"&&(t.computeBalanceMicroUsd=n.computeBalanceMicroUsd),typeof n.weeklyGrantMicroUsd=="number"&&(t.weeklyGrantMicroUsd=n.weeklyGrantMicroUsd),typeof n.pendingMicroUsd=="number"&&(t.pendingMicroUsd=n.pendingMicroUsd),t}async function F(e,n){let t=await D(n.origin,"/v1/serve",J(e,n),n.timeoutMs);return fe(t)}async function X(e,n,t){let o=await D(t.origin,"/v1/serve/batch",{...J(e,t),count:n},t.timeoutMs);if(typeof o!="object"||o===null)return null;let i=o;return Array.isArray(i.blips)?{blips:i.blips,fallback:i.fallback??null,config:V(i.config),...Array.isArray(i.allowedPlacements)?{allowedPlacements:i.allowedPlacements.filter(r=>typeof r=="string")}:{}}:null}function $(e,n,t){return D(n.origin,"/v1/events/impression",{impressionId:e,...t?{renderToken:t}:{}},n.timeoutMs).then(()=>{}).catch(()=>{})}var ue=new RegExp("\x1B\\[[0-9;]*m|\x1B\\]8;;[^\x07\x1B]*(?:\x07|\x1B\\\\)","g"),k={dim:"\x1B[2m",bold:"\x1B[1m",reset:"\x1B[0m"},de=60,pe=24,me="\u2139 This project is supported by Blips via OpenCrater. Opt out: `npx opencrater off` or OPENCRATER_DISABLE=1";function ge(e){return e.replace(ue,"").length}function y(e,n){return n<=0?"":e.length<=n?e:n===1?"\u2026":e.slice(0,n-1).trimEnd()+"\u2026"}function he(e,n,t){let o=e.split(/\s+/).filter(l=>l.length>0),i=[],r="";for(let l of o){let u=r===""?l:`${r} ${l}`;if(u.length<=n)r=u;else if(r!==""&&i.push(r),r=l.length>n?y(l,n):l,i.length>=t)break}r!==""&&i.length<t&&i.push(r),i.length>t&&(i.length=t);let s=i.join(" "),a=i.length-1,f=i[a];return f!==void 0&&s.length<o.join(" ").length&&(i[a]=y(`${f}\u2026`,n)),i}function I(e=process.env,n=!!process.stdout.isTTY){if(!n)return false;if(e.FORCE_HYPERLINK!==void 0&&e.FORCE_HYPERLINK!=="0")return true;let t=e.TERM_PROGRAM??"";return !!(["iTerm.app","WezTerm","ghostty","Hyper","vscode","Tabby"].includes(t)||e.KITTY_WINDOW_ID||e.WT_SESSION||Number(e.VTE_VERSION??"0")>=5e3)}function P(e=process.env,n=!!process.stdout.isTTY){return !(e.NO_COLOR!==void 0&&e.NO_COLOR!==""||!n||(e.TERM??"")==="dumb")}function ye(e,n){return `\x1B]8;;${e}\x07${n}\x1B]8;;\x07`}function E(e){let n={sponsorLabel:e.sponsorLabel,title:e.creative.title,body:e.creative.body,url:e.clickUrl};return e.creative.cta!==void 0&&(n.cta=e.creative.cta),n}function Z(e){return {sponsorLabel:"",title:e.title,body:e.body,url:e.url}}function h(e,n={}){let t=n.width??process.stdout.columns??80,i=Math.max(pe,Math.min(t,de))-4,r=n.color??P(),s=n.hyperlinks??I(),a=(g,M)=>r?`${M}${g}${k.reset}`:g,f=e.label?y(e.label,i):e.sponsorLabel?y(`Sponsored Blips \xB7 ${e.sponsorLabel}`,i):"Sponsored Blips",l=[];l.push(a(f,k.dim)),e.title!==e.sponsorLabel&&l.push(a(y(e.title,i),k.bold));for(let g of he(e.body,i,2))l.push(g);let u="\u2192 ";if(s){let g=y(e.cta??e.url,i-u.length);l.push(u+a(ye(e.url,g),k.dim));}else e.cta&&l.push(y(e.cta,i)),l.push(u+a(y(e.url,i-u.length),k.dim));let T=`\u256D${"\u2500".repeat(i+2)}\u256E`,j=`\u2570${"\u2500".repeat(i+2)}\u256F`,L=l.map(g=>{let M=" ".repeat(Math.max(0,i-ge(g)));return `\u2502 ${g}${M} \u2502`}),b=[];return n.disclosure&&b.push(a(me,k.dim)),b.push(T,...L,j),b.join(`
3
3
  `)+`
4
4
  `}function Q(e){return e!==void 0&&e!==""}function U(e=process.env,n=!!process.stdout.isTTY){if(!n)return "none";let t=e.TERM??"";if(Q(e.TMUX)||t.startsWith("tmux")||t.startsWith("screen"))return "none";let o=e.TERM_PROGRAM??"";return o==="iTerm.app"||e.LC_TERMINAL==="iTerm2"||o==="WezTerm"?"iterm2":t==="xterm-kitty"||Q(e.KITTY_WINDOW_ID)?"kitty":"none"}var v="\x1B",be="\x07",we=2e3,ke=2*1024*1024,Se=new Set(["image/png","image/jpeg","image/gif","image/webp"]),O=4096;async function ve(e,n=fetch,t={}){let o=t.timeoutMs??we,i=t.maxBytes??ke;try{let r=await n(e,{signal:AbortSignal.timeout(o)});if(!r.ok)return c(`media: HTTP ${r.status} for ${e}`),null;let s=(r.headers.get("content-type")??"").split(";")[0].trim().toLowerCase();if(!Se.has(s))return c(`media: disallowed content-type "${s}" for ${e}`),null;let a=Number(r.headers.get("content-length")??"0");if(Number.isFinite(a)&&a>i)return c(`media: content-length ${a} exceeds ${i} for ${e}`),null;let f=r.body;if(f&&typeof f.getReader=="function"){let u=f.getReader(),T=[],j=0;for(;;){let{done:L,value:b}=await u.read();if(L)break;if(b!==void 0){if(j+=b.byteLength,j>i)return await u.cancel().catch(()=>{}),c(`media: stream exceeded ${i} bytes for ${e}`),null;T.push(b);}}return Buffer.concat(T)}let l=Buffer.from(await r.arrayBuffer());return l.byteLength>i?(c(`media: body ${l.byteLength} bytes exceeds ${i} for ${e}`),null):l}catch(r){return c(`media: fetch failed for ${e}:`,r),null}}function xe(e){let n=e.toString("base64");return `${v}]1337;File=inline=1;size=${e.byteLength};width=auto:${n}${be}`}function Ce(e){let n=e.toString("base64");if(n.length<=O)return `${v}_Gf=100,a=T;${n}${v}\\`;let t=[];for(let o=0;o<n.length;o+=O){let i=n.slice(o,o+O),s=`m=${o+O>=n.length?0:1}`,a=o===0?`f=100,a=T,${s}`:s;t.push(`${v}_G${a};${i}${v}\\`);}return t.join("")}function A(e){let n=E(e),t=e.creative;switch(t.format){case "image":case "gif":return {...n,body:t.textFallback??n.body};case "video":return {...n,body:t.textFallback??n.body,cta:n.cta??"\u25B6 Watch"};case "audio":return {...n,body:t.textFallback??n.body,cta:n.cta??"\u{1F50A} Listen"};default:return n}}async function z(e,n={}){try{let t=e.creative;if(t.format!=="image"&&t.format!=="gif")return h(A(e),n);let o=n.protocol??U();if(o==="none"||t.mediaUrl===void 0||t.mediaUrl==="")return h(A(e),n);let i={};n.timeoutMs!==void 0&&(i.timeoutMs=n.timeoutMs),n.maxBytes!==void 0&&(i.maxBytes=n.maxBytes);let r=await ve(t.mediaUrl,n.fetchImpl??fetch,i);return r===null||r.byteLength===0?h(A(e),n):(o==="kitty"?Ce(r):xe(r))+`
5
5
  `+h(E(e),n)}catch(t){return c("media: render failed, falling back to text:",t),h(E(e),n)}}function Te(e,n){return e.filter(t=>t.renderBy>n)}function ee(e,n,t=18e5){return e.filter(o=>o&&typeof o.impressionId=="string"&&typeof o.clickUrl=="string"&&o.creative&&typeof o.creative.title=="string").map(o=>({blip:o,renderBy:n+t}))}function ne(e,n){let t=Te(e.pool,n),o=t.shift();return {blip:o?o.blip:null,pool:t}}var te=360*60*1e3;function Ie(e=process.env){return S.join(ie.homedir(),".config","opencrater")}function oe(e=process.env){return S.join(Ie(e),"state.json")}function W(){return {installId:randomUUID(),lastShownAt:0,optOut:false,disclosureShown:false,cachedConfig:null,configFetchedAt:0,pool:[],allowedPlacements:{},sessionTopics:[],integrations:[],devToken:null,computeRouting:null,computeCards:null}}function d(e){return typeof e=="number"&&Number.isFinite(e)}var re=new Set(["EPERM","EACCES","EBUSY","EEXIST"]);function se(e){for(let n=0;;n++)try{return {text:m.readFileSync(e,"utf8")}}catch(t){let o=t.code??"";if(!(o==="ENOENT"||re.has(o)))return {locked:true};if(n>=4)return o==="ENOENT"?{missing:true}:{locked:true};try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(n+1));}catch{}}}function Pe(e){if(typeof e!="object"||e===null)return null;let n=e;return !d(n.minIntervalSeconds)||!d(n.serveTimeoutMs)||!d(n.preloadPoolSize)||typeof n.killSwitch!="boolean"?null:{minIntervalSeconds:n.minIntervalSeconds,serveTimeoutMs:n.serveTimeoutMs,preloadPoolSize:n.preloadPoolSize,killSwitch:n.killSwitch,displayDurationSeconds:d(n.displayDurationSeconds)?n.displayDurationSeconds:25,minSdkVersion:typeof n.minSdkVersion=="string"?n.minSdkVersion:""}}function Ee(e){if(!Array.isArray(e))return [];let n=[];for(let t of e){if(typeof t!="object"||t===null)continue;let o=t,i=o.blip;if(!d(o.renderBy)||typeof i!="object"||i===null||typeof i.impressionId!="string"||typeof i.clickUrl!="string"||typeof i.sponsorLabel!="string"||typeof i.creative!="object"||i.creative===null)continue;let r=i.creative;typeof r.title!="string"||typeof r.body!="string"||n.push({blip:{impressionId:i.impressionId,...typeof i.campaignId=="string"?{campaignId:i.campaignId}:{},clickUrl:i.clickUrl,sponsorLabel:i.sponsorLabel,creative:{format:"text",title:r.title,body:r.body,...typeof r.cta=="string"?{cta:r.cta}:{}}},renderBy:o.renderBy});}return n}function Oe(e){if(typeof e!="object"||e===null||Array.isArray(e))return {};let n={};for(let[t,o]of Object.entries(e)){if(!Array.isArray(o))continue;let i=o.filter(r=>typeof r=="string"&&r.length<=64);n[t]=i.slice(0,64);}return n}function Ae(e){if(!Array.isArray(e))return [];let n=[];for(let t of e){if(typeof t!="object"||t===null)continue;let o=t;if(!(typeof o.topic!="string"||!d(o.at))&&(n.push({topic:o.topic.slice(0,32),at:o.at}),n.length>=24))break}return n}function We(e){if(!Array.isArray(e))return [];let n=[],t=new Set;for(let o of e){if(typeof o!="object"||o===null)continue;let i=o;if(typeof i.key!="string"||typeof i.package!="string"||i.key===""||i.package==="")continue;let r=`${i.package}\0${i.key}`;if(!t.has(r)&&(t.add(r),n.push({key:i.key,package:i.package}),n.length>=32))break}return n}function Be(e){if(typeof e!="object"||e===null)return null;let n=e,t={};if(typeof n.savedEnv=="object"&&n.savedEnv!==null)for(let[o,i]of Object.entries(n.savedEnv))(typeof i=="string"||i===null)&&(t[o]=i);return {active:n.active===true,savedEnv:t}}function _e(e){if(typeof e!="object"||e===null)return null;let n=e,t=o=>d(o)&&o>=0?o:0;return {turns:t(n.turns),lastLimitAt:t(n.lastLimitAt),lastDepletedAt:t(n.lastDepletedAt),lastBackupAt:t(n.lastBackupAt)}}function Le(e){let n=e.attrTagsAt,t=e.attrTagsCwd;return !d(n)||Date.now()-n>te||typeof t!="string"||t.length===0||t.length>64?{}:{attrTags:Array.isArray(e.attrTags)?e.attrTags.filter(i=>typeof i=="string"&&i.length<=40).slice(0,48):[],attrTagsCwd:t,attrTagsAt:n}}function Me(e){let n=W();if(typeof e!="object"||e===null)return n;let t=e;return {installId:typeof t.installId=="string"&&t.installId.length>0?t.installId:n.installId,lastShownAt:d(t.lastShownAt)&&t.lastShownAt>=0?t.lastShownAt:0,optOut:t.optOut===true,disclosureShown:t.disclosureShown===true,cachedConfig:Pe(t.cachedConfig),allowedPlacements:Oe(t.allowedPlacements),sessionTopics:Ae(t.sessionTopics),integrations:We(t.integrations),devToken:typeof t.devToken=="string"?t.devToken:null,computeRouting:Be(t.computeRouting),computeCards:_e(t.computeCards),configFetchedAt:d(t.configFetchedAt)&&t.configFetchedAt>=0?t.configFetchedAt:0,pool:Ee(t.pool),...Le(t)}}function x(e=process.env){let n=oe(e),t=se(n);if(t.text!==void 0)try{return Me(JSON.parse(t.text))}catch{let o=W();try{p(o,e);}catch{}return o}if(t.missing){let o=W();try{p(o,e);}catch{}return o}return W()}function p(e,n=process.env,t={}){let o=oe(n),i=S.dirname(o);m.mkdirSync(i,{recursive:true});let r=se(o),s=null;if(r.text!==void 0)try{s=JSON.parse(r.text);}catch{s=null;}if(s)typeof s.lastShownAt=="number"&&s.lastShownAt>e.lastShownAt&&(e={...e,lastShownAt:s.lastShownAt}),!t.allowClearToken&&typeof s.devToken=="string"&&e.devToken==null&&(e={...e,devToken:s.devToken}),typeof s.installId=="string"&&s.installId.length>0&&s.installId!==e.installId&&(e={...e,installId:s.installId});else if(!t.allowClearToken&&e.devToken==null&&r.text===void 0&&!r.missing)return;let a=S.join(i,`.state.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`);m.writeFileSync(a,JSON.stringify(e,null,2)+`
6
- `,"utf8");for(let f=0;;f++)try{m.renameSync(a,o);return}catch(l){let u=l.code??"";if(f>=4||!re.has(u)){try{m.rmSync(a,{force:!0});}catch{}if(f>=4)return;throw l}try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(f+1));}catch{}}}var qe=["CI","CONTINUOUS_INTEGRATION","GITHUB_ACTIONS","GITLAB_CI","CIRCLECI","TRAVIS","BUILDKITE","JENKINS_URL","TEAMCITY_VERSION","TF_BUILD","APPVEYOR","CODEBUILD_BUILD_ID","DRONE","NETLIFY","VERCEL"];function Y(e){return e!==void 0&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}function Ne(e){return Y(e.OPENCRATER_DISABLE)||Y(e.TSN_DISABLE)}function De(e){return qe.some(n=>Y(e[n]))}function H(e){return e?{...w,...e}:w}function C(e,n={}){if(Ne(e.env))return "env_disabled";if(e.state.optOut)return "opt_out";let t=H(e.state.cachedConfig);if(t.killSwitch)return "kill_switch";if(De(e.env))return "ci";if(!n.skipTTY&&!e.isTTY)return "not_tty";if(!n.skipFrequency){let o=t.minIntervalSeconds*1e3;if(e.state.lastShownAt>0&&e.now-e.state.lastShownAt<o)return "frequency"}return null}async function B(e){try{return await e()}catch(n){return c("suppressed error:",n),null}}function _(e,n){let t=H(n.cachedConfig);return {origin:K(e.apiOrigin),timeoutMs:t.serveTimeoutMs,installId:n.installId,config:t}}function Fe(e,n){let t=!n.disclosureShown,o=h(e,{width:process.stdout.columns??80,color:P(),hyperlinks:I(),disclosure:t});return process.stdout.write(o),{...n,lastShownAt:Date.now(),disclosureShown:true}}async function ae(e,n){let t=await z(e,{width:process.stdout.columns??80,color:P(),hyperlinks:I(),disclosure:!n.disclosureShown});return process.stdout.write(t),{...n,lastShownAt:Date.now(),disclosureShown:true}}async function $e(e){let n=x(),t=C({env:process.env,isTTY:!!process.stdout.isTTY,state:n,now:Date.now()},{skipFrequency:true});if(t!==null)return c("fetch suppressed:",t),null;let o=_(e,n),i=await F(e,o);return i?(p({...n,cachedConfig:i.config,configFetchedAt:Date.now()}),i.fill&&i.blip?i.blip:null):null}async function Ue(e){let n=x(),t=C({env:process.env,isTTY:!!process.stdout.isTTY,state:n,now:Date.now()});if(t!==null)return c("suppressed:",t),false;let o=_(e,n),i=await F(e,o);return i?(n={...n,cachedConfig:i.config,configFetchedAt:Date.now()},i.fill&&i.blip?(n=await ae(i.blip,n),p(n),$(i.blip.impressionId,o),true):i.fallback?(n=Fe(Z(i.fallback),n),p(n),true):(p(n),false)):false}async function ze(e){let n=x(),t=C({env:process.env,isTTY:!!process.stdout.isTTY,state:n,now:Date.now()},{skipTTY:true,skipFrequency:true});if(t!==null)return c("preload suppressed:",t),0;let o=_(e,n),i=Math.max(1,o.config.preloadPoolSize),r=await X(e,i,o);if(!r)return 0;let s=Date.now(),a=ee(r.blips,s);return p({...n,pool:a,cachedConfig:r.config,configFetchedAt:s}),a.length}async function Ge(e){let n=x(),t=Date.now(),o=C({env:process.env,isTTY:!!process.stdout.isTTY,state:n,now:t});if(o!==null)return c("renderFromPool suppressed:",o),false;let{blip:i,pool:r}=ne(n,t);if(!i)return p({...n,pool:r}),false;let s=await ae(i,{...n,pool:r});p(s);let a=_(e,n);return $(i.impressionId,a),true}var kn={show(e){return B(()=>Ue(e)).then(n=>n??false)},fetch(e){return B(()=>$e(e))},preload(e){return B(()=>ze(e)).then(n=>n??0)},renderFromPool(e){return B(()=>Ge(e)).then(n=>n??false)}};export{w as DEFAULT_CONFIG,le as HOOK_CATALOG,N as SDK_VERSION,U as detectImageProtocol,z as renderBlip,h as renderCard,kn as sponsor,A as textCardForBlip};
6
+ `,"utf8");for(let f=0;;f++)try{m.renameSync(a,o);return}catch(l){let u=l.code??"";if(f>=4||!re.has(u)){try{m.rmSync(a,{force:!0});}catch{}if(f>=4)return;throw l}try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(f+1));}catch{}}}var qe=["CI","CONTINUOUS_INTEGRATION","GITHUB_ACTIONS","GITLAB_CI","CIRCLECI","TRAVIS","BUILDKITE","JENKINS_URL","TEAMCITY_VERSION","TF_BUILD","APPVEYOR","CODEBUILD_BUILD_ID","DRONE","NETLIFY","VERCEL"];function Y(e){return e!==void 0&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}function Ne(e){return Y(e.OPENCRATER_DISABLE)||Y(e.TSN_DISABLE)}function De(e){return qe.some(n=>Y(e[n]))}function H(e){return e?{...w,...e}:w}function C(e,n={}){if(Ne(e.env))return "env_disabled";if(e.state.optOut)return "opt_out";let t=H(e.state.cachedConfig);if(t.killSwitch)return "kill_switch";if(De(e.env))return "ci";if(!n.skipTTY&&!e.isTTY)return "not_tty";if(!n.skipFrequency){let o=t.minIntervalSeconds*1e3;if(e.state.lastShownAt>0&&e.now-e.state.lastShownAt<o)return "frequency"}return null}async function B(e){try{return await e()}catch(n){return c("suppressed error:",n),null}}function _(e,n){let t=H(n.cachedConfig);return {origin:K(e.apiOrigin),timeoutMs:t.serveTimeoutMs,installId:n.installId,config:t}}function Fe(e,n){let t=!n.disclosureShown,o=h(e,{width:process.stdout.columns??80,color:P(),hyperlinks:I(),disclosure:t});return process.stdout.write(o),{...n,lastShownAt:Date.now(),disclosureShown:true}}async function ae(e,n){let t=await z(e,{width:process.stdout.columns??80,color:P(),hyperlinks:I(),disclosure:!n.disclosureShown});return process.stdout.write(t),{...n,lastShownAt:Date.now(),disclosureShown:true}}async function $e(e){let n=x(),t=C({env:process.env,isTTY:!!process.stdout.isTTY,state:n,now:Date.now()},{skipFrequency:true});if(t!==null)return c("fetch suppressed:",t),null;let o=_(e,n),i=await F(e,o);return i?(p({...n,cachedConfig:i.config,configFetchedAt:Date.now()}),i.fill&&i.blip?i.blip:null):null}async function Ue(e){let n=x(),t=C({env:process.env,isTTY:!!process.stdout.isTTY,state:n,now:Date.now()});if(t!==null)return c("suppressed:",t),false;let o=_(e,n),i=await F(e,o);return i?(n={...n,cachedConfig:i.config,configFetchedAt:Date.now()},i.fill&&i.blip?(n=await ae(i.blip,n),p(n),$(i.blip.impressionId,o,i.blip.renderToken),true):i.fallback?(n=Fe(Z(i.fallback),n),p(n),true):(p(n),false)):false}async function ze(e){let n=x(),t=C({env:process.env,isTTY:!!process.stdout.isTTY,state:n,now:Date.now()},{skipTTY:true,skipFrequency:true});if(t!==null)return c("preload suppressed:",t),0;let o=_(e,n),i=Math.max(1,o.config.preloadPoolSize),r=await X(e,i,o);if(!r)return 0;let s=Date.now(),a=ee(r.blips,s);return p({...n,pool:a,cachedConfig:r.config,configFetchedAt:s}),a.length}async function Ge(e){let n=x(),t=Date.now(),o=C({env:process.env,isTTY:!!process.stdout.isTTY,state:n,now:t});if(o!==null)return c("renderFromPool suppressed:",o),false;let{blip:i,pool:r}=ne(n,t);if(!i)return p({...n,pool:r}),false;let s=await ae(i,{...n,pool:r});p(s);let a=_(e,n);return $(i.impressionId,a,i.renderToken),true}var kn={show(e){return B(()=>Ue(e)).then(n=>n??false)},fetch(e){return B(()=>$e(e))},preload(e){return B(()=>ze(e)).then(n=>n??0)},renderFromPool(e){return B(()=>Ge(e)).then(n=>n??false)}};export{w as DEFAULT_CONFIG,le as HOOK_CATALOG,N as SDK_VERSION,U as detectImageProtocol,z as renderBlip,h as renderCard,kn as sponsor,A as textCardForBlip};
package/dist/paint.js CHANGED
@@ -2,7 +2,7 @@
2
2
  'use strict';var child_process=require('child_process'),crypto=require('crypto'),zt=require('http'),re=require('fs'),Tt=require('os'),L=require('path'),zlib=require('zlib'),pt=require('tty');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 zt__namespace=/*#__PURE__*/_interopNamespace(zt);var re__namespace=/*#__PURE__*/_interopNamespace(re);var Tt__namespace=/*#__PURE__*/_interopNamespace(Tt);var L__namespace=/*#__PURE__*/_interopNamespace(L);var pt__namespace=/*#__PURE__*/_interopNamespace(pt);var tt=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,i)=>(typeof require<"u"?require:t)[i]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});function Pt(e){return e>=21||e<8?.2:.4}function Rt(e,t){let i=t.filter(o=>Number.isFinite(o)&&e-o<6e5&&o<=e);return i.length>=2?{play:false,next:i}:{play:true,next:[...i,e]}}function rt(e=process.env){return L__namespace.join(Tt__namespace.homedir(),".config","opencrater")}var mn=600*1e3;function ot(){return L__namespace.join(rt(),"blocked-ads.json")}function st(){return L__namespace.join(rt(),"reported-ads.json")}function gn(e,t){let i={};for(let[o,a]of Object.entries(e))typeof a=="number"&&Number.isFinite(a)&&a>t&&(i[o]=a);return i}function hn(e){try{let t=JSON.parse(re__namespace.readFileSync(ot(),"utf8"));return gn(t&&typeof t=="object"?t:{},e)}catch{return {}}}function Ne(e,t=Date.now()){if(e)try{let i=hn(t);i[e]=t+mn,re__namespace.mkdirSync(L__namespace.dirname(ot()),{recursive:!0}),re__namespace.writeFileSync(ot(),JSON.stringify(i));}catch{}}function bn(){try{let e=JSON.parse(re__namespace.readFileSync(st(),"utf8"));return e&&typeof e=="object"?e:{}}catch{return {}}}function Mt(e,t=Date.now()){if(e)try{let i=bn();i[e]=t,re__namespace.mkdirSync(L__namespace.dirname(st()),{recursive:!0}),re__namespace.writeFileSync(st(),JSON.stringify(i));}catch{}}var wn=[137,80,78,71,13,10,26,10];function Wt(e){try{if(e.length<45)return null;for(let A=0;A<8;A++)if(e[A]!==wn[A])return null;let t=new DataView(e.buffer,e.byteOffset,e.byteLength),i=8,o=0,a=0,u=0,n=-1,m=0,p=[];for(;i+8<=e.length;){let A=t.getUint32(i),N=String.fromCharCode(e[i+4],e[i+5],e[i+6],e[i+7]),U=e.subarray(i+8,i+8+A);if(N==="IHDR")o=t.getUint32(i+8),a=t.getUint32(i+12),u=e[i+16],n=e[i+17],m=e[i+20];else if(N==="IDAT")p.push(U);else if(N==="IEND")break;i+=12+A;}if(u!==8||n!==2&&n!==6||m!==0||o===0||a===0||o>1024||a>1024)return null;let y=n===6?4:3,g=o*y,c=zlib.inflateSync(Buffer.concat(p.map(A=>Buffer.from(A))));if(c.length<(g+1)*a)return null;let M=new Uint8Array(o*a*4),S=new Uint8Array(g),x=new Uint8Array(g);for(let A=0;A<a;A++){let N=A*(g+1),U=c[N];for(let j=0;j<g;j++){let I=c[N+1+j],b=j>=y?x[j-y]:0,$=S[j],F=j>=y?S[j-y]:0,w;switch(U){case 0:w=I;break;case 1:w=I+b;break;case 2:w=I+$;break;case 3:w=I+(b+$>>1);break;case 4:{let W=b+$-F,V=Math.abs(W-b),xe=Math.abs(W-$),B=Math.abs(W-F);w=I+(V<=xe&&V<=B?b:xe<=B?$:F);break}default:return null}x[j]=w&255;}for(let j=0;j<o;j++){let I=j*y,b=(A*o+j)*4;M[b]=x[I],M[b+1]=x[I+1],M[b+2]=x[I+2],M[b+3]=y===4?x[I+3]:255;}S.set(x);}return {width:o,height:a,rgba:M}}catch{return null}}var _e=300,Et=140,lt=12e3,An=9;var On=1500,Nt=3*1024*1024,Pn=12*1024*1024,Rn=12*1024*1024,Tn=6e3,_t=25e3,Ht=64,k="\x1B",Mn="\x07",Lt=`${k}7`,Dt=`${k}8`;function Le(e,t){return `${k}]8;;${e}${k}\\${t}${k}]8;;${k}\\`}function De(e){return e.replace(/\x1b\[[0-9;]*m/g,"").replace(/\x1b\]8;;[^\x1b\x07]*(?:\x1b\\|\x07)/g,"").replace(/[︎️]/g,"").length}function me(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1))}\u2026`}function Wn(e,t){let i=e.split(/\s+/).filter(Boolean),o=[],a="";for(let u of i)if(a===""?a=me(u,t):a.length+1+u.length<=t?a+=` ${u}`:(o.push(a),a=me(u,t)),o.length>=3)break;return a&&o.length<4&&o.push(a),o}var H=process.platform==="win32";function oe(e){return H?`${e}\uFE0E`:e}function En(e){let t=()=>{try{re.closeSync(e);}catch{}};return {write:i=>{try{re.writeSync(e,i);}catch{}},close:t,closeAndWait:async()=>t()}}var Nn=["$ErrorActionPreference='SilentlyContinue'","$dbg=$env:OPENCRATER_DEBUG -eq '1'","$log=Join-Path $env:USERPROFILE '.config\\opencrater\\pump.log'","function L($m){ if($dbg){ try{ Add-Content -LiteralPath $log -Value ((Get-Date).ToString('o')+' '+$m) }catch{} } }","L 'pump: process started (loading types)'","Add-Type -TypeDefinition @'","using System;using System.Runtime.InteropServices;","namespace OCP{","public struct COORD{public short X;public short Y;}","public struct SR{public short L;public short T;public short R;public short B;}","public struct CSBI{public COORD sz;public COORD cur;public ushort attr;public SR win;public COORD max;}","public static class N{",'[DllImport("kernel32.dll",SetLastError=true,CharSet=CharSet.Unicode)]public static extern IntPtr CreateFileW(string n,uint a,uint s,IntPtr sec,uint d,uint f,IntPtr t);','[DllImport("kernel32.dll")]public static extern bool GetConsoleMode(IntPtr h,out uint m);','[DllImport("kernel32.dll")]public static extern bool SetConsoleMode(IntPtr h,uint m);','[DllImport("kernel32.dll")]public static extern bool SetConsoleOutputCP(uint cp);','[DllImport("kernel32.dll")]public static extern bool WriteFile(IntPtr h,byte[] b,uint n,out uint w,IntPtr o);','[DllImport("kernel32.dll")]public static extern bool FreeConsole();','[DllImport("kernel32.dll")]public static extern bool AttachConsole(uint p);','[DllImport("kernel32.dll")]public static extern IntPtr GetStdHandle(int n);','[DllImport("kernel32.dll")]public static extern bool GetConsoleScreenBufferInfo(IntPtr h,out CSBI i);',"}}","'@","L 'pump: types loaded'","$o=[uint32]'0xC0000000'","function OpenConout(){ return [OCP.N]::CreateFileW('CONOUT$',$o,3,[IntPtr]::Zero,3,0,[IntPtr]::Zero) }","function Csbi($hh){ $z=New-Object OCP.CSBI; if($hh -ne [IntPtr]-1 -and [OCP.N]::GetConsoleScreenBufferInfo($hh,[ref]$z)){ return $z } else { return $null } }","$self=Csbi (OpenConout); if($self){ L ('pump: SELF bufH='+$self.sz.Y+' winRows='+($self.win.B-$self.win.T+1)+' curY='+$self.cur.Y) }","$how='self'; $winId=0","$given=[int]($env:OPENCRATER_WIN_CONSOLE_PID)","if($given -gt 0){ [void][OCP.N]::FreeConsole(); if([OCP.N]::AttachConsole([uint32]$given)){ $winId=$given; $how='given' } L ('pump: given console pid '+$given+' attached='+($winId -eq $given)) }","if($winId -eq 0){"," $par=@{}; try{ Get-CimInstance Win32_Process -ErrorAction Stop | ForEach-Object { $par[[int]$_.ProcessId]=[int]$_.ParentProcessId } }catch{ L 'pump: WMI walk failed' }"," $chain=New-Object System.Collections.ArrayList; $p=$PID; for($i=0;$i -lt 12;$i++){ if(-not $par.ContainsKey($p)){break}; $pp=$par[$p]; if($pp -le 4){break}; $nm='?'; try{ $nm=(Get-Process -Id $pp -ErrorAction Stop).ProcessName }catch{}; [void]$chain.Add(@{id=$pp;name=$nm}); $p=$pp }"," L ('pump: ancestors = ' + (($chain | ForEach-Object { $_.name+'('+$_.id+')' }) -join ' -> '))"," foreach($c in $chain){ [void][OCP.N]::FreeConsole(); if([OCP.N]::AttachConsole([uint32]$c.id)){ $b=Csbi (OpenConout); if($b){ L ('pump: '+$c.name+'('+$c.id+') bufH='+$b.sz.Y+' winRows='+($b.win.B-$b.win.T+1)+' curY='+$b.cur.Y); if($b.sz.Y -lt 1000 -and $c.name -notmatch '^(WindowsTerminal|OpenConsole|conhost|explorer|Code|devenv|wininit|services|svchost|WmiPrvSE)$'){ $winId=$c.id; $how=('attach:'+$c.name) } } } }","}","[void][OCP.N]::FreeConsole()","if($winId -ne 0){ [void][OCP.N]::AttachConsole([uint32]$winId) } else { [void][OCP.N]::AttachConsole(0xFFFFFFFF); $how='attach-parent' }","$h=OpenConout","if($h -eq [IntPtr]-1){ L 'pump: NO CONSOLE after attach walk'; exit 1 }","$fb=Csbi $h; if($fb){ L ('pump: FINAL via '+$how+' bufH='+$fb.sz.Y+' winRows='+($fb.win.B-$fb.win.T+1)+' curY='+$fb.cur.Y) } else { L ('pump: FINAL via '+$how) }","if($fb){ $cols=$fb.win.R-$fb.win.L+1; $rows=$fb.win.B-$fb.win.T+1; [Console]::Out.WriteLine('OCWIN '+$winId+' '+$cols+' '+$rows); [Console]::Out.Flush() }","$m=[uint32]0;[void][OCP.N]::GetConsoleMode($h,[ref]$m);[void][OCP.N]::SetConsoleMode($h,($m -bor 4));[void][OCP.N]::SetConsoleOutputCP(65001)","$in=[Console]::OpenStandardInput();$buf=New-Object byte[] 65536;$tot=0;$frames=0","while(($n=$in.Read($buf,0,$buf.Length)) -gt 0){$w=[uint32]0;[void][OCP.N]::WriteFile($h,$buf,$n,[ref]$w,[IntPtr]::Zero);$tot+=$w;$frames++}","L ('pump: stdin closed, streamed '+$tot+' bytes in '+$frames+' chunks')"].join(`
3
3
  `);function Jt(){return `${process.env.SystemRoot||process.env.windir||"C:\\Windows"}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`}function _n(){try{let e=Buffer.from(Nn,"utf16le").toString("base64"),t=Jt(),i="ignore";if(process.env.OPENCRATER_DEBUG==="1")try{i=re.openSync(L__namespace.join(Tt.homedir(),".config","opencrater","pump-err.log"),"a");}catch{}E("spawning pump:",t);let o=child_process.spawn(t,["-NoProfile","-NonInteractive","-EncodedCommand",e],{stdio:["pipe","pipe",i],windowsHide:!0});o.on("error",m=>E("pump spawn error:",t,"-",m.message)),o.on("exit",m=>E("pump process exited code",m,"pid",o.pid));let a=o.stdin;if(!a)return E("pump: no stdin pipe"),null;a.on("error",()=>{});let u=!1;return o.on("exit",()=>{u=!0;}),{size:new Promise(m=>{let p="",y=!1,g=M=>{y||(y=!0,m(M));},c=o.stdout;if(!c)return g(null);c.setEncoding("utf8"),c.on("data",M=>{p+=M;let S=p.match(/OCWIN\s+(\d+)\s+(\d+)\s+(\d+)/);S&&(E("pump reported console pid",S[1],"size",S[2]+"x"+S[3]),g({pid:Number(S[1]),cols:Number(S[2]),rows:Number(S[3])}));}),c.on("error",()=>g(null)),c.on("end",()=>g(null)),setTimeout(()=>g(null),2500);}),write:m=>{try{a.write(m);}catch{}},close:()=>{try{a.end();}catch{}},closeAndWait:()=>new Promise(m=>{if(u)return m();let p=!1,y=()=>{p||(p=!0,m());};o.on("exit",y),setTimeout(y,5e3);try{a.end();}catch{y();}})}}catch(e){return E("pump: spawn threw",e.message),null}}function Ln(e){try{let t=e.replace(/'/g,"''"),i=`$ErrorActionPreference='Stop';try{$r=$null;try{$su=([wmiclass]'Win32_ProcessStartup').CreateInstance();$su.CreateFlags=[uint32]8;$r=([wmiclass]'Win32_Process').Create('${t}',$null,$su)}catch{};if($r -eq $null -or $r.ReturnValue -ne 0){$r=([wmiclass]'Win32_Process').Create('${t}')};if($r.ReturnValue -eq 0){[Console]::Out.Write('OCPID '+$r.ProcessId)}else{[Console]::Out.Write('OCERR rv='+$r.ReturnValue)}}catch{[Console]::Out.Write('OCERR '+$_.Exception.Message)}`,o=Buffer.from(i,"utf16le").toString("base64"),a=child_process.spawnSync(Jt(),["-NoProfile","-NonInteractive","-EncodedCommand",o],{timeout:5e3,encoding:"utf8"}),u=(a.stdout??"").match(/OCPID\s+(\d+)/);return u?Number(u[1]):(E("wmi spawn failed:",(a.stdout??"").trim(),"|",(a.stderr??"").trim()),0)}catch(t){return E("wmi spawn threw",t.message),0}}function Dn(e,t){try{let i=L__namespace.join(Tt.homedir(),".config","opencrater");re.mkdirSync(i,{recursive:!0});let o=L__namespace.join(i,`paint-${process.pid}-${Date.now()}.json`);re.writeFileSync(o,JSON.stringify({...e,_env:process.env}),"utf8");let a=m=>`"${m}"`,u=[a(process.execPath),a(__filename),"--persist","--payload-file",a(o),"--console-pid",String(t)];qe&&u.push("--debug");let n=Ln(u.join(" "));return E("escape: wmi persistent painter pid",n),n>0}catch(i){return E("escape failed",i.message),false}}function ki(e){return !!(e.WT_SESSION||e.TERM_PROGRAM||e.ConEmuANSI==="ON"||e.ANSICON)}function qn(){try{let e=child_process.spawnSync("mode",["con"],{timeout:1500,encoding:"utf8"}).stdout;if(!e)return null;let i=[...e.matchAll(/:\s*(\d+)/g)].map(o=>Number(o[1]))[1];return i&&i>0?i:null}catch{return null}}function Un(e){let t=e.TERM_PROGRAM??"",i=e.TERM??"";return e.TMUX?"none":t==="iTerm.app"||e.LC_TERMINAL==="iTerm2"||t==="WezTerm"?"iterm2":i==="xterm-kitty"||e.KITTY_WINDOW_ID?"kitty":"none"}function qt(e,t){let i=e.toString("base64");return `${k}]1337;File=inline=1;size=${e.length};width=${t.w};height=${t.h};preserveAspectRatio=1:${i}${Mn}`}function Fn(e,t){let i=e.toString("base64"),o=[];for(let u=0;u<i.length;u+=4096)o.push(i.slice(u,u+4096));let a="";for(let u=0;u<o.length;u++){let n=u===0,m=u===o.length-1,p=n?`a=T,f=100,c=${t.w},r=${t.h},m=${m?0:1}`:`m=${m?0:1}`;a+=`${k}_G${p};${o[u]}${k}\\`;}return a}function Bn(e){let t=(e.COLORTERM??"").toLowerCase();if(t.includes("truecolor")||t.includes("24bit"))return true;let i=e.TERM_PROGRAM??"";return ["iTerm.app","WezTerm","vscode","ghostty","Apple_Terminal"].includes(i)}function ct(e,t,i){if(Math.abs(e-t)<12&&Math.abs(t-i)<12&&Math.abs(e-i)<12)return e<8?16:e>248?231:232+Math.round((e-8)/247*23);let o=a=>Math.round(a/255*5);return 16+36*o(e)+6*o(t)+o(i)}var zn=[" ","\u2598","\u259D","\u2580","\u2596","\u258C","\u259E","\u259B","\u2597","\u259A","\u2590","\u259C","\u2584","\u2599","\u259F","\u2588"];function Yt(e,t,i,o){let a=[],u=(m,p)=>{let y=(p*t+m)*3;return [e[y],e[y+1],e[y+2]]},n=(m,p)=>{let y=m[0]-p[0],g=m[1]-p[1],c=m[2]-p[2];return y*y+g*g+c*c};for(let m=0;m+1<i;m+=2){let p="",y="";for(let g=0;g+1<t;g+=2){let c=[u(g,m),u(g+1,m),u(g,m+1),u(g+1,m+1)],M=0,S=1,x=-1;for(let w=0;w<4;w++)for(let W=w+1;W<4;W++){let V=n(c[w],c[W]);V>x&&(x=V,M=w,S=W);}let A=0,N=[0,0,0],U=[0,0,0],j=0,I=0;for(let w=0;w<4;w++)n(c[w],c[M])<=n(c[w],c[S])?(A|=1<<w,N[0]+=c[w][0],N[1]+=c[w][1],N[2]+=c[w][2],j++):(U[0]+=c[w][0],U[1]+=c[w][1],U[2]+=c[w][2],I++);if(x<1e3){let w=xe=>xe&-8,W=[w(Math.round((c[0][0]+c[1][0]+c[2][0]+c[3][0])/4)),w(Math.round((c[0][1]+c[1][1]+c[2][1]+c[3][1])/4)),w(Math.round((c[0][2]+c[1][2]+c[2][2]+c[3][2])/4))],V=o?`${k}[48;2;${W[0]};${W[1]};${W[2]}m`:`${k}[48;5;${ct(W[0],W[1],W[2])}m`;V!==y&&(p+=V,y=V),p+=" ";continue}let b=j?[Math.round(N[0]/j),Math.round(N[1]/j),Math.round(N[2]/j)]:[0,0,0],$=I?[Math.round(U[0]/I),Math.round(U[1]/I),Math.round(U[2]/I)]:b,F=o?`${k}[38;2;${b[0]};${b[1]};${b[2]};48;2;${$[0]};${$[1]};${$[2]}m`:`${k}[38;5;${ct(b[0],b[1],b[2])};48;5;${ct($[0],$[1],$[2])}m`;F!==y&&(p+=F,y=F),p+=zn[A];}p+=`${k}[0m`,a.push(p);}return a}function Gn(e,t,i,o,a,u){let n=t*2,m=i*2,p=`${u?`${u},`:""}scale=${n}:${m}:flags=lanczos+accurate_rnd`,y=["-y","-i",e];o?y.push("-t","6","-vf",`fps=7,${p}`):y.push("-frames:v","1","-vf",p),y.push("-f","rawvideo","-pix_fmt","rgb24","-");let g=child_process.spawnSync("ffmpeg",y,{timeout:12e3,maxBuffer:64*1024*1024});if(g.status!==0||!g.stdout||g.stdout.length===0)return null;let c=n*m*3,M=Math.min(Math.floor(g.stdout.length/c),Ht);if(M===0)return null;let S=[];for(let x=0;x<M;x++)S.push(Yt(g.stdout.subarray(x*c,(x+1)*c),n,m,a));return S}function Hn(e,t,i,o,a,u){if(!te("chafa"))return null;let n=L__namespace.join(t,"fr_%03d.png"),m=["-y","-i",e],p=[];if(a?(m.push("-t","6"),p.push("fps=5")):m.push("-frames:v","1"),u&&p.push(u),p.length>0&&m.push("-vf",p.join(",")),m.push(n),child_process.spawnSync("ffmpeg",m,{timeout:12e3}).status!==0)return null;let g=[];for(let c=1;c<=Ht;c++){let M=L__namespace.join(t,`fr_${String(c).padStart(3,"0")}.png`),S;try{S=child_process.spawnSync("chafa",a?["-f","symbols","-s",`${i}x${o}`,"--stretch","--symbols","vhalf","--colors","full",M]:["-f","symbols","-s",`${i}x${o}`,"--stretch","--colors","full",M],{timeout:5e3,maxBuffer:8*1024*1024,encoding:"utf8"});}catch{break}if(S.status!==0||!S.stdout)break;let A=S.stdout.replace(/\x1b\[\?25[lh]/g,"").split(`
4
4
  `).filter(I=>I.length>0);if(A.length===0)break;let N=" ".repeat(i),U=Math.floor((o-A.length)/2),j=[];for(let I=0;I<o;I++){let b=A[I-U];if(b===void 0)j.push(N);else {let $=" ".repeat(Math.max(0,i-De(b)));j.push(b+$);}}g.push(j);}return g.length>0?g:null}function Vt(e){try{let t=child_process.spawnSync("ffprobe",["-v","quiet","-select_streams","v:0","-show_entries","stream=width,height","-of","csv=p=0",e],{timeout:5e3,encoding:"utf8"});if(t.status!==0||!t.stdout)return null;let i=t.stdout.trim().match(/^(\d+),(\d+)/);if(!i)return null;let o=Number(i[1]),a=Number(i[2]);return o>0&&a>0?{w:o,h:a}:null}catch{return null}}function Jn(e){try{let i=(child_process.spawnSync("ffmpeg",["-t","2","-i",e,"-vf","cropdetect=24:2:1","-f","null","-"],{timeout:8e3,encoding:"utf8"}).stderr??"").match(/crop=(\d+):(\d+):(\d+):(\d+)/g);if(!i||i.length===0)return null;let o=i[i.length-1],a=o.match(/crop=(\d+):(\d+):(\d+):(\d+)/),u=Number(a[1]),n=Number(a[2]);if(u<8||n<8)return null;let m=Vt(e);if(m){let p=u*n/(m.w*m.h);if(p<.55||p>.92)return null}return o}catch{return null}}function te(e){try{return H?child_process.spawnSync("where",[e],{timeout:2e3}).status===0:child_process.spawnSync("sh",["-c",'command -v -- "$1" >/dev/null 2>&1',"sh",e],{timeout:2e3}).status===0}catch{return false}}async function Ut(e,t){try{let i=await fetch(e,{signal:AbortSignal.timeout(Tn)});if(!i.ok)return null;let o=(i.headers.get("content-type")??"").split(";")[0].trim().toLowerCase();if(Number(i.headers.get("content-length")??"0")>t)return null;let u=Buffer.from(await i.arrayBuffer());return u.length===0||u.length>t?null:{data:u,type:o}}catch{return null}}var Se=L__namespace.join(Tt.homedir(),".config","opencrater","painter.lock"),Yn=6e3;function Ft(e){try{if(!re.existsSync(Se))return;let t=JSON.parse(re.readFileSync(Se,"utf8"));if(t.pid&&t.pid!==process.pid){if(t.startedAt&&Date.now()-t.startedAt<Yn){let o=!0;try{process.kill(t.pid,0);}catch{o=!1;}o&&(e.close(),process.exit(0));}let i=!0;try{process.kill(t.pid,"SIGTERM");}catch{i=!1;}try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,250);}catch{}if(t.rows>0&&t.width>0){let o="\x1B7\x1B[0m",a=" ".repeat(t.width);for(let u=0;u<t.rows;u++)o+=`\x1B[${t.row+u};${t.col}H${a}`;o+="\x1B8",e.write(o);}}}catch{}}var Bt="";function Vn(e){let t=JSON.stringify(e);if(t!==Bt){Bt=t;try{re.mkdirSync(L__namespace.dirname(Se),{recursive:!0}),re.writeFileSync(Se,JSON.stringify(e));}catch{}}}function Xn(){try{JSON.parse(re.readFileSync(Se,"utf8")).pid===process.pid&&re.unlinkSync(Se);}catch{}}var qe=process.env.OPENCRATER_DEBUG==="1";function E(...e){try{if(!qe)return;let t=`[opencrater-paint] ${e.map(i=>String(i)).join(" ")}`;console.error(t);try{re.appendFileSync(L__namespace.join(Tt.homedir(),".config","opencrater","paint.log"),`${new Date().toISOString()} ${t}
5
- `);}catch{}}catch{}}function Kn(){let e=process.argv.slice(2),t=r=>{let s=e.indexOf(r);return s>=0?e[s+1]:void 0};e.includes("--debug")&&(qe=true,process.env.OPENCRATER_DEBUG="1");let i=e.includes("--persist")||process.env.OPENCRATER_WIN_PERSIST==="1",o=Number(t("--console-pid")??"0");o>0&&(process.env.OPENCRATER_WIN_CONSOLE_PID=String(o));let a=t("--payload-file"),u=process.env.OPENCRATER_PAINT;if(a)try{u=re.readFileSync(a,"utf8");}catch(r){E("payload-file unreadable:",r.message);}if(!u){E("no paint payload (env or --payload-file) \u2014 nothing to draw");return}let n;try{let r=JSON.parse(u);if(r._env&&typeof r._env=="object"){let s=process.env.OPENCRATER_WIN_CONSOLE_PID;Object.assign(process.env,r._env),s&&(process.env.OPENCRATER_WIN_CONSOLE_PID=s),process.env.OPENCRATER_DEBUG==="1"&&(qe=!0),delete r._env;}n=r;}catch(r){E("paint payload is not valid JSON:",r.message);return}let m=process.env.OPENCRATER_TTY??"/dev/tty",p,y=-1;if(H){let r=_n();if(!r){E("Windows: could not start the console pump (powershell.exe)");return}p=r;}else {try{y=re.openSync(m,"w");}catch(r){E("could not open output device",m,"-",r.message);return}p=En(y);}E("painting via",H?"Windows console pump":m,"format",n.format??"text"),process.env.OPENCRATER_FLOW!=="1"&&!H&&Ft(p);let g=0;if(H)g=qn()??0;else try{let r=new pt__namespace.WriteStream(y);r.columns&&(g=r.columns);}catch{}g||(g=80);let c=process.env.NO_COLOR===void 0,M=c&&Bn(process.env),S=(n.format??"text").toLowerCase(),x=S==="image"||S==="logo",A=S==="gif"||S==="video",N=A?72:56,U=H?24:40;if(H)process.stdout.rows&&(U=process.stdout.rows);else try{let r=new pt__namespace.WriteStream(re.openSync(m,"w"));r.rows&&(U=r.rows);}catch{}let j=A?Math.max(8,Math.min(16,Math.floor((U-14)/2)*2)):An,I=x?5:j,b=Math.min(N,g-4);if(b<24){p.close();return}let $=b-4,F=Math.max(1,g-b-1),w=2,W=Date.now(),V=c?`${k}[2m`:"",B=c?`${k}[38;5;214m`:"",_=c?`${k}[0m`:"",R=S,Ie=Un(process.env),Ae=process.env.OPENCRATER_FLOW==="1",Xt=process.env.OPENCRATER_MUTE==="1",se=n.apiOrigin??"https://api.opencrater.to",Ce=R==="video"?`${oe("\u25B6")} `:R==="audio"?`${oe("\u266A")} `:"",mt=false,gt=r=>{if(n.impressionId)try{fetch(`${se}/v1/events/engagement`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({impressionId:n.impressionId,events:r}),signal:AbortSignal.timeout(1500)}).catch(()=>{});}catch{}},Kt=1e3,ht=false,Ue=setTimeout(()=>{if(ht||!n.reportImpressionUrl||!n.impressionId||n.replay)return;ht=true;let r=Date.now()-W,s=H?"win-console":process.env.OPENCRATER_TTY??"tty";E("reporting confirmed render \u2014 visibleMs",r,"surface",s);try{fetch(n.reportImpressionUrl,{method:"POST",headers:{"content-type":"application/json",...n.reportImpressionAuth?{authorization:`Bearer ${n.reportImpressionAuth}`}:{}},body:JSON.stringify({impressionId:n.impressionId,rendered:!0,surface:s}),signal:AbortSignal.timeout(8e3)}).catch(()=>{});}catch{}},Kt),ie=null,z=null,Oe=0,ue=0,X=null,J="none",Fe=null,Be=null,ae=null,ze=0,bt=0,Z=null,T=0,O=0,Qt=(r,s)=>{let f=r/s,l=x?Math.min(10,Math.floor($*.35)):$;T=Math.max(4,Math.min(l,Math.round(2*f*I))),O=Math.max(2,Math.min(I,Math.round(l/(2*f))||I)),x&&(O=Math.min(O,I));let d=Math.min(1,r/(T*2),s/(O*2));d<1&&(T=Math.max(8,Math.floor(T*d)),O=Math.max(2,Math.floor(O*d)));},ge=0,en=()=>{let r=(n.label??"").trim(),s=(n.sponsorLabel??"").trim(),f=s.toLowerCase()===n.title.trim().toLowerCase(),l=r||(s&&!f?`Sponsored Blips \xB7 ${s}`:"Sponsored Blips"),d=[],h=he??`${se}/x/${n.impressionId}`,v=n.impressionId||n.replay&&he?Le(h,oe("\u2715")):"",G=ge>0&&!Ae?Math.max(0,Math.ceil((ge-Date.now())/1e3)):0,D=G>0?`Auto dismiss in: ${G}s `:"",P=c?G<=5?`${k}[1;38;5;196m`:G<=12?`${k}[1;38;5;178m`:`${k}[1;38;5;35m`:"",C=me(l,Math.max(8,$-2-D.length)),q=" ".repeat(Math.max(1,$-C.length-D.length-1));d.push(`${V}${C}${_}${q}${P}${D}${_}${B}${v}${_}`);let Q=c?Ie!=="none"||(process.env.COLORTERM??"").includes("truecolor")?`${k}[1;38;2;255;184;48m`:`${k}[1;38;5;214m`:"",ee=x&&O>0?$-T-2:$;x||d.push(""),d.push(`${Q}${me(n.title.toUpperCase(),ee)}${_}`);for(let Y of Wn(n.body,ee))d.push(Y);if(J!=="none"){let Y=J==="playing"?`${oe("\u23F8")} pause`:J==="paused"?`${oe("\u25B6")} play`:`${oe("\u25B6")} replay`,de=Math.max(6,Math.min(14,ee-Y.length-5)),pe="\u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588",We="";for(let Ee=0;Ee<de;Ee++){let un=J==="playing"?Math.abs(Math.sin(ue*.9+Ee*1.7)*.55+Math.sin(ue*.37+Ee*.53)*.45):.05;We+=pe[Math.max(0,Math.min(7,Math.floor(un*8)))];}let fn=Fe?Le(Fe,Y):Y;d.push(`${oe("\u266A")} ${B}${We}${_} ${B}${fn}${_}`);}let Xe=process.env.TERM_PROGRAM??"",sn=process.env.TERM??"",Ke=Ie!=="none"||["vscode","ghostty","iTerm.app","WezTerm","Hyper","WarpTerminal","rio","Tabby"].includes(Xe)||/kitty|wezterm|alacritty|foot|rio|ghostty/i.test(sn)||process.env.WT_SESSION!==void 0||process.env.ConEmuANSI==="ON"||process.env.VTE_VERSION!==void 0,Ze=(Y,de,pe)=>c?`${k}[48;2;${de[0]};${de[1]};${de[2]};38;2;${pe[0]};${pe[1]};${pe[2]};1m ${Y} ${k}[0m`:`[ ${Y} ]`,ye=[240,178,50],Qe=[12,12,10],et=n.impressionId?`${se}/k/${n.impressionId}`:n.url,we=[];if(Ke){let Y=me(n.cta&&n.cta.trim()!==""?n.cta:"visit sponsor",$-6-Ce.length);we.push(Le(n.url,Ze(`${Ce}${Y} \u2192`,ye,Qe)));}else {let Y=(n.cta&&n.cta.trim()!==""?n.cta.trim():"VISIT").toUpperCase();Ce.length+Y.length+1+et.length<=$?we.push(Ze(`${Y} ${Ce}${et}`,ye,Qe)):we.push(Ze(`${Ce}${et}`,ye,Qe));let de=process.platform==="darwin"?"\u2318-click":"Ctrl-click",pe=me(`${oe("\u2191")} ${de} the link to open`,$),We=c?`${k}[38;2;${ye[0]};${ye[1]};${ye[2]}m`:"";we.push(`${We}${pe}${_}`);}let At=Be??(n.impressionId?`${se}/r/${n.impressionId}`:null),Ot=At&&Ke?` \xB7 ${Le(At,`${oe("\u2691")} report`)}`:"",cn=Ke?"dismiss: click \u2715 or npx opencrater x \xB7 opt out: npx opencrater off":"dismiss: npx opencrater x \xB7 opt out: npx opencrater off";return we.push(`${V}${me(cn,Math.max(0,$-De(Ot)))}${Ot}${_}`),{head:d,tail:we}},yt=0,wt=()=>{let{head:r,tail:s}=en(),f=`${B}\u256D${"\u2500".repeat(b-2)}\u256E${_}`,l=`${B}\u2570${"\u2500".repeat(b-2)}\u256F${_}`,d=v=>{let G=" ".repeat(Math.max(0,$-De(v)));return `${B}\u2502${_} ${v}${G} ${B}\u2502${_}`},h;if(x&&O>0&&(z||ie)){let v=$-T-2,G=r[0]??"",D=r.slice(1),P=z?z[Oe%z.length]:null;h=[f,d(G)];let C=Math.max(D.length,O);for(let q=0;q<C;q++){let Q=D[q]??"",ee=" ".repeat(Math.max(0,v-De(Q))),Xe=q<O&&P?P[q]??" ".repeat(T):" ".repeat(T);h.push(`${B}\u2502${_} ${Q}${ee} ${Xe} ${B}\u2502${_}`);}}else {h=[f,...r.map(d)];let v=Math.max(0,Math.floor(($-T)/2)),G=Math.max(0,$-T-v);if(z&&O>0){let D=z[Oe%z.length];for(let P=0;P<O;P++){let C=D[P]??" ".repeat(T);h.push(`${B}\u2502${_} ${" ".repeat(v)}${C}${" ".repeat(G)} ${B}\u2502${_}`);}}else if(ie&&O>0)for(let D=0;D<O;D++)h.push(`${B}\u2502${_} ${" ".repeat($)} ${B}\u2502${_}`);}return h.push(...s.map(d)),h.push(l),yt=s.length+1,h},Ge=0,kt=`${k}[?2026h`,$t=`${k}[?2026l`,vt=0,St=2e3,nn=8,He=()=>{let r=wt();Ge=Math.max(Ge,r.length),Vn({pid:process.pid,row:w,col:F,width:b,rows:r.length,startedAt:W,...n.impressionId?{impressionId:n.impressionId}:{},...he?{dismissUrl:he}:{}});let s=kt+Lt,f=Date.now()<vt,l=Math.max(1,w-(f?nn:2));for(let d=l;d<w;d++)s+=`${k}[${d};${F}H${k}[0m${" ".repeat(b)}`;for(let d=0;d<r.length;d++)s+=`${k}[${w+d};${F}H${r[d]}`;if(ie&&ue%(f?1:3)===0&&O>0){let d=x?w+2:w+r.length-yt-O,h=x?F+2+($-T):F+2+Math.max(0,Math.floor(($-T)/2));s+=`${k}[${d};${h}H${ie}`;}return s+=Dt+$t,ue++,z&&z.length>1&&Oe++,s},le=()=>{p.write(He());},xt=()=>{let r=kt+Lt+`${k}[0m`,s=" ".repeat(b);for(let f=0;f<Ge;f++)r+=`${k}[${w+f};${F}H${s}`;r+=Dt+$t,p.write(r);},ce=null,Pe=null,Re=null,Te=null,he=null,K=r=>{if(E("cleanup wipe="+r+" elapsed="+(Date.now()-W)+"ms"),Ue&&(clearTimeout(Ue),Ue=null),mt||(mt=true,gt([{type:"dwell",ms:Date.now()-W}])),ce&&clearInterval(ce),Pe&&clearInterval(Pe),Re&&clearInterval(Re),r){let s=Number(process.env.OPENCRATER_HOST_PID??0);s>1&&!H&&setTimeout(()=>{try{process.kill(s,"SIGWINCH");}catch{}},80);}if(Te){try{Te.close();}catch{}Te=null;}if(ce=null,Pe=null,Re=null,X){try{X.kill("SIGKILL");}catch{}X=null;}if(Z){try{re.rmSync(Z,{recursive:!0,force:!0});}catch{}Z=null;}if(xt(),Xn(),H){let s=false,f=()=>{s||(s=true,process.exit(0));};p.closeAndWait().then(f),setTimeout(f,1500).unref?.();return}p.close(),process.exit(0);},rn=()=>{ce&&clearInterval(ce);let s=T*O>1100?200:Et;ce=setInterval(le,z&&z.length>1?s:_e);},Me=()=>(Z||(Z=re.mkdtempSync(L__namespace.join(Tt.tmpdir(),"ocpaint-"))),Z),Je=async()=>{if(n.mediaPixelUrl&&(S==="image"||S==="logo"))try{let P=await fetch(n.mediaPixelUrl,{signal:AbortSignal.timeout(2500)});if(P.ok){let C=Wt(new Uint8Array(await P.arrayBuffer()));if(C&&C.width>=4&&C.height>=2){let q=Buffer.alloc(C.width*C.height*3);for(let Q=0,ee=0;Q<C.rgba.length;Q+=4,ee+=3)q[ee]=C.rgba[Q],q[ee+1]=C.rgba[Q+1],q[ee+2]=C.rgba[Q+2];T=Math.floor(C.width/2),O=Math.floor(C.height/2),z=[Yt(q,C.width,C.height,M)];return}}}catch{}if(!n.mediaUrl)return;let r=R==="video",s=await Ut(n.mediaUrl,r?Pn:Nt);if(!s||!(r?s.type.startsWith("video/"):s.type.startsWith("image/")))return;let l=L__namespace.join(Me(),"in");try{re.writeFileSync(l,s.data);}catch{return}let d=Vt(l),h=te("ffmpeg")?Jn(l):null,v=h?.match(/crop=(\d+):(\d+)/),G=v?Number(v[1]):d?.w??16,D=v?Number(v[2]):d?.h??9;if(x&&te("ffmpeg")&&G>0&&D>0){let P=Math.min(G,D),C=Math.floor((G-P)/2),q=Math.floor((D-P)/2);h=`crop=${P}:${P}:${C}:${q}`,G=P,D=P,v=null;}if(Qt(G,D),!r&&Ie==="iterm2"){ie=qt(s.data,{w:T,h:O}),ue=0;return}if(!r&&Ie==="kitty"&&s.type==="image/png"){ie=Fn(s.data,{w:T,h:O}),ue=0;return}if(r&&Ie==="iterm2"&&te("ffmpeg"))try{let P=L__namespace.join(Me(),"out.gif");if(child_process.spawnSync("ffmpeg",["-y","-i",l,"-t","6","-vf","fps=8,scale=280:-1:flags=lanczos","-loop","0",P],{timeout:12e3}).status===0){let q=re.readFileSync(P);if(q.length<=Nt){ie=qt(q,{w:T,h:O}),ue=0;return}}}catch{}if(te("ffmpeg"))try{let P=r||s.type==="image/gif",C=Hn(l,Me(),T,O,P,h)??Gn(l,T,O,P,M,h);C&&C.length>0&&(z=C,Oe=0,rn());}catch{}},Ye=(r=0)=>{if(!ae)return;let{kind:s,file:f,vol:l}=ae,d=Math.max(0,r/1e3),h,v;s==="afplay"?(h="afplay",v=["-v",l.toFixed(2),f]):s==="ffplay"?(h="ffplay",v=["-nodisp","-autoexit","-volume",String(Math.round(l*100))],d>.2&&v.push("-ss",d.toFixed(2)),v.push(f)):s==="mpv"?(h="mpv",v=["--no-video","--really-quiet",`--volume=${Math.round(l*100)}`],d>.2&&v.push(`--start=${d.toFixed(2)}`),v.push(f)):s==="paplay"?(h="paplay",v=[`--volume=${Math.round(l*65536)}`,f]):(h="mpg123",v=["-q","-f",String(Math.round(32768*l))],d>.2&&v.push("-k",String(Math.round(r/26.12))),v.push(f));try{X=H?child_process.spawn(h,v,{stdio:"ignore",detached:!0,windowsHide:!0}):child_process.spawn(h,v,{stdio:"ignore"}),J="playing",bt=Date.now(),X.on("exit",()=>{J!=="paused"&&(J="ended",ze=0);});}catch{J="none";}},on=()=>{try{J==="playing"&&X?(J="paused",ze+=Date.now()-bt,X.kill("SIGKILL"),X=null,gt([{type:"sound_muted"}])):J==="paused"?ae?.canSeek&&Ye(ze):J==="ended"&&Ye(0);}catch{}le();},be=async(r=n.mediaUrl)=>{if(!r||Xt)return;let s=L__namespace.join(Tt.homedir(),".config","opencrater","audio-plays.json");try{let l=[];try{l=JSON.parse(re.readFileSync(s,"utf8")),Array.isArray(l)||(l=[]);}catch{}let d=Rt(Date.now(),l);if(re.writeFileSync(s,JSON.stringify(d.next)),!d.play)return}catch{}let f=await Ut(r,Rn);if(!(!f||!f.type.startsWith("audio/")))try{let l=f.type.includes("wav")?"wav":f.type.includes("ogg")?"ogg":"mp3",d=L__namespace.join(Me(),`ad.${l}`);re.writeFileSync(d,f.data);let h=Pt(new Date().getHours());if(te("ffplay"))ae={kind:"ffplay",file:d,vol:h,canSeek:!0};else if(!H&&te("mpv"))ae={kind:"mpv",file:d,vol:h,canSeek:!0};else if(process.platform==="darwin"&&te("afplay"))ae={kind:"afplay",file:d,vol:h,canSeek:!1};else if(!H&&te("mpg123")&&l==="mp3")ae={kind:"mpg123",file:d,vol:h,canSeek:!0};else if(!H&&l!=="mp3"&&te("paplay"))ae={kind:"paplay",file:d,vol:h,canSeek:!1};else return;Ye(),setTimeout(()=>{try{X?.kill("SIGKILL");}catch{}(J==="playing"||J==="paused")&&(J="ended");},_t).unref?.();}catch{}},It=()=>{if(!n.impressionId||n.replay)return;let r=L__namespace.join(Tt.homedir(),".config","opencrater","dismiss.signal"),s=Date.now();Pe=setInterval(()=>{try{let f=re.readFileSync(r,"utf8"),l=JSON.parse(f),d=typeof l.at=="number"&&l.at>=s-5e3,h=!l.impressionId||l.impressionId===n.impressionId;if(d&&h){try{re.unlinkSync(r);}catch{}Ne(n.campaignId),fetch(`${se}/x/${n.impressionId}`,{signal:AbortSignal.timeout(1500)}).catch(()=>{}),K(!0);return}}catch{}(async()=>{try{let f=await fetch(`${se}/v1/events/dismissed/${n.impressionId}`,{signal:AbortSignal.timeout(1200)});if(!f.ok)return;(await f.json()).dismissed&&(Ne(n.campaignId),K(!0));}catch{}})();},On);},Ct=()=>{if(Ae)return;let r=L__namespace.join(Tt.homedir(),".config","opencrater","activity.signal"),s=Date.now(),f=1500;Re=setInterval(()=>{try{let l=re.statSync(r).mtimeMs;l>s+f&&l>Date.now()-St&&(vt=l+St,le());}catch{}},150);};if(H){(async()=>{let r=p.size?await p.size:null;if(r&&r.cols>=24&&(g=r.cols,b=Math.min(N,g-4),$=b-4,F=Math.max(1,g-b-1),E("windows geometry from pump:","cols",g,"width",b,"col",F,"ownerPid",r.pid)),R==="image"||R==="logo"||R==="gif"||R==="video"?await Je():R==="audio"&&await be(),n.audioUrl&&R!=="audio"&&be(n.audioUrl),i){let d=Math.min(Math.max(n.durationMs??lt,3e3),12e4);if(ge=Date.now()+d,a)try{re.unlinkSync(a);}catch{}Ft(p);let h=z,v=!!(h&&h.length>1);le(),ce=setInterval(le,v?Et:_e),Ct(),jt(),It(),process.on("SIGINT",()=>K(true)),process.on("SIGHUP",()=>K(true)),setTimeout(()=>K(true),d);return}let s=r?.pid??0;s>0&&Dn(n,s)&&(p.close(),process.exit(0)),E("no job-escape (ownerPid",s,") \u2014 bounded toast fallback");let f=Number(process.env.OPENCRATER_WIN_HOLD_MS),l=f>0?f:Math.min(n.durationMs??lt,5e3);if(ge=Date.now()+l,p.write(He()),await new Promise(d=>{let h=setInterval(()=>{if(Date.now()>=ge){clearInterval(h),d();return}p.write(He());},_e);}),xt(),Z)try{re.rmSync(Z,{recursive:!0,force:!0});}catch{}await p.closeAndWait(),process.exit(0);})();return}if(Ae){(async()=>{R==="image"||R==="logo"||R==="gif"||R==="video"?await Je():R==="audio"&&await be(),n.audioUrl&&R!=="audio"&&be(n.audioUrl);let r=z;r&&r.length>1&&(z=[r[0]]);let s=wt(),f=" ".repeat(Math.max(0,g-b-2)),l=`\r
5
+ `);}catch{}}catch{}}function Kn(){let e=process.argv.slice(2),t=r=>{let s=e.indexOf(r);return s>=0?e[s+1]:void 0};e.includes("--debug")&&(qe=true,process.env.OPENCRATER_DEBUG="1");let i=e.includes("--persist")||process.env.OPENCRATER_WIN_PERSIST==="1",o=Number(t("--console-pid")??"0");o>0&&(process.env.OPENCRATER_WIN_CONSOLE_PID=String(o));let a=t("--payload-file"),u=process.env.OPENCRATER_PAINT;if(a)try{u=re.readFileSync(a,"utf8");}catch(r){E("payload-file unreadable:",r.message);}if(!u){E("no paint payload (env or --payload-file) \u2014 nothing to draw");return}let n;try{let r=JSON.parse(u);if(r._env&&typeof r._env=="object"){let s=process.env.OPENCRATER_WIN_CONSOLE_PID;Object.assign(process.env,r._env),s&&(process.env.OPENCRATER_WIN_CONSOLE_PID=s),process.env.OPENCRATER_DEBUG==="1"&&(qe=!0),delete r._env;}n=r;}catch(r){E("paint payload is not valid JSON:",r.message);return}let m=process.env.OPENCRATER_TTY??"/dev/tty",p,y=-1;if(H){let r=_n();if(!r){E("Windows: could not start the console pump (powershell.exe)");return}p=r;}else {try{y=re.openSync(m,"w");}catch(r){E("could not open output device",m,"-",r.message);return}p=En(y);}E("painting via",H?"Windows console pump":m,"format",n.format??"text"),process.env.OPENCRATER_FLOW!=="1"&&!H&&Ft(p);let g=0;if(H)g=qn()??0;else try{let r=new pt__namespace.WriteStream(y);r.columns&&(g=r.columns);}catch{}g||(g=80);let c=process.env.NO_COLOR===void 0,M=c&&Bn(process.env),S=(n.format??"text").toLowerCase(),x=S==="image"||S==="logo",A=S==="gif"||S==="video",N=A?72:56,U=H?24:40;if(H)process.stdout.rows&&(U=process.stdout.rows);else try{let r=new pt__namespace.WriteStream(re.openSync(m,"w"));r.rows&&(U=r.rows);}catch{}let j=A?Math.max(8,Math.min(16,Math.floor((U-14)/2)*2)):An,I=x?5:j,b=Math.min(N,g-4);if(b<24){p.close();return}let $=b-4,F=Math.max(1,g-b-1),w=2,W=Date.now(),V=c?`${k}[2m`:"",B=c?`${k}[38;5;214m`:"",_=c?`${k}[0m`:"",R=S,Ie=Un(process.env),Ae=process.env.OPENCRATER_FLOW==="1",Xt=process.env.OPENCRATER_MUTE==="1",se=n.apiOrigin??"https://api.opencrater.to",Ce=R==="video"?`${oe("\u25B6")} `:R==="audio"?`${oe("\u266A")} `:"",mt=false,gt=r=>{if(n.impressionId)try{fetch(`${se}/v1/events/engagement`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({impressionId:n.impressionId,events:r,...n.renderToken?{renderToken:n.renderToken}:{}}),signal:AbortSignal.timeout(1500)}).catch(()=>{});}catch{}},Kt=1e3,ht=false,Ue=setTimeout(()=>{if(ht||!n.reportImpressionUrl||!n.impressionId||n.replay)return;ht=true;let r=Date.now()-W,s=H?"win-console":process.env.OPENCRATER_TTY??"tty";E("reporting confirmed render \u2014 visibleMs",r,"surface",s);try{fetch(n.reportImpressionUrl,{method:"POST",headers:{"content-type":"application/json",...n.reportImpressionAuth?{authorization:`Bearer ${n.reportImpressionAuth}`}:{}},body:JSON.stringify({impressionId:n.impressionId,rendered:!0,surface:s,...n.renderToken?{renderToken:n.renderToken}:{}}),signal:AbortSignal.timeout(8e3)}).catch(()=>{});}catch{}},Kt),ie=null,z=null,Oe=0,ue=0,X=null,J="none",Fe=null,Be=null,ae=null,ze=0,bt=0,Z=null,T=0,O=0,Qt=(r,s)=>{let f=r/s,l=x?Math.min(10,Math.floor($*.35)):$;T=Math.max(4,Math.min(l,Math.round(2*f*I))),O=Math.max(2,Math.min(I,Math.round(l/(2*f))||I)),x&&(O=Math.min(O,I));let d=Math.min(1,r/(T*2),s/(O*2));d<1&&(T=Math.max(8,Math.floor(T*d)),O=Math.max(2,Math.floor(O*d)));},ge=0,en=()=>{let r=(n.label??"").trim(),s=(n.sponsorLabel??"").trim(),f=s.toLowerCase()===n.title.trim().toLowerCase(),l=r||(s&&!f?`Sponsored Blips \xB7 ${s}`:"Sponsored Blips"),d=[],h=he??`${se}/x/${n.impressionId}`,v=n.impressionId||n.replay&&he?Le(h,oe("\u2715")):"",G=ge>0&&!Ae?Math.max(0,Math.ceil((ge-Date.now())/1e3)):0,D=G>0?`Auto dismiss in: ${G}s `:"",P=c?G<=5?`${k}[1;38;5;196m`:G<=12?`${k}[1;38;5;178m`:`${k}[1;38;5;35m`:"",C=me(l,Math.max(8,$-2-D.length)),q=" ".repeat(Math.max(1,$-C.length-D.length-1));d.push(`${V}${C}${_}${q}${P}${D}${_}${B}${v}${_}`);let Q=c?Ie!=="none"||(process.env.COLORTERM??"").includes("truecolor")?`${k}[1;38;2;255;184;48m`:`${k}[1;38;5;214m`:"",ee=x&&O>0?$-T-2:$;x||d.push(""),d.push(`${Q}${me(n.title.toUpperCase(),ee)}${_}`);for(let Y of Wn(n.body,ee))d.push(Y);if(J!=="none"){let Y=J==="playing"?`${oe("\u23F8")} pause`:J==="paused"?`${oe("\u25B6")} play`:`${oe("\u25B6")} replay`,de=Math.max(6,Math.min(14,ee-Y.length-5)),pe="\u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588",We="";for(let Ee=0;Ee<de;Ee++){let un=J==="playing"?Math.abs(Math.sin(ue*.9+Ee*1.7)*.55+Math.sin(ue*.37+Ee*.53)*.45):.05;We+=pe[Math.max(0,Math.min(7,Math.floor(un*8)))];}let fn=Fe?Le(Fe,Y):Y;d.push(`${oe("\u266A")} ${B}${We}${_} ${B}${fn}${_}`);}let Xe=process.env.TERM_PROGRAM??"",sn=process.env.TERM??"",Ke=Ie!=="none"||["vscode","ghostty","iTerm.app","WezTerm","Hyper","WarpTerminal","rio","Tabby"].includes(Xe)||/kitty|wezterm|alacritty|foot|rio|ghostty/i.test(sn)||process.env.WT_SESSION!==void 0||process.env.ConEmuANSI==="ON"||process.env.VTE_VERSION!==void 0,Ze=(Y,de,pe)=>c?`${k}[48;2;${de[0]};${de[1]};${de[2]};38;2;${pe[0]};${pe[1]};${pe[2]};1m ${Y} ${k}[0m`:`[ ${Y} ]`,ye=[240,178,50],Qe=[12,12,10],et=n.impressionId?`${se}/k/${n.impressionId}`:n.url,we=[];if(Ke){let Y=me(n.cta&&n.cta.trim()!==""?n.cta:"visit sponsor",$-6-Ce.length);we.push(Le(n.url,Ze(`${Ce}${Y} \u2192`,ye,Qe)));}else {let Y=(n.cta&&n.cta.trim()!==""?n.cta.trim():"VISIT").toUpperCase();Ce.length+Y.length+1+et.length<=$?we.push(Ze(`${Y} ${Ce}${et}`,ye,Qe)):we.push(Ze(`${Ce}${et}`,ye,Qe));let de=process.platform==="darwin"?"\u2318-click":"Ctrl-click",pe=me(`${oe("\u2191")} ${de} the link to open`,$),We=c?`${k}[38;2;${ye[0]};${ye[1]};${ye[2]}m`:"";we.push(`${We}${pe}${_}`);}let At=Be??(n.impressionId?`${se}/r/${n.impressionId}`:null),Ot=At&&Ke?` \xB7 ${Le(At,`${oe("\u2691")} report`)}`:"",cn=Ke?"dismiss: click \u2715 or npx opencrater x \xB7 opt out: npx opencrater off":"dismiss: npx opencrater x \xB7 opt out: npx opencrater off";return we.push(`${V}${me(cn,Math.max(0,$-De(Ot)))}${Ot}${_}`),{head:d,tail:we}},yt=0,wt=()=>{let{head:r,tail:s}=en(),f=`${B}\u256D${"\u2500".repeat(b-2)}\u256E${_}`,l=`${B}\u2570${"\u2500".repeat(b-2)}\u256F${_}`,d=v=>{let G=" ".repeat(Math.max(0,$-De(v)));return `${B}\u2502${_} ${v}${G} ${B}\u2502${_}`},h;if(x&&O>0&&(z||ie)){let v=$-T-2,G=r[0]??"",D=r.slice(1),P=z?z[Oe%z.length]:null;h=[f,d(G)];let C=Math.max(D.length,O);for(let q=0;q<C;q++){let Q=D[q]??"",ee=" ".repeat(Math.max(0,v-De(Q))),Xe=q<O&&P?P[q]??" ".repeat(T):" ".repeat(T);h.push(`${B}\u2502${_} ${Q}${ee} ${Xe} ${B}\u2502${_}`);}}else {h=[f,...r.map(d)];let v=Math.max(0,Math.floor(($-T)/2)),G=Math.max(0,$-T-v);if(z&&O>0){let D=z[Oe%z.length];for(let P=0;P<O;P++){let C=D[P]??" ".repeat(T);h.push(`${B}\u2502${_} ${" ".repeat(v)}${C}${" ".repeat(G)} ${B}\u2502${_}`);}}else if(ie&&O>0)for(let D=0;D<O;D++)h.push(`${B}\u2502${_} ${" ".repeat($)} ${B}\u2502${_}`);}return h.push(...s.map(d)),h.push(l),yt=s.length+1,h},Ge=0,kt=`${k}[?2026h`,$t=`${k}[?2026l`,vt=0,St=2e3,nn=8,He=()=>{let r=wt();Ge=Math.max(Ge,r.length),Vn({pid:process.pid,row:w,col:F,width:b,rows:r.length,startedAt:W,...n.impressionId?{impressionId:n.impressionId}:{},...he?{dismissUrl:he}:{}});let s=kt+Lt,f=Date.now()<vt,l=Math.max(1,w-(f?nn:2));for(let d=l;d<w;d++)s+=`${k}[${d};${F}H${k}[0m${" ".repeat(b)}`;for(let d=0;d<r.length;d++)s+=`${k}[${w+d};${F}H${r[d]}`;if(ie&&ue%(f?1:3)===0&&O>0){let d=x?w+2:w+r.length-yt-O,h=x?F+2+($-T):F+2+Math.max(0,Math.floor(($-T)/2));s+=`${k}[${d};${h}H${ie}`;}return s+=Dt+$t,ue++,z&&z.length>1&&Oe++,s},le=()=>{p.write(He());},xt=()=>{let r=kt+Lt+`${k}[0m`,s=" ".repeat(b);for(let f=0;f<Ge;f++)r+=`${k}[${w+f};${F}H${s}`;r+=Dt+$t,p.write(r);},ce=null,Pe=null,Re=null,Te=null,he=null,K=r=>{if(E("cleanup wipe="+r+" elapsed="+(Date.now()-W)+"ms"),Ue&&(clearTimeout(Ue),Ue=null),mt||(mt=true,gt([{type:"dwell",ms:Date.now()-W}])),ce&&clearInterval(ce),Pe&&clearInterval(Pe),Re&&clearInterval(Re),r){let s=Number(process.env.OPENCRATER_HOST_PID??0);s>1&&!H&&setTimeout(()=>{try{process.kill(s,"SIGWINCH");}catch{}},80);}if(Te){try{Te.close();}catch{}Te=null;}if(ce=null,Pe=null,Re=null,X){try{X.kill("SIGKILL");}catch{}X=null;}if(Z){try{re.rmSync(Z,{recursive:!0,force:!0});}catch{}Z=null;}if(xt(),Xn(),H){let s=false,f=()=>{s||(s=true,process.exit(0));};p.closeAndWait().then(f),setTimeout(f,1500).unref?.();return}p.close(),process.exit(0);},rn=()=>{ce&&clearInterval(ce);let s=T*O>1100?200:Et;ce=setInterval(le,z&&z.length>1?s:_e);},Me=()=>(Z||(Z=re.mkdtempSync(L__namespace.join(Tt.tmpdir(),"ocpaint-"))),Z),Je=async()=>{if(n.mediaPixelUrl&&(S==="image"||S==="logo"))try{let P=await fetch(n.mediaPixelUrl,{signal:AbortSignal.timeout(2500)});if(P.ok){let C=Wt(new Uint8Array(await P.arrayBuffer()));if(C&&C.width>=4&&C.height>=2){let q=Buffer.alloc(C.width*C.height*3);for(let Q=0,ee=0;Q<C.rgba.length;Q+=4,ee+=3)q[ee]=C.rgba[Q],q[ee+1]=C.rgba[Q+1],q[ee+2]=C.rgba[Q+2];T=Math.floor(C.width/2),O=Math.floor(C.height/2),z=[Yt(q,C.width,C.height,M)];return}}}catch{}if(!n.mediaUrl)return;let r=R==="video",s=await Ut(n.mediaUrl,r?Pn:Nt);if(!s||!(r?s.type.startsWith("video/"):s.type.startsWith("image/")))return;let l=L__namespace.join(Me(),"in");try{re.writeFileSync(l,s.data);}catch{return}let d=Vt(l),h=te("ffmpeg")?Jn(l):null,v=h?.match(/crop=(\d+):(\d+)/),G=v?Number(v[1]):d?.w??16,D=v?Number(v[2]):d?.h??9;if(x&&te("ffmpeg")&&G>0&&D>0){let P=Math.min(G,D),C=Math.floor((G-P)/2),q=Math.floor((D-P)/2);h=`crop=${P}:${P}:${C}:${q}`,G=P,D=P,v=null;}if(Qt(G,D),!r&&Ie==="iterm2"){ie=qt(s.data,{w:T,h:O}),ue=0;return}if(!r&&Ie==="kitty"&&s.type==="image/png"){ie=Fn(s.data,{w:T,h:O}),ue=0;return}if(r&&Ie==="iterm2"&&te("ffmpeg"))try{let P=L__namespace.join(Me(),"out.gif");if(child_process.spawnSync("ffmpeg",["-y","-i",l,"-t","6","-vf","fps=8,scale=280:-1:flags=lanczos","-loop","0",P],{timeout:12e3}).status===0){let q=re.readFileSync(P);if(q.length<=Nt){ie=qt(q,{w:T,h:O}),ue=0;return}}}catch{}if(te("ffmpeg"))try{let P=r||s.type==="image/gif",C=Hn(l,Me(),T,O,P,h)??Gn(l,T,O,P,M,h);C&&C.length>0&&(z=C,Oe=0,rn());}catch{}},Ye=(r=0)=>{if(!ae)return;let{kind:s,file:f,vol:l}=ae,d=Math.max(0,r/1e3),h,v;s==="afplay"?(h="afplay",v=["-v",l.toFixed(2),f]):s==="ffplay"?(h="ffplay",v=["-nodisp","-autoexit","-volume",String(Math.round(l*100))],d>.2&&v.push("-ss",d.toFixed(2)),v.push(f)):s==="mpv"?(h="mpv",v=["--no-video","--really-quiet",`--volume=${Math.round(l*100)}`],d>.2&&v.push(`--start=${d.toFixed(2)}`),v.push(f)):s==="paplay"?(h="paplay",v=[`--volume=${Math.round(l*65536)}`,f]):(h="mpg123",v=["-q","-f",String(Math.round(32768*l))],d>.2&&v.push("-k",String(Math.round(r/26.12))),v.push(f));try{X=H?child_process.spawn(h,v,{stdio:"ignore",detached:!0,windowsHide:!0}):child_process.spawn(h,v,{stdio:"ignore"}),J="playing",bt=Date.now(),X.on("exit",()=>{J!=="paused"&&(J="ended",ze=0);});}catch{J="none";}},on=()=>{try{J==="playing"&&X?(J="paused",ze+=Date.now()-bt,X.kill("SIGKILL"),X=null,gt([{type:"sound_muted"}])):J==="paused"?ae?.canSeek&&Ye(ze):J==="ended"&&Ye(0);}catch{}le();},be=async(r=n.mediaUrl)=>{if(!r||Xt)return;let s=L__namespace.join(Tt.homedir(),".config","opencrater","audio-plays.json");try{let l=[];try{l=JSON.parse(re.readFileSync(s,"utf8")),Array.isArray(l)||(l=[]);}catch{}let d=Rt(Date.now(),l);if(re.writeFileSync(s,JSON.stringify(d.next)),!d.play)return}catch{}let f=await Ut(r,Rn);if(!(!f||!f.type.startsWith("audio/")))try{let l=f.type.includes("wav")?"wav":f.type.includes("ogg")?"ogg":"mp3",d=L__namespace.join(Me(),`ad.${l}`);re.writeFileSync(d,f.data);let h=Pt(new Date().getHours());if(te("ffplay"))ae={kind:"ffplay",file:d,vol:h,canSeek:!0};else if(!H&&te("mpv"))ae={kind:"mpv",file:d,vol:h,canSeek:!0};else if(process.platform==="darwin"&&te("afplay"))ae={kind:"afplay",file:d,vol:h,canSeek:!1};else if(!H&&te("mpg123")&&l==="mp3")ae={kind:"mpg123",file:d,vol:h,canSeek:!0};else if(!H&&l!=="mp3"&&te("paplay"))ae={kind:"paplay",file:d,vol:h,canSeek:!1};else return;Ye(),setTimeout(()=>{try{X?.kill("SIGKILL");}catch{}(J==="playing"||J==="paused")&&(J="ended");},_t).unref?.();}catch{}},It=()=>{if(!n.impressionId||n.replay)return;let r=L__namespace.join(Tt.homedir(),".config","opencrater","dismiss.signal"),s=Date.now();Pe=setInterval(()=>{try{let f=re.readFileSync(r,"utf8"),l=JSON.parse(f),d=typeof l.at=="number"&&l.at>=s-5e3,h=!l.impressionId||l.impressionId===n.impressionId;if(d&&h){try{re.unlinkSync(r);}catch{}Ne(n.campaignId),fetch(`${se}/x/${n.impressionId}`,{signal:AbortSignal.timeout(1500)}).catch(()=>{}),K(!0);return}}catch{}(async()=>{try{let f=await fetch(`${se}/v1/events/dismissed/${n.impressionId}`,{signal:AbortSignal.timeout(1200)});if(!f.ok)return;(await f.json()).dismissed&&(Ne(n.campaignId),K(!0));}catch{}})();},On);},Ct=()=>{if(Ae)return;let r=L__namespace.join(Tt.homedir(),".config","opencrater","activity.signal"),s=Date.now(),f=1500;Re=setInterval(()=>{try{let l=re.statSync(r).mtimeMs;l>s+f&&l>Date.now()-St&&(vt=l+St,le());}catch{}},150);};if(H){(async()=>{let r=p.size?await p.size:null;if(r&&r.cols>=24&&(g=r.cols,b=Math.min(N,g-4),$=b-4,F=Math.max(1,g-b-1),E("windows geometry from pump:","cols",g,"width",b,"col",F,"ownerPid",r.pid)),R==="image"||R==="logo"||R==="gif"||R==="video"?await Je():R==="audio"&&await be(),n.audioUrl&&R!=="audio"&&be(n.audioUrl),i){let d=Math.min(Math.max(n.durationMs??lt,3e3),12e4);if(ge=Date.now()+d,a)try{re.unlinkSync(a);}catch{}Ft(p);let h=z,v=!!(h&&h.length>1);le(),ce=setInterval(le,v?Et:_e),Ct(),jt(),It(),process.on("SIGINT",()=>K(true)),process.on("SIGHUP",()=>K(true)),setTimeout(()=>K(true),d);return}let s=r?.pid??0;s>0&&Dn(n,s)&&(p.close(),process.exit(0)),E("no job-escape (ownerPid",s,") \u2014 bounded toast fallback");let f=Number(process.env.OPENCRATER_WIN_HOLD_MS),l=f>0?f:Math.min(n.durationMs??lt,5e3);if(ge=Date.now()+l,p.write(He()),await new Promise(d=>{let h=setInterval(()=>{if(Date.now()>=ge){clearInterval(h),d();return}p.write(He());},_e);}),xt(),Z)try{re.rmSync(Z,{recursive:!0,force:!0});}catch{}await p.closeAndWait(),process.exit(0);})();return}if(Ae){(async()=>{R==="image"||R==="logo"||R==="gif"||R==="video"?await Je():R==="audio"&&await be(),n.audioUrl&&R!=="audio"&&be(n.audioUrl);let r=z;r&&r.length>1&&(z=[r[0]]);let s=wt(),f=" ".repeat(Math.max(0,g-b-2)),l=`\r
6
6
  `;for(let h of s)l+=`${f}${h}\r
7
7
  `;ie&&O>0&&(l+=`${f}${ie}\r
8
8
  `),p.write(l);let d=X?_t+1e3:250;setTimeout(()=>{if(X)try{X.kill("SIGKILL");}catch{}if(Z)try{re.rmSync(Z,{recursive:!0,force:!0});}catch{}p.close(),process.exit(0);},d);})();return}le(),ce=setInterval(le,_e);function jt(){if(!(!n.impressionId&&!n.replay||Ae))try{let r=crypto.randomBytes(8).toString("hex"),s=zt__namespace.createServer((f,l)=>{if(!f.url||!f.url.includes(r)){l.writeHead(404).end();return}if(f.url.startsWith("/p/")){Mt(n.campaignId),n.impressionId?(l.writeHead(302,{location:`${se}/r/${n.impressionId}`}),l.end()):(l.writeHead(200,{"content-type":"text/html; charset=utf-8"}),l.end(`<!doctype html><meta charset=utf-8><title>Ad reported</title><body style="font-family:ui-monospace,monospace;background:#0c0c0a;color:#e9e6da;display:grid;place-items:center;height:100vh;margin:0"><p>\u2691 Reported \u2014 you won't see this Blip again. This tab closes itself.</p><script>setTimeout(function(){window.close()},600);</script>`)),setTimeout(()=>K(!0),150);return}if(f.url.startsWith("/a/")){on(),l.writeHead(200,{"content-type":"text/html; charset=utf-8"}),l.end('<!doctype html><meta charset=utf-8><title>Audio</title><body style="font-family:ui-monospace,monospace;background:#0c0c0a;color:#e9e6da;display:grid;place-items:center;height:100vh;margin:0"><p>\u266A toggled \u2014 this tab closes itself.</p><script>setTimeout(function(){window.close()},300);</script>');return}l.writeHead(200,{"content-type":"text/html; charset=utf-8"}),l.end('<!doctype html><meta charset=utf-8><title>Ad dismissed</title><body style="font-family:ui-monospace,monospace;background:#0c0c0a;color:#e9e6da;display:grid;place-items:center;height:100vh;margin:0"><p>\u2715 Ad dismissed \u2014 this tab closes itself.</p><script>setTimeout(function(){window.close()},400);</script>'),Ne(n.campaignId),!n.replay&&n.impressionId&&fetch(`${se}/x/${n.impressionId}`,{signal:AbortSignal.timeout(2e3)}).catch(()=>{}),setTimeout(()=>K(!0),150);});s.unref(),s.listen(0,"127.0.0.1",()=>{let f=s.address();f&&typeof f=="object"&&(he=`http://127.0.0.1:${f.port}/x/${r}`,Fe=`http://127.0.0.1:${f.port}/a/${r}`,Be=`http://127.0.0.1:${f.port}/p/${r}`,Te=s,le());}),s.on("error",()=>{he=null,Be=null;});}catch{}}try{re.writeFileSync(L__namespace.join(Tt.homedir(),".config","opencrater","last-ad.json"),JSON.stringify({payload:n,at:Date.now()}));}catch{}jt(),It(),Ct(),R==="image"||R==="logo"||R==="gif"||R==="video"?Je():R==="audio"&&be(),n.audioUrl&&R!=="audio"&&be(n.audioUrl);let Ve=n.durationMs??(R==="video"?18e3:R==="audio"?16e3:lt);ge=Date.now()+Ve,setTimeout(()=>K(true),Ve),process.on("SIGTERM",()=>K(true)),process.on("SIGINT",()=>K(true)),process.on("SIGHUP",()=>K(true)),setTimeout(()=>K(true),Ve+5e3).unref?.();}typeof tt<"u"&&typeof module<"u"&&tt.main===module&&Kn();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencrater",
3
- "version": "1.4.5",
3
+ "version": "1.4.7",
4
4
  "description": "OpenCrater — sponsor cards for AI coding terminals (Claude Code, Codex, Gemini CLI, Copilot CLI). One command, auto-wires every host, opt out anytime.",
5
5
  "keywords": [
6
6
  "opencrater",