opencrater 1.1.42 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  # opencrater
6
6
 
7
- **AdSense for the terminal.** Tasteful, opt-in sponsor cards for CLI tools, MCP servers, and AI agents — the rendering engine that powers [OpenCrater](https://opencrater.to).
7
+ **Blips for the terminal.** Tasteful, opt-in sponsor cards for CLI tools, MCP servers, and AI agents — the rendering engine that powers [OpenCrater](https://opencrater.to).
8
8
 
9
9
  [![npm](https://img.shields.io/npm/v/opencrater?color=2ea043&label=npm)](https://www.npmjs.com/package/opencrater)
10
10
  [![node](https://img.shields.io/badge/node-%E2%89%A518.17-2ea043)](https://nodejs.org)
package/dist/cli.js CHANGED
@@ -1,15 +1,15 @@
1
1
  #!/usr/bin/env node
2
- 'use strict';var crypto=require('crypto'),d=require('fs'),j=require('os'),u=require('path'),child_process=require('child_process'),pe=require('readline');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 d__namespace=/*#__PURE__*/_interopNamespace(d);var j__namespace=/*#__PURE__*/_interopNamespace(j);var u__namespace=/*#__PURE__*/_interopNamespace(u);var pe__namespace=/*#__PURE__*/_interopNamespace(pe);var G=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(o,n)=>(typeof require<"u"?require:o)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});function ge(e=process.env){return u__namespace.join(j__namespace.homedir(),".config","opencrater")}function E(e=process.env){return u__namespace.join(ge(e),"state.json")}function N(){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 k(e){return typeof e=="number"&&Number.isFinite(e)}var X=new Set(["EPERM","EACCES","EBUSY","EEXIST"]);function Q(e){for(let o=0;;o++)try{return {text:d__namespace.readFileSync(e,"utf8")}}catch(n){let t=n.code??"";if(!(t==="ENOENT"||X.has(t)))return {locked:true};if(o>=4)return t==="ENOENT"?{missing:true}:{locked:true};try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(o+1));}catch{}}}function he(e){if(typeof e!="object"||e===null)return null;let o=e;return !k(o.minIntervalSeconds)||!k(o.serveTimeoutMs)||!k(o.preloadPoolSize)||typeof o.killSwitch!="boolean"?null:{minIntervalSeconds:o.minIntervalSeconds,serveTimeoutMs:o.serveTimeoutMs,preloadPoolSize:o.preloadPoolSize,killSwitch:o.killSwitch,displayDurationSeconds:k(o.displayDurationSeconds)?o.displayDurationSeconds:25,minSdkVersion:typeof o.minSdkVersion=="string"?o.minSdkVersion:""}}function ke(e){if(!Array.isArray(e))return [];let o=[];for(let n of e){if(typeof n!="object"||n===null)continue;let t=n,r=t.blip;if(!k(t.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"||o.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:t.renderBy});}return o}function ye(e){if(typeof e!="object"||e===null||Array.isArray(e))return {};let o={};for(let[n,t]of Object.entries(e)){if(!Array.isArray(t))continue;let r=t.filter(i=>typeof i=="string"&&i.length<=64);o[n]=r.slice(0,64);}return o}function Se(e){if(!Array.isArray(e))return [];let o=[];for(let n of e){if(typeof n!="object"||n===null)continue;let t=n;if(!(typeof t.topic!="string"||!k(t.at))&&(o.push({topic:t.topic.slice(0,32),at:t.at}),o.length>=24))break}return o}function be(e){if(!Array.isArray(e))return [];let o=[],n=new Set;for(let t of e){if(typeof t!="object"||t===null)continue;let r=t;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),o.push({key:r.key,package:r.package}),o.length>=32))break}return o}function we(e){if(typeof e!="object"||e===null)return null;let o=e,n={};if(typeof o.savedEnv=="object"&&o.savedEnv!==null)for(let[t,r]of Object.entries(o.savedEnv))(typeof r=="string"||r===null)&&(n[t]=r);return {active:o.active===true,savedEnv:n}}function ve(e){if(typeof e!="object"||e===null)return null;let o=e,n=t=>k(t)&&t>=0?t:0;return {turns:n(o.turns),lastLimitAt:n(o.lastLimitAt),lastDepletedAt:n(o.lastDepletedAt),lastBackupAt:n(o.lastBackupAt)}}function Ce(e){let o=N();if(typeof e!="object"||e===null)return o;let n=e;return {installId:typeof n.installId=="string"&&n.installId.length>0?n.installId:o.installId,lastShownAt:k(n.lastShownAt)&&n.lastShownAt>=0?n.lastShownAt:0,optOut:n.optOut===true,disclosureShown:n.disclosureShown===true,cachedConfig:he(n.cachedConfig),allowedPlacements:ye(n.allowedPlacements),sessionTopics:Se(n.sessionTopics),integrations:be(n.integrations),devToken:typeof n.devToken=="string"?n.devToken:null,computeRouting:we(n.computeRouting),computeCards:ve(n.computeCards),configFetchedAt:k(n.configFetchedAt)&&n.configFetchedAt>=0?n.configFetchedAt:0,pool:ke(n.pool)}}function f(e=process.env){let o=E(e),n=Q(o);if(n.text!==void 0)try{return Ce(JSON.parse(n.text))}catch{let t=N();try{A(t,e);}catch{}return t}if(n.missing){let t=N();try{A(t,e);}catch{}return t}return N()}function A(e,o=process.env,n={}){let t=E(o),r=u__namespace.dirname(t);d__namespace.mkdirSync(r,{recursive:true});let i=Q(t),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 p=u__namespace.join(r,`.state.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`);d__namespace.writeFileSync(p,JSON.stringify(e,null,2)+`
3
- `,"utf8");for(let s=0;;s++)try{d__namespace.renameSync(p,t);return}catch(c){let l=c.code??"";if(s>=4||!X.has(l)){try{d__namespace.rmSync(p,{force:!0});}catch{}if(s>=4)return;throw c}try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(s+1));}catch{}}}function v(e,o=process.env){let n={...f(o),...e};return A(n,o),n}var Z={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:[],gemini_cli:["AfterAgent","SessionStart","SessionEnd","Notification","BeforeAgent","BeforeModel","AfterModel","BeforeToolSelection","BeforeTool","AfterTool","PreCompress"],copilot_cli:["agentStop","sessionStart","sessionEnd","notification","userPromptSubmitted","preToolUse","postToolUse","permissionRequest","errorOccurred","subagentStart","subagentStop"],grok_cli:["SessionStart","Stop","SessionEnd","Notification"],generic:["SessionStart","Stop"]};var b=["claude_code","codex","gemini_cli","copilot_cli","grok_cli"];function C(e){return e.includes("opencrater-hook")||/opencrater[\\/][^"']*hook\.js/.test(e)}function Oe(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Re(e,o){return C(e)&&new RegExp(`--package ['"]?${Oe(o)}['"]?`).test(e)}function re(e,o){return o?Re(e,o):C(e)&&!/--package\b/.test(e)}function ee(e){return /^[A-Za-z0-9@_./:-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}var ne='"$HOME/.config/opencrater/runtime/node_modules/opencrater/dist/hook.js"',oe="$env:USERPROFILE\\.config\\opencrater\\runtime\\node_modules\\opencrater\\dist\\hook.js";function P(e,o,n,t){let r=`--placement ${o}`;return n&&(r+=` --key ${ee(n)}`),t&&(r+=` --package ${ee(t)}`),r+=` --host ${e}`,`{ if [ -f ${ne} ]; then node ${ne} ${r}; else npx -y -p opencrater opencrater-hook ${r}; fi; } 2>/dev/null || true`}function Ae(e,o,n){if(process.platform!=="win32")return P("grok_cli",e,o,n);let t=`--placement ${e}`;o&&(t+=` --key ${o}`),n&&(t+=` --package ${n}`),t+=" --host grok_cli";let r=`${j__namespace.homedir()}\\.config\\opencrater\\runtime\\node_modules\\opencrater\\dist\\hook.js`;return `try { if (Test-Path "${r}") { node "${r}" ${t} } else { npx -y -p opencrater opencrater-hook ${t} } } catch {}`}function se(e,o,n,t){let r=`--placement ${o}`;return n&&(r+=` --key '${n}'`),t&&(r+=` --package '${t}'`),r+=` --host ${e}`,`try { if (Test-Path "${oe}") { node "${oe}" ${r} } else { npx -y -p opencrater opencrater-hook ${r} } } catch {}`}function Ee(e,o,n){if(process.platform!=="win32")return P("claude_code",e,o,n);let t=`--placement ${e}`;return o&&(t+=` --key ${o}`),n&&(t+=` --package ${n}`),t+=" --host claude_code",`node "${`${j__namespace.homedir()}\\.config\\opencrater\\runtime\\node_modules\\opencrater\\dist\\hook.js`}" ${t}; exit 0`}function J(e,o,n,t){if(e==="grok_cli")return {type:"command",command:Ae(o,n,t),timeout:15};let i={type:"command",command:e==="claude_code"?Ee(o,n,t):P(e,o,n,t)};return e==="codex"&&(i.commandWindows=se(e,o,n,t)),i}function K(e,o){let n=j__namespace.homedir();switch(e){case "claude_code":{let t=o.CLAUDE_CONFIG_DIR;return t&&t.trim()!==""?t:u__namespace.join(n,".claude")}case "codex":{let t=o.CODEX_HOME;return t&&t.trim()!==""?t:u__namespace.join(n,".codex")}case "gemini_cli":return u__namespace.join(n,".gemini");case "copilot_cli":{let t=o.COPILOT_HOME;return t&&t.trim()!==""?t:u__namespace.join(n,".copilot")}case "grok_cli":{let t=o.GROK_HOME;return t&&t.trim()!==""?t:u__namespace.join(n,".grok")}default:return u__namespace.join(n,".opencrater-unknown")}}function H(e,o=process.env){let n=K(e,o);switch(e){case "claude_code":return u__namespace.join(n,"settings.json");case "codex":return u__namespace.join(n,"hooks.json");case "gemini_cli":return u__namespace.join(n,"settings.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 Pe={claude_code:["claude"],codex:["codex"],gemini_cli:["gemini"],copilot_cli:["copilot"],grok_cli:["grok"]};function $e(e,o){if(e.length===0)return false;let n=(o.PATH??o.Path??"").split(u__namespace.delimiter).filter(Boolean),t=process.platform==="win32"?["",".exe",".cmd",".bat"]:[""];for(let r of n)for(let i of e)for(let a of t)try{if(d__namespace.existsSync(u__namespace.join(r,i+a)))return !0}catch{}return false}function xe(e,o=process.env){try{if(d__namespace.existsSync(K(e,o)))return !0}catch{}return $e(Pe[e]??[],o)}function z(e=process.env){return b.filter(o=>xe(o,e))}function M(e){let o;try{o=d__namespace.readFileSync(e,"utf8");}catch{return {}}let n=JSON.parse(o);if(typeof n!="object"||n===null||Array.isArray(n))throw new Error(`${e} is not a JSON object`);return n}function W(e,o){let n=u__namespace.dirname(e);d__namespace.mkdirSync(n,{recursive:true});let t=u__namespace.join(n,`.${u__namespace.basename(e)}.${process.pid}.tmp`);d__namespace.writeFileSync(t,JSON.stringify(o,null,2)+`
4
- `,"utf8"),d__namespace.renameSync(t,e);}function _e(e,o){return Array.isArray(e.hooks)&&e.hooks.some(n=>typeof n.command=="string"&&re(n.command,o))}function Ie(e,o,n,t){let r=H(e),i=M(r),a=i.hooks&&typeof i.hooks=="object"?i.hooks:{};if(t.every(s=>{let c=J(e,s,o,n);return (Array.isArray(a[s])?a[s]:[]).some(l=>Array.isArray(l.hooks)&&l.hooks.some(g=>g.command===c.command&&g.commandWindows===c.commandWindows))}))return "nochange";for(let s of t){let l=(Array.isArray(a[s])?a[s]:[]).filter(m=>!_e(m,n)),g=e==="grok_cli"?{hooks:[J(e,s,o,n)]}:{matcher:"",hooks:[J(e,s,o,n)]};l.push(g),a[s]=l;}return i.hooks=a,W(r,i),"wrote"}var te=12;function Te(e,o){return [e.bash,e.powershell,e.command].some(n=>typeof n=="string"&&re(n,o))}function Ne(e,o,n,t){let r=H(e),i=M(r);typeof i.version!="number"&&(i.version=1);let a=i.hooks&&typeof i.hooks=="object"?i.hooks:{};if(t.every(s=>{let c=P(e,s,o,n);return (Array.isArray(a[s])?a[s]:[]).some(l=>l.bash===c&&l.timeoutSec===te)}))return "nochange";for(let s of t){let l=(Array.isArray(a[s])?a[s]:[]).filter(g=>!Te(g,n));l.push({type:"command",bash:P(e,s,o,n),powershell:se(e,s,o,n),timeoutSec:te}),a[s]=l;}return i.hooks=a,W(r,i),"wrote"}function U(e){return [...Z[e]]}function je(e){let o=e;for(let n of ["claude","cursor"]){if(new RegExp(`^\\s*\\[compat\\.${n}\\]`,"m").test(o))continue;let t=o.length===0?"":o.endsWith(`
2
+ 'use strict';var crypto=require('crypto'),p=require('fs'),N=require('os'),f=require('path'),child_process=require('child_process'),pe=require('readline');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 p__namespace=/*#__PURE__*/_interopNamespace(p);var N__namespace=/*#__PURE__*/_interopNamespace(N);var f__namespace=/*#__PURE__*/_interopNamespace(f);var pe__namespace=/*#__PURE__*/_interopNamespace(pe);var D=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(o,n)=>(typeof require<"u"?require:o)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var X=360*60*1e3;function ke(e=process.env){return f__namespace.join(N__namespace.homedir(),".config","opencrater")}function A(e=process.env){return f__namespace.join(ke(e),"state.json")}function I(){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 h(e){return typeof e=="number"&&Number.isFinite(e)}var Z=new Set(["EPERM","EACCES","EBUSY","EEXIST"]);function ee(e){for(let o=0;;o++)try{return {text:p__namespace.readFileSync(e,"utf8")}}catch(n){let t=n.code??"";if(!(t==="ENOENT"||Z.has(t)))return {locked:true};if(o>=4)return t==="ENOENT"?{missing:true}:{locked:true};try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(o+1));}catch{}}}function we(e){if(typeof e!="object"||e===null)return null;let o=e;return !h(o.minIntervalSeconds)||!h(o.serveTimeoutMs)||!h(o.preloadPoolSize)||typeof o.killSwitch!="boolean"?null:{minIntervalSeconds:o.minIntervalSeconds,serveTimeoutMs:o.serveTimeoutMs,preloadPoolSize:o.preloadPoolSize,killSwitch:o.killSwitch,displayDurationSeconds:h(o.displayDurationSeconds)?o.displayDurationSeconds:25,minSdkVersion:typeof o.minSdkVersion=="string"?o.minSdkVersion:""}}function be(e){if(!Array.isArray(e))return [];let o=[];for(let n of e){if(typeof n!="object"||n===null)continue;let t=n,i=t.blip;if(!h(t.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"||o.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:t.renderBy});}return o}function ve(e){if(typeof e!="object"||e===null||Array.isArray(e))return {};let o={};for(let[n,t]of Object.entries(e)){if(!Array.isArray(t))continue;let i=t.filter(r=>typeof r=="string"&&r.length<=64);o[n]=i.slice(0,64);}return o}function Se(e){if(!Array.isArray(e))return [];let o=[];for(let n of e){if(typeof n!="object"||n===null)continue;let t=n;if(!(typeof t.topic!="string"||!h(t.at))&&(o.push({topic:t.topic.slice(0,32),at:t.at}),o.length>=24))break}return o}function je(e){if(!Array.isArray(e))return [];let o=[],n=new Set;for(let t of e){if(typeof t!="object"||t===null)continue;let i=t;if(typeof i.key!="string"||typeof i.package!="string"||i.key===""||i.package==="")continue;let r=`${i.package}\0${i.key}`;if(!n.has(r)&&(n.add(r),o.push({key:i.key,package:i.package}),o.length>=32))break}return o}function xe(e){if(typeof e!="object"||e===null)return null;let o=e,n={};if(typeof o.savedEnv=="object"&&o.savedEnv!==null)for(let[t,i]of Object.entries(o.savedEnv))(typeof i=="string"||i===null)&&(n[t]=i);return {active:o.active===true,savedEnv:n}}function Ce(e){if(typeof e!="object"||e===null)return null;let o=e,n=t=>h(t)&&t>=0?t:0;return {turns:n(o.turns),lastLimitAt:n(o.lastLimitAt),lastDepletedAt:n(o.lastDepletedAt),lastBackupAt:n(o.lastBackupAt)}}function Oe(e){let o=e.attrTagsAt,n=e.attrTagsCwd;return !h(o)||Date.now()-o>X||typeof n!="string"||n.length===0||n.length>64?{}:{attrTags:Array.isArray(e.attrTags)?e.attrTags.filter(i=>typeof i=="string"&&i.length<=40).slice(0,48):[],attrTagsCwd:n,attrTagsAt:o}}function Ae(e){let o=I();if(typeof e!="object"||e===null)return o;let n=e;return {installId:typeof n.installId=="string"&&n.installId.length>0?n.installId:o.installId,lastShownAt:h(n.lastShownAt)&&n.lastShownAt>=0?n.lastShownAt:0,optOut:n.optOut===true,disclosureShown:n.disclosureShown===true,cachedConfig:we(n.cachedConfig),allowedPlacements:ve(n.allowedPlacements),sessionTopics:Se(n.sessionTopics),integrations:je(n.integrations),devToken:typeof n.devToken=="string"?n.devToken:null,computeRouting:xe(n.computeRouting),computeCards:Ce(n.computeCards),configFetchedAt:h(n.configFetchedAt)&&n.configFetchedAt>=0?n.configFetchedAt:0,pool:be(n.pool),...Oe(n)}}function m(e=process.env){let o=A(e),n=ee(o);if(n.text!==void 0)try{return Ae(JSON.parse(n.text))}catch{let t=I();try{O(t,e);}catch{}return t}if(n.missing){let t=I();try{O(t,e);}catch{}return t}return I()}function O(e,o=process.env,n={}){let t=A(o),i=f__namespace.dirname(t);p__namespace.mkdirSync(i,{recursive:true});let r=ee(t),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}),!n.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(!n.allowClearToken&&e.devToken==null&&r.text===void 0&&!r.missing)return;let d=f__namespace.join(i,`.state.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`);p__namespace.writeFileSync(d,JSON.stringify(e,null,2)+`
3
+ `,"utf8");for(let a=0;;a++)try{p__namespace.renameSync(d,t);return}catch(c){let l=c.code??"";if(a>=4||!Z.has(l)){try{p__namespace.rmSync(d,{force:!0});}catch{}if(a>=4)return;throw c}try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(a+1));}catch{}}}function S(e,o=process.env){let n={...m(o),...e};return O(n,o),n}var ne={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:["AfterAgent","SessionStart","SessionEnd","Notification","BeforeAgent","BeforeModel","AfterModel","BeforeToolSelection","BeforeTool","AfterTool","PreCompress"],copilot_cli:["agentStop","sessionStart","sessionEnd","notification","userPromptSubmitted","preToolUse","postToolUse","permissionRequest","errorOccurred","subagentStart","subagentStop"],grok_cli:["SessionStart","Stop","SessionEnd","Notification"],generic:["SessionStart","Stop"]};var b=["claude_code","codex","antigravity","copilot_cli","grok_cli"];function j(e){return e.includes("opencrater-hook")||/opencrater[\\/][^"']*hook\.js/.test(e)}function Re(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Pe(e,o){return j(e)&&new RegExp(`--package ['"]?${Re(o)}['"]?`).test(e)}function se(e,o){return o?Pe(e,o):j(e)&&!/--package\b/.test(e)}function oe(e){return /^[A-Za-z0-9@_./:-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}var te='"$HOME/.config/opencrater/runtime/node_modules/opencrater/dist/hook.js"',ie="$env:USERPROFILE\\.config\\opencrater\\runtime\\node_modules\\opencrater\\dist\\hook.js";function R(e,o,n,t){let i=`--placement ${o}`;return n&&(i+=` --key ${oe(n)}`),t&&(i+=` --package ${oe(t)}`),i+=` --host ${e}`,`{ if [ -f ${te} ]; then node ${te} ${i}; else npx -y -p opencrater opencrater-hook ${i}; fi; } 2>/dev/null || true`}function Ee(e,o,n){if(process.platform!=="win32")return R("grok_cli",e,o,n);let t=`--placement ${e}`;o&&(t+=` --key ${o}`),n&&(t+=` --package ${n}`),t+=" --host grok_cli";let i=`${N__namespace.homedir()}\\.config\\opencrater\\runtime\\node_modules\\opencrater\\dist\\hook.js`;return `try { if (Test-Path "${i}") { node "${i}" ${t} } else { npx -y -p opencrater opencrater-hook ${t} } } catch {}`}function ae(e,o,n,t){let i=`--placement ${o}`;return n&&(i+=` --key '${n}'`),t&&(i+=` --package '${t}'`),i+=` --host ${e}`,`try { if (Test-Path "${ie}") { node "${ie}" ${i} } else { npx -y -p opencrater opencrater-hook ${i} } } catch {}`}function Te(e,o,n){if(process.platform!=="win32")return R("claude_code",e,o,n);let t=`--placement ${e}`;return o&&(t+=` --key ${o}`),n&&(t+=` --package ${n}`),t+=" --host claude_code",`node "${`${N__namespace.homedir()}\\.config\\opencrater\\runtime\\node_modules\\opencrater\\dist\\hook.js`}" ${t}; exit 0`}function G(e,o,n,t){if(e==="grok_cli")return {type:"command",command:Ee(o,n,t),timeout:15};let r={type:"command",command:e==="claude_code"?Te(o,n,t):R(e,o,n,t)};return e==="codex"&&(r.commandWindows=ae(e,o,n,t)),r}function J(e,o){let n=N__namespace.homedir();switch(e){case "claude_code":{let t=o.CLAUDE_CONFIG_DIR;return t&&t.trim()!==""?t:f__namespace.join(n,".claude")}case "codex":{let t=o.CODEX_HOME;return t&&t.trim()!==""?t:f__namespace.join(n,".codex")}case "antigravity":return f__namespace.join(n,".gemini");case "copilot_cli":{let t=o.COPILOT_HOME;return t&&t.trim()!==""?t:f__namespace.join(n,".copilot")}case "grok_cli":{let t=o.GROK_HOME;return t&&t.trim()!==""?t:f__namespace.join(n,".grok")}default:return f__namespace.join(n,".opencrater-unknown")}}function M(e,o=process.env){let n=J(e,o);switch(e){case "claude_code":return f__namespace.join(n,"settings.json");case "codex":return f__namespace.join(n,"hooks.json");case "antigravity":return f__namespace.join(n,"settings.json");case "copilot_cli":return f__namespace.join(n,"hooks","hooks.json");case "grok_cli":return f__namespace.join(n,"hooks","opencrater.json");default:return f__namespace.join(n,"hooks.json")}}var $e={claude_code:["claude"],codex:["codex"],antigravity:["agy"],copilot_cli:["copilot"],grok_cli:["grok"]};function We(e,o){if(e.length===0)return false;let n=(o.PATH??o.Path??"").split(f__namespace.delimiter).filter(Boolean),t=process.platform==="win32"?["",".exe",".cmd",".bat"]:[""];for(let i of n)for(let r of e)for(let s of t)try{if(p__namespace.existsSync(f__namespace.join(i,r+s)))return !0}catch{}return false}function _e(e,o=process.env){try{if(p__namespace.existsSync(J(e,o)))return !0}catch{}return We($e[e]??[],o)}function K(e=process.env){return b.filter(o=>_e(o,e))}function H(e){let o;try{o=p__namespace.readFileSync(e,"utf8");}catch{return {}}let n=JSON.parse(o);if(typeof n!="object"||n===null||Array.isArray(n))throw new Error(`${e} is not a JSON object`);return n}function V(e,o){let n=f__namespace.dirname(e);p__namespace.mkdirSync(n,{recursive:true});let t=f__namespace.join(n,`.${f__namespace.basename(e)}.${process.pid}.tmp`);p__namespace.writeFileSync(t,JSON.stringify(o,null,2)+`
4
+ `,"utf8"),p__namespace.renameSync(t,e);}function Ie(e,o){return Array.isArray(e.hooks)&&e.hooks.some(n=>typeof n.command=="string"&&se(n.command,o))}function Ne(e,o,n,t){let i=M(e),r=H(i),s=r.hooks&&typeof r.hooks=="object"?r.hooks:{};if(!(e==="antigravity"&&r["json-hooks-enabled"]!==true)&&t.every(c=>{let l=G(e,c,o,n);return (Array.isArray(s[c])?s[c]:[]).some(g=>Array.isArray(g.hooks)&&g.hooks.some(u=>u.command===l.command&&u.commandWindows===l.commandWindows))}))return "nochange";for(let c of t){let g=(Array.isArray(s[c])?s[c]:[]).filter(_=>!Ie(_,n)),u=e==="grok_cli"?{hooks:[G(e,c,o,n)]}:{matcher:"",hooks:[G(e,c,o,n)]};g.push(u),s[c]=g;}return e==="antigravity"&&(r["json-hooks-enabled"]=true),r.hooks=s,V(i,r),"wrote"}var re=12;function Me(e,o){return [e.bash,e.powershell,e.command].some(n=>typeof n=="string"&&se(n,o))}function He(e,o,n,t){let i=M(e),r=H(i);typeof r.version!="number"&&(r.version=1);let s=r.hooks&&typeof r.hooks=="object"?r.hooks:{};if(t.every(a=>{let c=R(e,a,o,n);return (Array.isArray(s[a])?s[a]:[]).some(l=>l.bash===c&&l.timeoutSec===re)}))return "nochange";for(let a of t){let l=(Array.isArray(s[a])?s[a]:[]).filter(g=>!Me(g,n));l.push({type:"command",bash:R(e,a,o,n),powershell:ae(e,a,o,n),timeoutSec:re}),s[a]=l;}return r.hooks=s,V(i,r),"wrote"}function q(e){return [...ne[e]]}function qe(e){let o=e;for(let n of ["claude","cursor"]){if(new RegExp(`^\\s*\\[compat\\.${n}\\]`,"m").test(o))continue;let t=o.length===0?"":o.endsWith(`
5
5
  `)?`
6
6
  `:`
7
7
 
8
8
  `;o+=`${t}[compat.${n}]
9
9
  hooks = false
10
- `;}return o}function He(e){try{let o=u__namespace.join(K("grok_cli",e),"config.toml"),n="";try{n=d__namespace.readFileSync(o,"utf8");}catch{}let t=je(n);if(t===n)return;d__namespace.mkdirSync(u__namespace.dirname(o),{recursive:!0}),d__namespace.writeFileSync(o,t,"utf8");}catch{}}function F(e,o,n){let t=U(e);return t.length===0?"nochange":(e==="grok_cli"&&He(process.env),e==="copilot_cli"?Ne(e,o,n,t):Ie(e,o,n,t))}function $(e,o,n=process.env){return z(n).map(t=>{try{let r=F(t,e,o);return {host:t,status:r,events:U(t)}}catch(r){return {host:t,status:"error",events:[],error:r.message}}})}function V(e=process.env){let o=[];for(let n of b){let t;try{t=M(H(n,e));}catch{continue}let r=t.hooks;if(!(!r||typeof r!="object"))for(let[i,a]of Object.entries(r))for(let p of Array.isArray(a)?a:[]){let s=p,c=Array.isArray(s.hooks)?s.hooks.find(m=>typeof m.command=="string"&&C(m.command))?.command:void 0,l=[s.bash,s.command,s.powershell].find(m=>typeof m=="string"&&C(m)),g=c??l;g&&o.push({host:n,event:i,command:g});}}return o}function ie(e=process.env){let o=0;for(let n of b){let t=H(n,e),r;try{r=M(t);}catch{continue}let i=r.hooks;if(!i||typeof i!="object")continue;let a=i,p=false;for(let s of Object.keys(a)){let c=Array.isArray(a[s])?a[s]:[],l=c.filter(g=>{let m=g,q=Array.isArray(m.hooks)&&m.hooks.some(R=>typeof R.command=="string"&&C(R.command))||[m.bash,m.powershell,m.command].some(R=>typeof R=="string"&&C(R));return q&&o++,!q});l.length!==c.length&&(p=true,l.length>0?a[s]=l:delete a[s]);}if(p)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?d__namespace.rmSync(t,{force:!0}):W(t,r);}catch{}}return o}var x="1.1.42";var Me="https://api.opencrater.to";function O(e,o=process.env){let n=o.OPENCRATER_API_ORIGIN;return (e??(n&&n.trim()!==""?n:Me)).replace(/\/+$/,"")}function Fe(){return u__namespace.join(j__namespace.homedir(),".config","opencrater","runtime")}function Be(e){return ["install","--prefix",e,"opencrater@latest","--silent","--no-audit","--no-fund"]}function B(e=Fe()){if(process.env.VITEST||process.env.OPENCRATER_DISABLE_RUNTIME_PIN)return false;try{return child_process.spawnSync("npm",Be(e),{stdio:"ignore",windowsHide:!0,shell:process.platform==="win32"}).status===0}catch{return false}}function De(){let e=process.env.OPENCRATER_WEB_ORIGIN;return e&&e.trim()!==""?e.replace(/\/$/,""):O().replace("//api.","//").replace(/\/$/,"")}function Le(e){try{let o=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";child_process.spawn(o,[e],{stdio:"ignore",detached:!0,shell:process.platform==="win32"}).unref();}catch{}}function Ge(e){let o=pe__namespace.createInterface({input:process.stdin,output:process.stdout});return new Promise(n=>o.question(e,t=>(o.close(),n(t))))}function _(e){return `${Math.round(e/1e3).toLocaleString()} tokens`}function Je(e){let o=e/1e3;return o>0&&o<10?`${(Math.round(o*10)/10).toFixed(1)} tokens`:`${Math.round(o).toLocaleString()} tokens`}function I(e){let o=e?.pendingMicroUsd??0;return o>0?` \xB7 +${Je(o)} pending`:""}async function T(e,o){try{let n=new URL(`${O()}/v1/dev/me`);o&&n.searchParams.set("installId",o);let t=await fetch(n,{headers:{authorization:`Bearer ${e}`}});return t.ok?await t.json():null}catch{return null}}async function Ke(){let e=`${De()}/dev/link`;console.log("Sign in and generate a CLI token here (we tried to open it):"),console.log(` ${e}
11
- `),Le(e);let o=(await Ge("Paste your token (ocd_\u2026): ")).trim();if(!o.startsWith("ocd_"))return console.error("That doesn't look like a token (should start with ocd_)."),1;let n=await T(o,f().installId);if(!n)return console.error("Couldn't verify that token \u2014 check it and try again."),1;v({devToken:o}),console.log(`
12
- \u2713 Signed in as ${n.displayName}.`),console.log(` Compute balance: ${_(n.balanceMicroUsd)}${I(n)} \xB7 tier: ${n.trustTier}`);let t=$().filter(r=>r.status!=="error").map(r=>r.host);return t.length?(console.log(` Wired into: ${t.join(", ")}`),process.stdout.write(" Pinning fast runtime (one-time, ~15s)\u2026 "),console.log(B()?"\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 ze(){let e=f().devToken;if(!e)return console.error("Not signed in. Run: opencrater login"),1;let o=await T(e,f().installId);return o?(console.log(`Compute balance: ${_(o.balanceMicroUsd)}${I(o)}`),console.log(` signed in as: ${o.displayName} \xB7 tier: ${o.trustTier}`),0):(console.error("Couldn't reach OpenCrater (or your session expired \u2014 try: opencrater login)."),1)}function We(){return A({...f(),devToken:null},process.env,{allowClearToken:true}),console.log("Signed out of the OpenCrater compute wallet on this machine."),0}async function Ve(e){let o=f().devToken;if(!o)return console.error("Not signed in. Run: opencrater login"),1;let n=await T(o,f().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 t=`${O().replace(/\/$/,"")}/gateway`,r=u__namespace.join(u__namespace.dirname(E()),"claude-gateway.settings.json");try{d__namespace.mkdirSync(u__namespace.dirname(r),{recursive:!0}),d__namespace.writeFileSync(r,JSON.stringify({apiKeyHelper:`echo ${o}`}),{mode:384});}catch(p){return console.error(`Couldn't write gateway settings: ${p.message}`),1}n&&console.log(`Launching Claude Code on OpenCrater compute \xB7 balance ${_(n.balanceMicroUsd)}${I(n)}`);let i={...process.env,ANTHROPIC_BASE_URL:t,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(p=>{a.on("exit",s=>p(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"),p(127);});})}async function qe(e){let o=f().devToken;if(!o)return console.error("Not signed in. Run: opencrater login"),1;let n=await T(o,f().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 t=`${O().replace(/\/$/,"")}/gateway/v1`;n&&console.log(`Launching Codex on OpenCrater compute \xB7 balance ${_(n.balanceMicroUsd)}${I(n)}`);let r={...process.env,OPENCRATER_TOKEN:o,OPENCRATER_ON_GATEWAY:"1"},i=["-c",'model_provider="opencrater"',"-c",'model_providers.opencrater.name="OpenCrater"',"-c",`model_providers.opencrater.base_url="${t}"`,"-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 p=child_process.spawn("codex",[...i,...a],{stdio:"inherit",env:r,shell:process.platform==="win32"});return await new Promise(s=>{p.on("exit",c=>s(c??0)),p.on("error",c=>{console.error(`Couldn't launch codex: ${c.message}`),console.error("Is Codex installed? npm i -g @openai/codex"),s(127);});})}function Ye(){let e=process.env.GROK_HOME;return e&&e.trim()!==""?e:u__namespace.join(j__namespace.homedir(),".grok")}function Xe(e){let o=u__namespace.join(Ye(),"config.toml"),n="";try{n=d__namespace.readFileSync(o,"utf8");}catch{}if(/^\s*\[model\.opencrater\]/m.test(n))return;let t=n.length===0?"":n.endsWith(`
10
+ `;}return o}function Le(e){try{let o=f__namespace.join(J("grok_cli",e),"config.toml"),n="";try{n=p__namespace.readFileSync(o,"utf8");}catch{}let t=qe(n);if(t===n)return;p__namespace.mkdirSync(f__namespace.dirname(o),{recursive:!0}),p__namespace.writeFileSync(o,t,"utf8");}catch{}}function L(e,o,n){let t=q(e);return t.length===0?"nochange":(e==="grok_cli"&&Le(process.env),e==="copilot_cli"?He(e,o,n,t):Ne(e,o,n,t))}function P(e,o,n=process.env){return K(n).map(t=>{try{let i=L(t,e,o);return {host:t,status:i,events:q(t)}}catch(i){return {host:t,status:"error",events:[],error:i.message}}})}function Y(e=process.env){let o=[];for(let n of b){let t;try{t=H(M(n,e));}catch{continue}let i=t.hooks;if(!(!i||typeof i!="object"))for(let[r,s]of Object.entries(i))for(let d of Array.isArray(s)?s:[]){let a=d,c=Array.isArray(a.hooks)?a.hooks.find(u=>typeof u.command=="string"&&j(u.command))?.command:void 0,l=[a.bash,a.command,a.powershell].find(u=>typeof u=="string"&&j(u)),g=c??l;g&&o.push({host:n,event:r,command:g});}}return o}function ce(e=process.env){let o=0;for(let n of b){let t=M(n,e),i;try{i=H(t);}catch{continue}let r=i.hooks;if(!r||typeof r!="object")continue;let s=r,d=false;for(let a of Object.keys(s)){let c=Array.isArray(s[a])?s[a]:[],l=c.filter(g=>{let u=g,_=Array.isArray(u.hooks)&&u.hooks.some(C=>typeof C.command=="string"&&j(C.command))||[u.bash,u.powershell,u.command].some(C=>typeof C=="string"&&j(C));return _&&o++,!_});l.length!==c.length&&(d=true,l.length>0?s[a]=l:delete s[a]);}if(d)try{let a=Object.keys(i).filter(l=>l!=="version"&&l!=="hooks"),c=n==="copilot_cli"||n==="codex";Object.keys(s).length===0&&a.length===0&&c?p__namespace.rmSync(t,{force:!0}):V(t,i);}catch{}}return o}var E="1.3.0";var Be="https://api.opencrater.to";function x(e,o=process.env){let n=o.OPENCRATER_API_ORIGIN;return (e??(n&&n.trim()!==""?n:Be)).replace(/\/+$/,"")}function Fe(){return f__namespace.join(N__namespace.homedir(),".config","opencrater","runtime")}function De(e){return ["install","--prefix",e,"opencrater@latest","--silent","--no-audit","--no-fund"]}function B(e=Fe()){if(process.env.VITEST||process.env.OPENCRATER_DISABLE_RUNTIME_PIN)return false;try{return child_process.spawnSync("npm",De(e),{stdio:"ignore",windowsHide:!0,shell:process.platform==="win32"}).status===0}catch{return false}}function ze(){let e=process.env.OPENCRATER_WEB_ORIGIN;return e&&e.trim()!==""?e.replace(/\/$/,""):x().replace("//api.","//").replace(/\/$/,"")}function Ge(e){try{let o=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";child_process.spawn(o,[e],{stdio:"ignore",detached:!0,shell:process.platform==="win32"}).unref();}catch{}}function Je(e){let o=pe__namespace.createInterface({input:process.stdin,output:process.stdout});return new Promise(n=>o.question(e,t=>(o.close(),n(t))))}function T(e){return `${Math.round(e/1e3).toLocaleString()} tokens`}function Ke(e){let o=e/1e3;return o>0&&o<10?`${(Math.round(o*10)/10).toFixed(1)} tokens`:`${Math.round(o).toLocaleString()} tokens`}function $(e){let o=e?.pendingMicroUsd??0;return o>0?` \xB7 +${Ke(o)} pending`:""}async function W(e,o){try{let n=new URL(`${x()}/v1/dev/me`);o&&n.searchParams.set("installId",o);let t=await fetch(n,{headers:{authorization:`Bearer ${e}`}});return t.ok?await t.json():null}catch{return null}}async function Ve(){let e=`${ze()}/dev/link`;console.log("Sign in and generate a CLI token here (we tried to open it):"),console.log(` ${e}
11
+ `),Ge(e);let o=(await Je("Paste your token (ocd_\u2026): ")).trim();if(!o.startsWith("ocd_"))return console.error("That doesn't look like a token (should start with ocd_)."),1;let n=await W(o,m().installId);if(!n)return console.error("Couldn't verify that token \u2014 check it and try again."),1;S({devToken:o}),console.log(`
12
+ \u2713 Signed in as ${n.displayName}.`),console.log(` Compute balance: ${T(n.balanceMicroUsd)}${$(n)} \xB7 tier: ${n.trustTier}`);let t=P().filter(i=>i.status!=="error").map(i=>i.host);return t.length?(console.log(` Wired into: ${t.join(", ")}`),process.stdout.write(" Pinning fast runtime (one-time, ~15s)\u2026 "),console.log(B()?"\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 Ye(){let e=m().devToken;if(!e)return console.error("Not signed in. Run: opencrater login"),1;let o=await W(e,m().installId);return o?(console.log(`Compute balance: ${T(o.balanceMicroUsd)}${$(o)}`),console.log(` signed in as: ${o.displayName} \xB7 tier: ${o.trustTier}`),0):(console.error("Couldn't reach OpenCrater (or your session expired \u2014 try: opencrater login)."),1)}function Xe(){return O({...m(),devToken:null},process.env,{allowClearToken:true}),console.log("Signed out of the OpenCrater compute wallet on this machine."),0}async function Qe(e){let o=m().devToken;if(!o)return console.error("Not signed in. Run: opencrater login"),1;let n=await W(o,m().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 t=`${x().replace(/\/$/,"")}/gateway`,i=f__namespace.join(f__namespace.dirname(A()),"claude-gateway.settings.json");try{p__namespace.mkdirSync(f__namespace.dirname(i),{recursive:!0}),p__namespace.writeFileSync(i,JSON.stringify({apiKeyHelper:`echo ${o}`}),{mode:384});}catch(d){return console.error(`Couldn't write gateway settings: ${d.message}`),1}n&&console.log(`Launching Claude Code on OpenCrater compute \xB7 balance ${T(n.balanceMicroUsd)}${$(n)}`);let r={...process.env,ANTHROPIC_BASE_URL:t,OPENCRATER_ON_GATEWAY:"1"};delete r.ANTHROPIC_API_KEY;let s=child_process.spawn("claude",[...e,"--settings",i],{stdio:"inherit",env:r,shell:process.platform==="win32"});return await new Promise(d=>{s.on("exit",a=>d(a??0)),s.on("error",a=>{console.error(`Couldn't launch claude: ${a.message}`),console.error("Is Claude Code installed? https://claude.com/claude-code"),d(127);});})}async function Ze(e){let o=m().devToken;if(!o)return console.error("Not signed in. Run: opencrater login"),1;let n=await W(o,m().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 t=`${x().replace(/\/$/,"")}/gateway/v1`;n&&console.log(`Launching Codex on OpenCrater compute \xB7 balance ${T(n.balanceMicroUsd)}${$(n)}`);let i={...process.env,OPENCRATER_TOKEN:o,OPENCRATER_ON_GATEWAY:"1"},r=["-c",'model_provider="opencrater"',"-c",'model_providers.opencrater.name="OpenCrater"',"-c",`model_providers.opencrater.base_url="${t}"`,"-c",'model_providers.opencrater.wire_api="responses"',"-c",'model_providers.opencrater.env_key="OPENCRATER_TOKEN"'],s=[];for(let a=0;a<e.length;a++){let c=e[a],l=e[a+1];c==="-c"&&(l===void 0||!l.includes("="))?s.push("resume","--last"):s.push(c);}let d=child_process.spawn("codex",[...r,...s],{stdio:"inherit",env:i,shell:process.platform==="win32"});return await new Promise(a=>{d.on("exit",c=>a(c??0)),d.on("error",c=>{console.error(`Couldn't launch codex: ${c.message}`),console.error("Is Codex installed? npm i -g @openai/codex"),a(127);});})}function en(){let e=process.env.GROK_HOME;return e&&e.trim()!==""?e:f__namespace.join(N__namespace.homedir(),".grok")}function nn(e){let o=f__namespace.join(en(),"config.toml"),n="";try{n=p__namespace.readFileSync(o,"utf8");}catch{}if(/^\s*\[model\.opencrater\]/m.test(n))return;let t=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
- `,d__namespace.mkdirSync(u__namespace.dirname(o),{recursive:true}),d__namespace.writeFileSync(o,n,"utf8");}async function Qe(e){let o=f().devToken;if(!o)return console.error("Not signed in. Run: opencrater login"),1;let n=await T(o,f().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 t=`${O().replace(/\/$/,"")}/gateway/v1`;n&&console.log(`Launching Grok on OpenCrater compute \xB7 balance ${_(n.balanceMicroUsd)}${I(n)}`);try{F("grok_cli");}catch{}try{Xe(t);}catch(s){return console.error(`Couldn't configure the Grok compute model: ${s.message}`),1}let r={...process.env,OPENCRATER_TOKEN:o,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"],p=child_process.spawn("grok",[...a,...e],{stdio:"inherit",env:r,shell:process.platform==="win32"});return await new Promise(s=>{p.on("exit",c=>s(c??0)),p.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 de(e){let o=new Map,n=[];for(let t=0;t<e.length;t++){let r=e[t];if(r!==void 0)if(r.startsWith("--")){let i=r.indexOf("=");if(i!==-1)o.set(r.slice(2,i),r.slice(i+1));else {let a=e[t+1];a!==void 0&&!a.startsWith("--")?(o.set(r.slice(2),a),t++):o.set(r.slice(2),"true");}}else n.push(r);}return {flags:o,rest:n}}function fe(e,o){let n=f();n.integrations.some(t=>t.key===e&&t.package===o)||v({integrations:[...n.integrations,{key:e,package:o}].slice(-32)});}function D(e,o){let n=o||"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 t of e)if(t.status==="error")console.log(` \u2717 ${t.host}: ${t.error}`);else {let r=t.status==="nochange"?" \u2014 already set up":"";console.log(` \u2022 ${t.host} (${t.events.join(", ")})${r}`);}}function Ze(){return v({optOut:true}),console.log("OpenCrater Blips are now OFF for this machine."),console.log("Re-enable any time with: npx opencrater on"),0}function en(e){let{flags:o}=de(e),n=o.get("key"),t=o.get("package");return v({optOut:false}),n&&t?(fe(n,t),D($(n,t),t),process.stdout.write("Pinning fast runtime (one-time, ~15s)\u2026 "),console.log(B()?"\u2713":"skipped (npm unavailable \u2014 hooks use npx fallback)")):f().devToken?(D($()),process.stdout.write("Pinning fast runtime (one-time, ~15s)\u2026 "),console.log(B()?"\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 nn(){let e=f(),o=e.lastShownAt>0?new Date(e.lastShownAt).toISOString():"never";console.log(`opencrater v${x}`),console.log(` state file: ${E()}`),console.log(` install id: ${e.installId}`),console.log(` opted out: ${e.optOut?"yes":"no"}`),console.log(` last shown: ${o}`),console.log(` pooled Blips: ${e.pool.length}`),console.log(` hosts found: ${z().join(", ")||"(none)"}`),console.log(` integrations: ${e.integrations.map(t=>t.package).join(", ")||"(none)"}`);let n=V();return console.log(` wired hooks: ${n.length}`),0}function on(e){let{flags:o}=de(e),n=o.get("key"),t=o.get("package");if(!n||!t)return console.error("Usage: opencrater hooks install --key <publisherKey> --package <name> [--host <host>]"),1;fe(n,t);let r=o.get("host");if(r&&r!=="true"){if(!b.includes(r))return console.error(`Unknown host "${r}". Supported: ${b.join(", ")}`),1;let i=r;try{let a=F(i,n,t);D([{host:i,status:a,events:U(i)}],t);}catch(a){return console.error(`Could not wire ${i}: ${a.message}`),1}}else D($(n,t),t);return console.log("Remove with: npx opencrater hooks uninstall"),0}function tn(){let e=ie();return v({integrations:[]}),console.log(e>0?`Removed ${e} OpenCrater hook${e===1?"":"s"} across all hosts.`:"No OpenCrater hooks installed."),0}function rn(){let e=V();if(e.length===0)return console.log("No OpenCrater hooks installed."),0;for(let o of e)console.log(`${o.host} ${o.event}: ${o.command}`);return 0}function le(){return console.log(`opencrater v${x} \u2014 OpenCrater Blips
21
+ `,p__namespace.mkdirSync(f__namespace.dirname(o),{recursive:true}),p__namespace.writeFileSync(o,n,"utf8");}async function on(e){let o=m().devToken;if(!o)return console.error("Not signed in. Run: opencrater login"),1;let n=await W(o,m().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 t=`${x().replace(/\/$/,"")}/gateway/v1`;n&&console.log(`Launching Grok on OpenCrater compute \xB7 balance ${T(n.balanceMicroUsd)}${$(n)}`);try{L("grok_cli");}catch{}try{nn(t);}catch(a){return console.error(`Couldn't configure the Grok compute model: ${a.message}`),1}let i={...process.env,OPENCRATER_TOKEN:o,OPENCRATER_ON_GATEWAY:"1"};delete i.GROK_MODELS_BASE_URL,delete i.GROK_HOME;let s=e.some(a=>a==="-m"||a==="--model"||a.startsWith("--model="))?[]:["-m","opencrater"],d=child_process.spawn("grok",[...s,...e],{stdio:"inherit",env:i,shell:process.platform==="win32"});return await new Promise(a=>{d.on("exit",c=>a(c??0)),d.on("error",c=>{console.error(`Couldn't launch grok: ${c.message}`),console.error("Is Grok installed? npm i -g @xai-official/grok"),a(127);});})}function me(e){let o=new Map,n=[];for(let t=0;t<e.length;t++){let i=e[t];if(i!==void 0)if(i.startsWith("--")){let r=i.indexOf("=");if(r!==-1)o.set(i.slice(2,r),i.slice(r+1));else {let s=e[t+1];s!==void 0&&!s.startsWith("--")?(o.set(i.slice(2),s),t++):o.set(i.slice(2),"true");}}else n.push(i);}return {flags:o,rest:n}}function ge(e,o){let n=m();n.integrations.some(t=>t.key===e&&t.package===o)||S({integrations:[...n.integrations,{key:e,package:o}].slice(-32)});}function U(e,o){let n=o||"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 t of e)if(t.status==="error")console.log(` \u2717 ${t.host}: ${t.error}`);else {let i=t.status==="nochange"?" \u2014 already set up":"";console.log(` \u2022 ${t.host} (${t.events.join(", ")})${i}`);}}function tn(){return S({optOut:true}),console.log("OpenCrater Blips are now OFF for this machine."),console.log("Re-enable any time with: npx opencrater on"),0}function rn(e){let{flags:o}=me(e),n=o.get("key"),t=o.get("package");return S({optOut:false}),n&&t?(ge(n,t),U(P(n,t),t),process.stdout.write("Pinning fast runtime (one-time, ~15s)\u2026 "),console.log(B()?"\u2713":"skipped (npm unavailable \u2014 hooks use npx fallback)")):m().devToken?(U(P()),process.stdout.write("Pinning fast runtime (one-time, ~15s)\u2026 "),console.log(B()?"\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 sn(){let e=m(),o=e.lastShownAt>0?new Date(e.lastShownAt).toISOString():"never";console.log(`opencrater v${E}`),console.log(` state file: ${A()}`),console.log(` install id: ${e.installId}`),console.log(` opted out: ${e.optOut?"yes":"no"}`),console.log(` last shown: ${o}`),console.log(` pooled Blips: ${e.pool.length}`),console.log(` hosts found: ${K().join(", ")||"(none)"}`),console.log(` integrations: ${e.integrations.map(t=>t.package).join(", ")||"(none)"}`);let n=Y();return console.log(` wired hooks: ${n.length}`),0}function an(e){let{flags:o}=me(e),n=o.get("key"),t=o.get("package");if(!n||!t)return console.error("Usage: opencrater hooks install --key <publisherKey> --package <name> [--host <host>]"),1;ge(n,t);let i=o.get("host");if(i&&i!=="true"){if(!b.includes(i))return console.error(`Unknown host "${i}". Supported: ${b.join(", ")}`),1;let r=i;try{let s=L(r,n,t);U([{host:r,status:s,events:q(r)}],t);}catch(s){return console.error(`Could not wire ${r}: ${s.message}`),1}}else U(P(n,t),t);return console.log("Remove with: npx opencrater hooks uninstall"),0}function cn(){let e=ce();return S({integrations:[]}),console.log(e>0?`Removed ${e} OpenCrater hook${e===1?"":"s"} across all hosts.`:"No OpenCrater hooks installed."),0}function ln(){let e=Y();if(e.length===0)return console.log("No OpenCrater hooks installed."),0;for(let o of e)console.log(`${o.host} ${o.event}: ${o.command}`);return 0}function de(){return console.log(`opencrater v${E} \u2014 OpenCrater Blips
22
22
 
23
23
  Usage:
24
24
  opencrater on [--key <ock_\u2026> --package <name>]
@@ -43,4 +43,4 @@ Usage:
43
43
  opencrater hooks list List installed OpenCrater hooks
44
44
 
45
45
  Hosts: ${b.join(", ")}
46
- Environment: OPENCRATER_DISABLE=1 disables everything; NO_COLOR respected.`),0}function sn(e){let[o,...n]=e;switch(o){case "off":return Ze();case "on":return en(n);case "login":return Ke();case "balance":return ze();case "logout":return We();case "claude":case "code":return Ve(n);case "codex":return qe(n);case "grok":return Qe(n);case "status":return nn();case "hooks":{let[t,...r]=n;switch(t){case "install":return on(r);case "uninstall":return tn();case "list":return rn();default:return console.error("Usage: opencrater hooks <install|uninstall|list>"),1}}case "version":case "--version":case "-v":return console.log(x),0;case void 0:case "help":case "--help":case "-h":return le();default:return console.error(`Unknown command: ${o}`),le(),1}}typeof G<"u"&&typeof module<"u"&&G.main===module&&Promise.resolve().then(()=>sn(process.argv.slice(2))).then(e=>{process.exitCode=e;}).catch(e=>{console.error(`opencrater: ${e.message}`),process.exitCode=1;});exports.runCli=sn;
46
+ Environment: OPENCRATER_DISABLE=1 disables everything; NO_COLOR respected.`),0}function fn(e){let[o,...n]=e;switch(o){case "off":return tn();case "on":return rn(n);case "login":return Ve();case "balance":return Ye();case "logout":return Xe();case "claude":case "code":return Qe(n);case "codex":return Ze(n);case "grok":return on(n);case "status":return sn();case "hooks":{let[t,...i]=n;switch(t){case "install":return an(i);case "uninstall":return cn();case "list":return ln();default:return console.error("Usage: opencrater hooks <install|uninstall|list>"),1}}case "version":case "--version":case "-v":return console.log(E),0;case void 0:case "help":case "--help":case "-h":return de();default:return console.error(`Unknown command: ${o}`),de(),1}}typeof D<"u"&&typeof module<"u"&&D.main===module&&Promise.resolve().then(()=>fn(process.argv.slice(2))).then(e=>{process.exitCode=e;}).catch(e=>{console.error(`opencrater: ${e.message}`),process.exitCode=1;});exports.runCli=fn;
package/dist/hook.js CHANGED
@@ -1,12 +1,13 @@
1
1
  #!/usr/bin/env node
2
- 'use strict';var child_process=require('child_process'),p=require('fs'),R=require('os'),m=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 p__namespace=/*#__PURE__*/_interopNamespace(p);var R__namespace=/*#__PURE__*/_interopNamespace(R);var m__namespace=/*#__PURE__*/_interopNamespace(m);var P=(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 M={minIntervalSeconds:600,serveTimeoutMs:2500,preloadPoolSize:3,killSwitch:false,displayDurationSeconds:25,minSdkVersion:""},fe={claude_code:["SessionStart","Stop","SessionEnd","Notification"],codex:["Stop"],openclaw:[],gemini_cli:["AfterAgent","SessionStart","SessionEnd"],copilot_cli:["agentStop","sessionStart","sessionEnd","notification"],grok_cli:["SessionStart","Stop","SessionEnd","Notification"],generic:["SessionStart","Stop"]},me={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:[],gemini_cli:["AfterAgent","SessionStart","SessionEnd","Notification","BeforeAgent","BeforeModel","AfterModel","BeforeToolSelection","BeforeTool","AfterTool","PreCompress"],copilot_cli:["agentStop","sessionStart","sessionEnd","notification","userPromptSubmitted","preToolUse","postToolUse","permissionRequest","errorOccurred","subagentStart","subagentStop"],grok_cli:["SessionStart","Stop","SessionEnd","Notification"],generic:["SessionStart","Stop"]};var I="1.1.42";var rt="https://api.opencrater.to";function B(e,t=process.env){let n=t.OPENCRATER_API_ORIGIN;return ((n&&n.trim()!==""?n:rt)).replace(/\/+$/,"")}function y(...e){try{if(process.env.OPENCRATER_DEBUG!=="1")return;console.error("[opencrater]",...e);try{let t=P("os"),n=P("fs"),r=P("path");n.appendFileSync(r.join(t.homedir(),".config","opencrater","hook.log"),`${new Date().toISOString()} [opencrater] ${e.map(o=>String(o)).join(" ")}
3
- `);}catch{}}catch{}}function L(e){return typeof e=="number"&&Number.isFinite(e)}function it(e){let t=M;if(typeof e!="object"||e===null)return {...t};let n=e;return {minIntervalSeconds:L(n.minIntervalSeconds)?n.minIntervalSeconds:t.minIntervalSeconds,serveTimeoutMs:L(n.serveTimeoutMs)?n.serveTimeoutMs:t.serveTimeoutMs,preloadPoolSize:L(n.preloadPoolSize)?n.preloadPoolSize:t.preloadPoolSize,killSwitch:n.killSwitch===true,displayDurationSeconds:L(n.displayDurationSeconds)?n.displayDurationSeconds:t.displayDurationSeconds,minSdkVersion:typeof n.minSdkVersion=="string"?n.minSdkVersion:t.minSdkVersion}}async function ge(e,t,n,r,o){try{let i=await fetch(`${e}${t}`,{method:"POST",headers:{"content-type":"application/json",...o??{}},body:JSON.stringify(n),signal:AbortSignal.timeout(r)});return i.ok?await i.json():(y(`POST ${t} -> HTTP ${i.status}`),null)}catch(i){return y(`POST ${t} failed:`,i),null}}function he(e,t){let n=e.host??"generic";return {publisherKey:e.publisherKey,packageName:e.packageName,placement:e.placement,host:n,sdkVersion:I,installId:t.installId,os:process.platform,termProgram:process.env.TERM_PROGRAM??void 0,topics:t.topics&&t.topics.length>0?t.topics:void 0}}function ye(e){if(typeof e!="object"||e===null)return null;let t=e;if(typeof t.fill!="boolean")return null;let n={fill:t.fill,fallback:t.fallback??null,config:it(t.config),...Array.isArray(t.allowedPlacements)?{allowedPlacements:t.allowedPlacements.filter(r=>typeof r=="string")}:{}};return t.blip!==void 0&&t.blip!==null&&(n.blip=t.blip),typeof t.computeBalanceMicroUsd=="number"&&(n.computeBalanceMicroUsd=t.computeBalanceMicroUsd),typeof t.weeklyGrantMicroUsd=="number"&&(n.weeklyGrantMicroUsd=t.weeklyGrantMicroUsd),typeof t.pendingMicroUsd=="number"&&(n.pendingMicroUsd=t.pendingMicroUsd),n}async function Se(e,t){let n=await ge(t.origin,"/v1/serve",he(e,t),t.timeoutMs);return ye(n)}async function be(e,t,n){let r={...he(t,n),publisherKey:t.publisherKey??"",packageName:t.packageName??""},o=await ge(n.origin,"/v1/dev/serve",r,n.timeoutMs,{authorization:`Bearer ${e}`});return ye(o)}function ke(e){let t={sponsorLabel:e.sponsorLabel,title:e.creative.title,body:e.creative.body,url:e.clickUrl};return e.creative.cta!==void 0&&(t.cta=e.creative.cta),t}function we(e){return {sponsorLabel:"",title:e.title,body:e.body,url:e.url}}function F(e){let t=ke(e),n=e.creative;switch(n.format){case "image":case "gif":return {...t,body:n.textFallback??t.body};case "video":return {...t,body:n.textFallback??t.body,cta:t.cta??"\u25B6 Watch"};case "audio":return {...t,body:n.textFallback??t.body,cta:t.cta??"\u{1F50A} Listen"};default:return t}}function H(e=process.env){return m__namespace.join(R__namespace.homedir(),".config","opencrater")}function J(e=process.env){return m__namespace.join(H(e),"state.json")}function G(){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 C(e){return typeof e=="number"&&Number.isFinite(e)}var Ce=new Set(["EPERM","EACCES","EBUSY","EEXIST"]);function Ee(e){for(let t=0;;t++)try{return {text:p__namespace.readFileSync(e,"utf8")}}catch(n){let r=n.code??"";if(!(r==="ENOENT"||Ce.has(r)))return {locked:true};if(t>=4)return r==="ENOENT"?{missing:true}:{locked:true};try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(t+1));}catch{}}}function at(e){if(typeof e!="object"||e===null)return null;let t=e;return !C(t.minIntervalSeconds)||!C(t.serveTimeoutMs)||!C(t.preloadPoolSize)||typeof t.killSwitch!="boolean"?null:{minIntervalSeconds:t.minIntervalSeconds,serveTimeoutMs:t.serveTimeoutMs,preloadPoolSize:t.preloadPoolSize,killSwitch:t.killSwitch,displayDurationSeconds:C(t.displayDurationSeconds)?t.displayDurationSeconds:25,minSdkVersion:typeof t.minSdkVersion=="string"?t.minSdkVersion:""}}function ct(e){if(!Array.isArray(e))return [];let t=[];for(let n of e){if(typeof n!="object"||n===null)continue;let r=n,o=r.blip;if(!C(r.renderBy)||typeof o!="object"||o===null||typeof o.impressionId!="string"||typeof o.clickUrl!="string"||typeof o.sponsorLabel!="string"||typeof o.creative!="object"||o.creative===null)continue;let i=o.creative;typeof i.title!="string"||typeof i.body!="string"||t.push({blip:{impressionId:o.impressionId,...typeof o.campaignId=="string"?{campaignId:o.campaignId}:{},clickUrl:o.clickUrl,sponsorLabel:o.sponsorLabel,creative:{format:"text",title:i.title,body:i.body,...typeof i.cta=="string"?{cta:i.cta}:{}}},renderBy:r.renderBy});}return t}function lt(e){if(typeof e!="object"||e===null||Array.isArray(e))return {};let t={};for(let[n,r]of Object.entries(e)){if(!Array.isArray(r))continue;let o=r.filter(i=>typeof i=="string"&&i.length<=64);t[n]=o.slice(0,64);}return t}function ut(e){if(!Array.isArray(e))return [];let t=[];for(let n of e){if(typeof n!="object"||n===null)continue;let r=n;if(!(typeof r.topic!="string"||!C(r.at))&&(t.push({topic:r.topic.slice(0,32),at:r.at}),t.length>=24))break}return t}function pt(e){if(!Array.isArray(e))return [];let t=[],n=new Set;for(let r of e){if(typeof r!="object"||r===null)continue;let o=r;if(typeof o.key!="string"||typeof o.package!="string"||o.key===""||o.package==="")continue;let i=`${o.package}\0${o.key}`;if(!n.has(i)&&(n.add(i),t.push({key:o.key,package:o.package}),t.length>=32))break}return t}function dt(e){if(typeof e!="object"||e===null)return null;let t=e,n={};if(typeof t.savedEnv=="object"&&t.savedEnv!==null)for(let[r,o]of Object.entries(t.savedEnv))(typeof o=="string"||o===null)&&(n[r]=o);return {active:t.active===true,savedEnv:n}}function ft(e){if(typeof e!="object"||e===null)return null;let t=e,n=r=>C(r)&&r>=0?r:0;return {turns:n(t.turns),lastLimitAt:n(t.lastLimitAt),lastDepletedAt:n(t.lastDepletedAt),lastBackupAt:n(t.lastBackupAt)}}function mt(e){let t=G();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:C(n.lastShownAt)&&n.lastShownAt>=0?n.lastShownAt:0,optOut:n.optOut===true,disclosureShown:n.disclosureShown===true,cachedConfig:at(n.cachedConfig),allowedPlacements:lt(n.allowedPlacements),sessionTopics:ut(n.sessionTopics),integrations:pt(n.integrations),devToken:typeof n.devToken=="string"?n.devToken:null,computeRouting:dt(n.computeRouting),computeCards:ft(n.computeCards),configFetchedAt:C(n.configFetchedAt)&&n.configFetchedAt>=0?n.configFetchedAt:0,pool:ct(n.pool)}}function ee(e=process.env){let t=J(e),n=Ee(t);if(n.text!==void 0)try{return mt(JSON.parse(n.text))}catch{let r=G();try{S(r,e);}catch{}return r}if(n.missing){let r=G();try{S(r,e);}catch{}return r}return G()}function S(e,t=process.env,n={}){let r=J(t),o=m__namespace.dirname(r);p__namespace.mkdirSync(o,{recursive:true});let i=Ee(r),s=null;if(i.text!==void 0)try{s=JSON.parse(i.text);}catch{s=null;}if(s)typeof s.lastShownAt=="number"&&s.lastShownAt>e.lastShownAt&&(e={...e,lastShownAt:s.lastShownAt}),!n.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(!n.allowClearToken&&e.devToken==null&&i.text===void 0&&!i.missing)return;let c=m__namespace.join(o,`.state.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`);p__namespace.writeFileSync(c,JSON.stringify(e,null,2)+`
4
- `,"utf8");for(let a=0;;a++)try{p__namespace.renameSync(c,r);return}catch(l){let f=l.code??"";if(a>=4||!Ce.has(f)){try{p__namespace.rmSync(c,{force:!0});}catch{}if(a>=4)return;throw l}try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(a+1));}catch{}}}var gt=300*1e3;function ht(){return m__namespace.join(H(),"blocked-ads.json")}function te(){return m__namespace.join(H(),"recent-renders.json")}function yt(){return m__namespace.join(H(),"reported-ads.json")}function Te(e,t){let n={};for(let[r,o]of Object.entries(e))typeof o=="number"&&Number.isFinite(o)&&o>t&&(n[r]=o);return n}function St(e){try{let t=JSON.parse(p__namespace.readFileSync(ht(),"utf8"));return Te(t&&typeof t=="object"?t:{},e)}catch{return {}}}function bt(){try{let e=JSON.parse(p__namespace.readFileSync(yt(),"utf8"));return e&&typeof e=="object"?e:{}}catch{return {}}}function kt(e){return e?bt()[e]!==void 0:false}function K(e,t=Date.now()){return e?St(t)[e]!==void 0||kt(e):false}function Re(e){try{let t=JSON.parse(p__namespace.readFileSync(te(),"utf8"));return Te(t&&typeof t=="object"?t:{},e)}catch{return {}}}function Y(e,t=Date.now()){if(e)try{let n=Re(t);n[e]=t+gt,p__namespace.mkdirSync(m__namespace.dirname(te()),{recursive:!0}),p__namespace.writeFileSync(te(),JSON.stringify(n));}catch{}}function W(e,t=Date.now()){return e?Re(t)[e]!==void 0:false}function wt(e,t){return e.filter(n=>n.renderBy>t)}function ne(e,t){let n=wt(e.pool,t),r=n.shift();return {blip:r?r.blip:null,pool:n}}var vt=["claude_code","codex","gemini_cli","copilot_cli","grok_cli"];function xe(e){return e.includes("opencrater-hook")||/opencrater[\\/][^"']*hook\.js/.test(e)}function Ct(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Et(e,t){return xe(e)&&new RegExp(`--package ['"]?${Ct(t)}['"]?`).test(e)}function Pe(e,t){return t?Et(e,t):xe(e)&&!/--package\b/.test(e)}function _e(e){return /^[A-Za-z0-9@_./:-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}var Oe='"$HOME/.config/opencrater/runtime/node_modules/opencrater/dist/hook.js"',Ie="$env:USERPROFILE\\.config\\opencrater\\runtime\\node_modules\\opencrater\\dist\\hook.js";function D(e,t,n,r){let o=`--placement ${t}`;return n&&(o+=` --key ${_e(n)}`),r&&(o+=` --package ${_e(r)}`),o+=` --host ${e}`,`{ if [ -f ${Oe} ]; then node ${Oe} ${o}; else npx -y -p opencrater opencrater-hook ${o}; fi; } 2>/dev/null || true`}function Tt(e,t,n){if(process.platform!=="win32")return D("grok_cli",e,t,n);let r=`--placement ${e}`;t&&(r+=` --key ${t}`),n&&(r+=` --package ${n}`),r+=" --host grok_cli";let o=`${R__namespace.homedir()}\\.config\\opencrater\\runtime\\node_modules\\opencrater\\dist\\hook.js`;return `try { if (Test-Path "${o}") { node "${o}" ${r} } else { npx -y -p opencrater opencrater-hook ${r} } } catch {}`}function Ne(e,t,n,r){let o=`--placement ${t}`;return n&&(o+=` --key '${n}'`),r&&(o+=` --package '${r}'`),o+=` --host ${e}`,`try { if (Test-Path "${Ie}") { node "${Ie}" ${o} } else { npx -y -p opencrater opencrater-hook ${o} } } catch {}`}function Rt(e,t,n){if(process.platform!=="win32")return D("claude_code",e,t,n);let r=`--placement ${e}`;return t&&(r+=` --key ${t}`),n&&(r+=` --package ${n}`),r+=" --host claude_code",`node "${`${R__namespace.homedir()}\\.config\\opencrater\\runtime\\node_modules\\opencrater\\dist\\hook.js`}" ${r}; exit 0`}function oe(e,t,n,r){if(e==="grok_cli")return {type:"command",command:Tt(t,n,r),timeout:15};let i={type:"command",command:e==="claude_code"?Rt(t,n,r):D(e,t,n,r)};return e==="codex"&&(i.commandWindows=Ne(e,t,n,r)),i}function re(e,t){let n=R__namespace.homedir();switch(e){case "claude_code":{let r=t.CLAUDE_CONFIG_DIR;return r&&r.trim()!==""?r:m__namespace.join(n,".claude")}case "codex":{let r=t.CODEX_HOME;return r&&r.trim()!==""?r:m__namespace.join(n,".codex")}case "gemini_cli":return m__namespace.join(n,".gemini");case "copilot_cli":{let r=t.COPILOT_HOME;return r&&r.trim()!==""?r:m__namespace.join(n,".copilot")}case "grok_cli":{let r=t.GROK_HOME;return r&&r.trim()!==""?r:m__namespace.join(n,".grok")}default:return m__namespace.join(n,".opencrater-unknown")}}function z(e,t=process.env){let n=re(e,t);switch(e){case "claude_code":return m__namespace.join(n,"settings.json");case "codex":return m__namespace.join(n,"hooks.json");case "gemini_cli":return m__namespace.join(n,"settings.json");case "copilot_cli":return m__namespace.join(n,"hooks","hooks.json");case "grok_cli":return m__namespace.join(n,"hooks","opencrater.json");default:return m__namespace.join(n,"hooks.json")}}var _t={claude_code:["claude"],codex:["codex"],gemini_cli:["gemini"],copilot_cli:["copilot"],grok_cli:["grok"]};function Ot(e,t){if(e.length===0)return false;let n=(t.PATH??t.Path??"").split(m__namespace.delimiter).filter(Boolean),r=process.platform==="win32"?["",".exe",".cmd",".bat"]:[""];for(let o of n)for(let i of e)for(let s of r)try{if(p__namespace.existsSync(m__namespace.join(o,i+s)))return !0}catch{}return false}function It(e,t=process.env){try{if(p__namespace.existsSync(re(e,t)))return !0}catch{}return Ot(_t[e]??[],t)}function ie(e=process.env){return vt.filter(t=>It(t,e))}function $e(e){let t;try{t=p__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 Me(e,t){let n=m__namespace.dirname(e);p__namespace.mkdirSync(n,{recursive:true});let r=m__namespace.join(n,`.${m__namespace.basename(e)}.${process.pid}.tmp`);p__namespace.writeFileSync(r,JSON.stringify(t,null,2)+`
5
- `,"utf8"),p__namespace.renameSync(r,e);}function At(e,t){return Array.isArray(e.hooks)&&e.hooks.some(n=>typeof n.command=="string"&&Pe(n.command,t))}function xt(e,t,n,r){let o=z(e),i=$e(o),s=i.hooks&&typeof i.hooks=="object"?i.hooks:{};if(r.every(a=>{let l=oe(e,a,t,n);return (Array.isArray(s[a])?s[a]:[]).some(f=>Array.isArray(f.hooks)&&f.hooks.some(d=>d.command===l.command&&d.commandWindows===l.commandWindows))}))return "nochange";for(let a of r){let f=(Array.isArray(s[a])?s[a]:[]).filter(u=>!At(u,n)),d=e==="grok_cli"?{hooks:[oe(e,a,t,n)]}:{matcher:"",hooks:[oe(e,a,t,n)]};f.push(d),s[a]=f;}return i.hooks=s,Me(o,i),"wrote"}var Ae=12;function Pt(e,t){return [e.bash,e.powershell,e.command].some(n=>typeof n=="string"&&Pe(n,t))}function Nt(e,t,n,r){let o=z(e),i=$e(o);typeof i.version!="number"&&(i.version=1);let s=i.hooks&&typeof i.hooks=="object"?i.hooks:{};if(r.every(a=>{let l=D(e,a,t,n);return (Array.isArray(s[a])?s[a]:[]).some(f=>f.bash===l&&f.timeoutSec===Ae)}))return "nochange";for(let a of r){let f=(Array.isArray(s[a])?s[a]:[]).filter(d=>!Pt(d,n));f.push({type:"command",bash:D(e,a,t,n),powershell:Ne(e,a,t,n),timeoutSec:Ae}),s[a]=f;}return i.hooks=s,Me(o,i),"wrote"}function He(e){return [...me[e]]}function $t(e){let t=e;for(let n of ["claude","cursor"]){if(new RegExp(`^\\s*\\[compat\\.${n}\\]`,"m").test(t))continue;let r=t.length===0?"":t.endsWith(`
2
+ 'use strict';var child_process=require('child_process'),h=require('fs'),I=require('os'),b=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 I__namespace=/*#__PURE__*/_interopNamespace(I);var b__namespace=/*#__PURE__*/_interopNamespace(b);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 B={minIntervalSeconds:600,serveTimeoutMs:2500,preloadPoolSize:3,killSwitch:false,displayDurationSeconds:25,minSdkVersion:""},Te={claude_code:["SessionStart","Stop","SessionEnd","Notification"],codex:["Stop"],openclaw:[],antigravity:["AfterAgent","SessionStart","SessionEnd"],copilot_cli:["agentStop","sessionStart","sessionEnd","notification"],grok_cli:["SessionStart","Stop","SessionEnd","Notification"],generic:["SessionStart","Stop"]},je={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:["AfterAgent","SessionStart","SessionEnd","Notification","BeforeAgent","BeforeModel","AfterModel","BeforeToolSelection","BeforeTool","AfterTool","PreCompress"],copilot_cli:["agentStop","sessionStart","sessionEnd","notification","userPromptSubmitted","preToolUse","postToolUse","permissionRequest","errorOccurred","subagentStart","subagentStop"],grok_cli:["SessionStart","Stop","SessionEnd","Notification"],generic:["SessionStart","Stop"]};var N="1.3.0";var yt="https://api.opencrater.to";function G(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 z(t){return typeof t=="number"&&Number.isFinite(t)}function bt(t){let o=B;if(typeof t!="object"||t===null)return {...o};let e=t;return {minIntervalSeconds:z(e.minIntervalSeconds)?e.minIntervalSeconds:o.minIntervalSeconds,serveTimeoutMs:z(e.serveTimeoutMs)?e.serveTimeoutMs:o.serveTimeoutMs,preloadPoolSize:z(e.preloadPoolSize)?e.preloadPoolSize:o.preloadPoolSize,killSwitch:e.killSwitch===true,displayDurationSeconds:z(e.displayDurationSeconds)?e.displayDurationSeconds:o.displayDurationSeconds,minSdkVersion:typeof e.minSdkVersion=="string"?e.minSdkVersion:o.minSdkVersion}}async function Re(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 Ee(t,o){let e=t.host??"generic";return {publisherKey:t.publisherKey,packageName:t.packageName,placement:t.placement,host:e,sdkVersion:N,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 Oe(t,o){let e=await Re(o.origin,"/v1/serve",Ee(t,o),o.timeoutMs);return _e(e)}async function Ae(t,o,e){let r={...Ee(o,e),publisherKey:o.publisherKey??"",packageName:o.packageName??""},n=await Re(e.origin,"/v1/dev/serve",r,e.timeoutMs,{authorization:`Bearer ${t}`});return _e(n)}var wt=48,J=360*60*1e3;function Pe(t){return crypto.createHash("sha256").update(t).digest("hex").slice(0,16)}function Ie(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(b__namespace.join(t,s),"utf8")}catch{return ""}},f=s=>{try{return JSON.parse(c(s))}catch{return null}},u=f("package.json")??{},d={...u.dependencies??{},...u.devDependencies??{},...u.peerDependencies??{}},a=s=>Object.prototype.hasOwnProperty.call(d,s),p=s=>Object.keys(d).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"),p("@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(y=>y.endsWith(".csproj"));if(i.length>0){let y=i.map(g=>c(g)).join(`
4
+ `).toLowerCase();(y.includes("microsoft.net.sdk.web")||y.includes("microsoft.aspnetcore"))&&e("fw:aspnet"),y.includes("blazor")&&e("fw:blazor"),(y.includes("microsoft.net.sdk.maui")||y.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(y=>y===i||y.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")||p("@aws-sdk/"))&&e("infra:aws"),(p("@google-cloud/")||a("googleapis"))&&e("infra:gcp"),p("@azure/")&&e("infra:azure"),(p("@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"),p("@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"),(p("@aws-sdk/client-sqs")||a("sqs-consumer"))&&e("infra:sqs"),a("@google-cloud/pubsub")&&e("infra:pubsub"),p("@temporalio/")&&e("infra:temporal"),(a("bullmq")||a("bull"))&&e("infra:bullmq"),p("@sentry/")&&e("infra:sentry"),(p("@datadog/")||a("dd-trace"))&&e("infra:datadog"),p("@opentelemetry/")&&e("infra:opentelemetry"),a("newrelic")&&e("infra:newrelic"),(a("posthog-node")||a("posthog-js"))&&e("infra:posthog"),p("@honeycombio/")&&e("infra:honeycomb"),a("prom-client")&&e("infra:prometheus"),(a("stripe")||a("@stripe/stripe-js"))&&e("infra:stripe"),p("@paddle/")&&e("infra:paddle"),p("@clerk/")&&e("infra:clerk"),(a("auth0")||p("@auth0/"))&&e("infra:auth0"),(a("next-auth")||p("@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"),p("@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(b__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),y=(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=>y.includes(w),A=w=>r.some(ae=>ae.toLowerCase().endsWith(w)),k=(...w)=>w.some(ae=>n(ae)),j=()=>Array.from(o).some(w=>w.startsWith("type:")),se=()=>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"),(A(".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")||A(".unity")||A(".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")||A(".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"),(A(".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"),(u.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(u.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"),ve=Array.from(o).some(w=>["infra:postgres","infra:mysql","infra:mongodb","infra:supabase","infra:neon"].includes(w)),xe=i("next-auth","@clerk/nextjs","@auth0/auth0-react","passport","lucia","@workos-inc/node")||l("django-allauth")||l("flask-login"),Ce=i("stripe","@stripe/stripe-js","@paddle/paddle-js","@lemonsqueezy/lemonsqueezy.js")||l("stripe");(!T&&!R&&(u.main||u.exports||u.module||u.types||u.publishConfig)||n("Cargo.toml")&&!m.includes("[[bin]]")&&m.includes("[lib]")||k("LICENSE","LICENSE.md","LICENSE.txt")&&!T&&!R&&!j())&&!j()&&e("type:library"),T?(ve&&(xe||Ce)&&e("type:saas"),e("type:web-app")):R&&(ve&&(xe||Ce)&&e("type:saas"),e("type:api-service")),j()||(se()?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")&&(u.main||u.exports)&&e("type:library"));}return Array.from(o)}function Ne(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 $e(t){return {sponsorLabel:"",title:t.title,body:t.body,url:t.url}}function K(t){let o=Ne(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 H(t=process.env){return b__namespace.join(I__namespace.homedir(),".config","opencrater")}function V(t=process.env){return b__namespace.join(H(t),"state.json")}function Y(){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 Le=new Set(["EPERM","EACCES","EBUSY","EEXIST"]);function De(t){for(let o=0;;o++)try{return {text:h__namespace.readFileSync(t,"utf8")}}catch(e){let r=e.code??"";if(!(r==="ENOENT"||Le.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 _t(t){let o=t.attrTagsAt,e=t.attrTagsCwd;return !E(o)||Date.now()-o>J||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 Ot(t){let o=Y();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),..._t(e)}}function le(t=process.env){let o=V(t),e=De(o);if(e.text!==void 0)try{return Ot(JSON.parse(e.text))}catch{let r=Y();try{C(r,t);}catch{}return r}if(e.missing){let r=Y();try{C(r,t);}catch{}return r}return Y()}function C(t,o=process.env,e={}){let r=V(o),n=b__namespace.dirname(r);h__namespace.mkdirSync(n,{recursive:true});let c=De(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 u=b__namespace.join(n,`.state.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`);h__namespace.writeFileSync(u,JSON.stringify(t,null,2)+`
5
+ `,"utf8");for(let d=0;;d++)try{h__namespace.renameSync(u,r);return}catch(a){let p=a.code??"";if(d>=4||!Le.has(p)){try{h__namespace.rmSync(u,{force:!0});}catch{}if(d>=4)return;throw a}try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(d+1));}catch{}}}var At=300*1e3;function Pt(){return b__namespace.join(H(),"blocked-ads.json")}function fe(){return b__namespace.join(H(),"recent-renders.json")}function It(){return b__namespace.join(H(),"reported-ads.json")}function We(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(Pt(),"utf8"));return We(o&&typeof o=="object"?o:{},t)}catch{return {}}}function $t(){try{let t=JSON.parse(h__namespace.readFileSync(It(),"utf8"));return t&&typeof t=="object"?t:{}}catch{return {}}}function Mt(t){return t?$t()[t]!==void 0:false}function X(t,o=Date.now()){return t?Nt(o)[t]!==void 0||Mt(t):false}function Be(t){try{let o=JSON.parse(h__namespace.readFileSync(fe(),"utf8"));return We(o&&typeof o=="object"?o:{},t)}catch{return {}}}function Z(t,o=Date.now()){if(t)try{let e=Be(o);e[t]=o+At,h__namespace.mkdirSync(b__namespace.dirname(fe()),{recursive:!0}),h__namespace.writeFileSync(fe(),JSON.stringify(e));}catch{}}function Q(t,o=Date.now()){return t?Be(o)[t]!==void 0:false}function Lt(t,o){return t.filter(e=>e.renderBy>o)}function ue(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 ze(t){return t.includes("opencrater-hook")||/opencrater[\\/][^"']*hook\.js/.test(t)}function Wt(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Bt(t,o){return ze(t)&&new RegExp(`--package ['"]?${Wt(o)}['"]?`).test(t)}function Ge(t,o){return o?Bt(t,o):ze(t)&&!/--package\b/.test(t)}function He(t){return /^[A-Za-z0-9@_./:-]+$/.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}var Ue='"$HOME/.config/opencrater/runtime/node_modules/opencrater/dist/hook.js"',Fe="$env:USERPROFILE\\.config\\opencrater\\runtime\\node_modules\\opencrater\\dist\\hook.js";function U(t,o,e,r){let n=`--placement ${o}`;return e&&(n+=` --key ${He(e)}`),r&&(n+=` --package ${He(r)}`),n+=` --host ${t}`,`{ if [ -f ${Ue} ]; then node ${Ue} ${n}; else npx -y -p opencrater opencrater-hook ${n}; fi; } 2>/dev/null || true`}function Ht(t,o,e){if(process.platform!=="win32")return U("grok_cli",t,o,e);let r=`--placement ${t}`;o&&(r+=` --key ${o}`),e&&(r+=` --package ${e}`),r+=" --host grok_cli";let n=`${I__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 Je(t,o,e,r){let n=`--placement ${o}`;return e&&(n+=` --key '${e}'`),r&&(n+=` --package '${r}'`),n+=` --host ${t}`,`try { if (Test-Path "${Fe}") { node "${Fe}" ${n} } else { npx -y -p opencrater opencrater-hook ${n} } } catch {}`}function Ut(t,o,e){if(process.platform!=="win32")return U("claude_code",t,o,e);let r=`--placement ${t}`;return o&&(r+=` --key ${o}`),e&&(r+=` --package ${e}`),r+=" --host claude_code",`node "${`${I__namespace.homedir()}\\.config\\opencrater\\runtime\\node_modules\\opencrater\\dist\\hook.js`}" ${r}; exit 0`}function de(t,o,e,r){if(t==="grok_cli")return {type:"command",command:Ht(o,e,r),timeout:15};let c={type:"command",command:t==="claude_code"?Ut(o,e,r):U(t,o,e,r)};return t==="codex"&&(c.commandWindows=Je(t,o,e,r)),c}function pe(t,o){let e=I__namespace.homedir();switch(t){case "claude_code":{let r=o.CLAUDE_CONFIG_DIR;return r&&r.trim()!==""?r:b__namespace.join(e,".claude")}case "codex":{let r=o.CODEX_HOME;return r&&r.trim()!==""?r:b__namespace.join(e,".codex")}case "antigravity":return b__namespace.join(e,".gemini");case "copilot_cli":{let r=o.COPILOT_HOME;return r&&r.trim()!==""?r:b__namespace.join(e,".copilot")}case "grok_cli":{let r=o.GROK_HOME;return r&&r.trim()!==""?r:b__namespace.join(e,".grok")}default:return b__namespace.join(e,".opencrater-unknown")}}function te(t,o=process.env){let e=pe(t,o);switch(t){case "claude_code":return b__namespace.join(e,"settings.json");case "codex":return b__namespace.join(e,"hooks.json");case "antigravity":return b__namespace.join(e,"settings.json");case "copilot_cli":return b__namespace.join(e,"hooks","hooks.json");case "grok_cli":return b__namespace.join(e,"hooks","opencrater.json");default:return b__namespace.join(e,"hooks.json")}}var Ft={claude_code:["claude"],codex:["codex"],antigravity:["agy"],copilot_cli:["copilot"],grok_cli:["grok"]};function qt(t,o){if(t.length===0)return false;let e=(o.PATH??o.Path??"").split(b__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(b__namespace.join(n,c+f)))return !0}catch{}return false}function zt(t,o=process.env){try{if(h__namespace.existsSync(pe(t,o)))return !0}catch{}return qt(Ft[t]??[],o)}function me(t=process.env){return Dt.filter(o=>zt(o,t))}function Ke(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 Ye(t,o){let e=b__namespace.dirname(t);h__namespace.mkdirSync(e,{recursive:true});let r=b__namespace.join(e,`.${b__namespace.basename(t)}.${process.pid}.tmp`);h__namespace.writeFileSync(r,JSON.stringify(o,null,2)+`
6
+ `,"utf8"),h__namespace.renameSync(r,t);}function Gt(t,o){return Array.isArray(t.hooks)&&t.hooks.some(e=>typeof e.command=="string"&&Ge(e.command,o))}function Jt(t,o,e,r){let n=te(t),c=Ke(n),f=c.hooks&&typeof c.hooks=="object"?c.hooks:{};if(!(t==="antigravity"&&c["json-hooks-enabled"]!==true)&&r.every(a=>{let p=de(t,a,o,e);return (Array.isArray(f[a])?f[a]:[]).some(s=>Array.isArray(s.hooks)&&s.hooks.some(i=>i.command===p.command&&i.commandWindows===p.commandWindows))}))return "nochange";for(let a of r){let s=(Array.isArray(f[a])?f[a]:[]).filter(y=>!Gt(y,e)),i=t==="grok_cli"?{hooks:[de(t,a,o,e)]}:{matcher:"",hooks:[de(t,a,o,e)]};s.push(i),f[a]=s;}return t==="antigravity"&&(c["json-hooks-enabled"]=true),c.hooks=f,Ye(n,c),"wrote"}var qe=12;function Kt(t,o){return [t.bash,t.powershell,t.command].some(e=>typeof e=="string"&&Ge(e,o))}function Yt(t,o,e,r){let n=te(t),c=Ke(n);typeof c.version!="number"&&(c.version=1);let f=c.hooks&&typeof c.hooks=="object"?c.hooks:{};if(r.every(d=>{let a=U(t,d,o,e);return (Array.isArray(f[d])?f[d]:[]).some(p=>p.bash===a&&p.timeoutSec===qe)}))return "nochange";for(let d of r){let p=(Array.isArray(f[d])?f[d]:[]).filter(s=>!Kt(s,e));p.push({type:"command",bash:U(t,d,o,e),powershell:Je(t,d,o,e),timeoutSec:qe}),f[d]=p;}return c.hooks=f,Ye(n,c),"wrote"}function Ve(t){return [...je[t]]}function Vt(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(`
6
7
  `)?`
7
8
  `:`
8
9
 
9
- `;t+=`${r}[compat.${n}]
10
+ `;o+=`${r}[compat.${e}]
10
11
  hooks = false
11
- `;}return t}function Mt(e){try{let t=m__namespace.join(re("grok_cli",e),"config.toml"),n="";try{n=p__namespace.readFileSync(t,"utf8");}catch{}let r=$t(n);if(r===n)return;p__namespace.mkdirSync(m__namespace.dirname(t),{recursive:!0}),p__namespace.writeFileSync(t,r,"utf8");}catch{}}function Ht(e,t,n){let r=He(e);return r.length===0?"nochange":(e==="grok_cli"&&Mt(process.env),e==="copilot_cli"?Nt(e,t,n,r):xt(e,t,n,r))}function se(e,t,n=process.env){return ie(n).map(r=>{try{let o=Ht(r,e,t);return {host:r,status:o,events:He(r)}}catch(o){return {host:r,status:"error",events:[],error:o.message}}})}function jt(){return m__namespace.join(R__namespace.homedir(),".config","opencrater","runtime")}function Ut(e){return ["install","--prefix",e,"opencrater@latest","--silent","--no-audit","--no-fund"]}function ae(e=jt()){child_process.spawn("npm",Ut(e),process.platform==="win32"?{detached:false,stdio:"ignore",windowsHide:true,shell:true}:{detached:true,stdio:"ignore"}).unref();}var Le={atLimit:false,resetAt:null};function Be(e,t=R__namespace.homedir()){try{if(e==="claude_code")return Lt(t);if(e==="codex")return Bt(t)}catch{}return Le}function Lt(e){let t=p__namespace.readFileSync(m__namespace.join(e,".claude.json"),"utf8"),n=JSON.parse(t),r=n.hasAvailableSubscription===false||n.cachedExtraUsageDisabledReason==="out_of_credits",o=null,c=n.cachedGrowthBookFeatures?.tengu_saffron_lattice?.planLimitsEndDate;if(typeof c=="string"){let a=Date.parse(c);Number.isFinite(a)&&(o=a);}return {atLimit:r,resetAt:o}}function Bt(e){return p__namespace.accessSync(m__namespace.join(e,".codex","auth.json")),Le}function Fe(e,t){switch(e){case "gemini_cli":return t==="AfterAgent";case "copilot_cli":return t==="agentStop";default:return t==="Stop"}}var Ge=36e5,Ft=30*6e4,Gt=30*6e4,Jt=4*Ge,Kt=3,q="https://opencrater.to/dashboard";function j(e){return `${Math.round(e/1e3).toLocaleString()} tokens`}function Yt(e){let t=e/1e3;return t>0&&t<10?`${(Math.round(t*10)/10).toFixed(1)} tokens`:`${Math.round(t).toLocaleString()} tokens`}function Wt(e){switch(e){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 X="opencrater claude";function Vt(e,t){if(!e||e<=t)return "";let n=e-t,r=n>=864e5?`${Math.floor(n/864e5)}d`:`${Math.max(1,Math.floor(n/Ge))}h`,o=new Date(e).toISOString().slice(0,10);return ` Your host limit resets in ${r} (${o}).`}function Je(e){let{balanceMicroUsd:t,pendingMicroUsd:n,onGateway:r,turnEnd:o,hostName:i,host:s,cc:c,now:a}=e;if(t===null)return null;let l=Wt(i),f=n&&n>0?` (+${Yt(n)} pending)`:"";return t<=0?a-(c.lastDepletedAt??0)<Gt?null:{kind:"depleted",card:{sponsorLabel:"OpenCrater",title:"Compute used up",body:`Keep coding in any CLI to earn more compute, then switch back to ${l?.name??"your plan"}.`+Vt(s.resetAt,a),url:q,cta:"Earn more"}}:r?!o||(c.turns??0)%Kt!==0?null:{kind:"hud",card:{sponsorLabel:"OpenCrater",title:"Running on OpenCrater compute",body:`${j(t)} compute available${f}.`,url:q,cta:"Wallet"}}:s.atLimit?a-(c.lastLimitAt??0)<Ft?null:{kind:"limit",card:{sponsorLabel:"OpenCrater",title:"Hit your limit? You've got compute",body:l?`${j(t)} of OpenCrater compute is ready. Continue this ${l.name} session now: ${l.resume}`:`${j(t)} of OpenCrater compute is ready. Run your coding agent on it: ${X}`,url:q,cta:l?l.resume:X}}:a-(c.lastBackupAt??0)>=Jt?{kind:"backup",card:{sponsorLabel:"OpenCrater",title:"Backup compute ready",body:l?`${j(t)} of OpenCrater compute waiting${f}. When you hit your limit: ${l.resume}`:`${j(t)} of OpenCrater compute waiting${f}. Spend it any time: ${X}`,url:q,cta:l?l.resume:X}}:null}var Zt=["CI","CONTINUOUS_INTEGRATION","GITHUB_ACTIONS","GITLAB_CI","CIRCLECI","TRAVIS","BUILDKITE","JENKINS_URL","TEAMCITY_VERSION","TF_BUILD","APPVEYOR","CODEBUILD_BUILD_ID","DRONE","NETLIFY","VERCEL"];function le(e){return e!==void 0&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}function Qt(e){return le(e.OPENCRATER_DISABLE)||le(e.TSN_DISABLE)}function en(e){return Zt.some(t=>le(e[t]))}function Q(e){return e?{...M,...e}:M}function Xe(e,t={}){if(Qt(e.env))return "env_disabled";if(e.state.optOut)return "opt_out";let n=Q(e.state.cachedConfig);if(n.killSwitch)return "kill_switch";if(en(e.env))return "ci";if(!t.skipTTY&&false);if(!t.skipFrequency){let r=n.minIntervalSeconds*1e3;if(e.state.lastShownAt>0&&e.now-e.state.lastShownAt<r)return "frequency"}return null}var tn=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 nn(e){if(e.includes("/")||e.includes("\\")||e.includes("@")||e.includes("://"))return true;let t=e.toLowerCase();return !!(/^(sk|pk|rk|ock|ghp|gho|ghs|xox|akia|eyj|npm|glpat)[-_]/.test(t)||e.length>=16&&/^[0-9a-f]+$/i.test(e)||e.length>=20&&/^[A-Za-z0-9+/=_-]+$/.test(e)&&/[A-Z]/.test(e)&&/[0-9]/.test(e))}function on(e,t=12){let n=[];for(let r of e.slice(0,2e3).split(/\s+/))if(!(!r||nn(r)))for(let o of r.split(/[^A-Za-z0-9+#.]+|(?<=[a-z0-9])(?=[A-Z])/)){let i=o.replace(/^[.]+|[.]+$/g,"").toLowerCase();if(!(i.length<3||i.length>24)&&!(/^\d+$/.test(i)||tn.has(i))&&!n.includes(i)&&(n.push(i),n.length>=t))return n}return n}function ue(e){let t=[];typeof e.prompt=="string"&&t.push(e.prompt);let n=e.cwd;if(typeof n=="string"&&n.length>0){let r=n.replace(/[\\/]+$/,""),o=r.split(/[\\/]/).pop()??"",i=(process.env.HOME??process.env.USERPROFILE??"").replace(/[\\/]+$/,""),s=process.env.USER??process.env.USERNAME??"";r!==i&&o!==s&&o.length>0&&t.push(o.replace(/[-_]/g," "));}return on(t.join(" "))}function pe(e,t,n){let r=new Map;for(let{topic:o,at:i}of e)n-i<216e5&&r.set(o,i);for(let o of t)r.set(o,n);return [...r.entries()].map(([o,i])=>({topic:o,at:i})).sort((o,i)=>i.at-o.at).slice(0,24)}function Ze(e,t){return e.filter(({at:n})=>t-n<216e5).sort((n,r)=>r.at-n.at).slice(0,12).map(({topic:n})=>n)}var an=false,cn=process.platform==="win32"?8e3:3200,ln=150,un=2800,de="claude_code";function pn(e){let t={host:"claude_code"};for(let n=0;n<e.length;n++){let r=e[n],o=e[n+1];switch(r){case "--placement":o!==void 0&&(t.placement=o,n++);break;case "--key":o!==void 0&&(t.key=o,n++);break;case "--package":o!==void 0&&(t.package=o,n++);break;case "--host":(o==="claude_code"||o==="codex"||o==="openclaw"||o==="gemini_cli"||o==="copilot_cli"||o==="grok_cli"||o==="generic")&&(t.host=o,n++);break;}}return t}function dn(e){return new Promise(t=>{if(process.stdin.isTTY){t("");return}let n="",r=false,o=()=>{r||(r=true,t(n));},i=setTimeout(o,e);i.unref?.(),process.stdin.setEncoding("utf8"),process.stdin.on("data",s=>{n+=s;}),process.stdin.on("end",()=>{clearTimeout(i),o();}),process.stdin.on("error",()=>{clearTimeout(i),o();});})}var fn="\\\\.\\CONOUT$";function mn(e){return !e||e==="?"||e==="??"||e==="-"?null:e.startsWith("/")?e:`/dev/${e}`}function gn(e){let t=e.match(/^\s*(\d+)\s+(\S+)/);return t?{ppid:Number(t[1]),tty:t[2]}:null}function hn(e){if(!Number.isInteger(e)||e<=0)return null;let t=e>>8&4095,n=e&255|e>>12&1048320;return t>=136&&t<=143?`/dev/pts/${(t-136)*256+n}`:t===4?n<64?`/dev/tty${n}`:`/dev/ttyS${n-64}`:null}function yn(e){let t=e.lastIndexOf(")");if(t<0)return null;let n=e.slice(t+1).trim().split(/\s+/),r=Number(n[1]),o=Number(n[4]);return !Number.isInteger(r)||!Number.isInteger(o)?null:{ppid:r,ttyNr:o}}function Sn(e){try{let t=yn(p__namespace.readFileSync(`/proc/${e}/stat`,"utf8"));if(t)return {ppid:t.ppid,ttyPath:hn(t.ttyNr)}}catch{}try{let t=child_process.spawnSync("ps",["-o","ppid=,tty=","-p",String(e)],{encoding:"utf8",timeout:1500}).stdout?.trim();if(!t)return null;let n=gn(t);return n?{ppid:n.ppid,ttyPath:mn(n.tty)}:null}catch{return null}}function bn(){if(process.platform==="win32")return {path:fn,ownerPid:null};let e=process.pid;for(let t=0;t<12&&e>1;t++){let n=Sn(e);if(!n)return null;if(n.ttyPath)return {path:n.ttyPath,ownerPid:e};e=n.ppid;}return null}function kn(e){return e==="win32"?{detached:false,stdio:"ignore",windowsHide:false}:{detached:true,stdio:"ignore",windowsHide:false}}async function U(e,t,n,r,o,i){try{let s=m__namespace.join(__dirname,"paint.js"),c,a;if(i&&r){let b=B();i.kind==="dev"?(c=`${b}/v1/dev/impression`,a=i.token):c=`${b}/v1/events/impression`;}let l=Q(t.cachedConfig),f=Math.min(Math.max(l.displayDurationSeconds??25,3),120),d={...e,format:n?.format,mediaUrl:n?.mediaUrl,mediaPixelUrl:n?.mediaPixelUrl,audioUrl:n?.audioUrl,impressionId:r,campaignId:o,apiOrigin:B(),reportImpressionUrl:c,reportImpressionAuth:a,durationMs:f*1e3,disclosure:!t.disclosureShown,host:de},u={...process.env,OPENCRATER_PAINT:JSON.stringify(d)};if(!u.OPENCRATER_TTY){let b=bn();b&&(u.OPENCRATER_TTY=b.path,b.ownerPid!==null&&(u.OPENCRATER_HOST_PID=String(b.ownerPid)));}let _=child_process.spawn(process.execPath,[s],{...kn(process.platform),env:u});process.platform==="win32"?await new Promise(b=>{let v=!1,k=()=>{v||(v=!0,b());};_.on("exit",k),_.on("error",k),setTimeout(k,7500);}):_.unref();}catch{}return {...t,lastShownAt:Date.now(),disclosureShown:true}}function Qe(e){if(process.platform!=="win32")return false;try{let t=m__namespace.join(R__namespace.homedir(),".config","opencrater","painter.lock"),n=JSON.parse(p__namespace.readFileSync(t,"utf8"));if(typeof n.startedAt!="number"||Date.now()-n.startedAt>e+1500)return !1;if(typeof n.pid=="number")try{process.kill(n.pid,0);}catch(r){if(r.code==="ESRCH")return !1}return !0}catch{return false}}var wn=8e3;function et(){let e=m__namespace.join(R__namespace.homedir(),".config","opencrater","render.lock");try{let t=p__namespace.statSync(e);if(Date.now()-t.mtimeMs<wn)return !1;p__namespace.unlinkSync(e);}catch{}try{return p__namespace.mkdirSync(m__namespace.join(R__namespace.homedir(),".config","opencrater"),{recursive:!0}),p__namespace.writeFileSync(e,String(process.pid),{flag:"wx"}),!0}catch{return false}}function vn(e,t,n,r){if(!t)return true;let o=e.allowedPlacements[`${t}:${n}`];return o?o.includes(r):t==="opencrater"?fe[n].includes(r):true}var Cn=1440*60*1e3;function En(){try{let e=m__namespace.join(R__namespace.homedir(),".config","opencrater","runtime"),t=m__namespace.join(e,"node_modules","opencrater","dist","hook.js"),n=m__namespace.join(e,".last-update");if(p__namespace.existsSync(t)){try{if(Date.now()-p__namespace.statSync(n).mtimeMs<Cn)return}catch{}try{p__namespace.writeFileSync(n,String(Date.now()));}catch{return}}else {let r=m__namespace.join(e,".installing");try{p__namespace.mkdirSync(e,{recursive:!0});let o=p__namespace.statSync(r);if(Date.now()-o.mtimeMs<600*1e3)return}catch{}p__namespace.writeFileSync(r,String(Date.now()));}ae(e);}catch{}}function tt(e,t){if(!t)return false;let n=s=>s.split(/[-+]/)[0].split(".").map(c=>parseInt(c,10)||0),r=n(e),o=n(t),i=Math.max(r.length,o.length);for(let s=0;s<i;s++){let c=r[s]??0,a=o[s]??0;if(c!==a)return c<a}return false}function nt(){try{let e=m__namespace.join(R__namespace.homedir(),".config","opencrater","runtime"),t=m__namespace.join(e,".last-update"),n=m__namespace.join(e,".force-update");try{if(Date.now()-p__namespace.statSync(n).mtimeMs<600*1e3)return}catch{}p__namespace.mkdirSync(e,{recursive:!0}),p__namespace.writeFileSync(n,String(Date.now()));try{p__namespace.rmSync(t,{force:!0});}catch{}ae(e);}catch{}}function Tn(){try{let e=m__namespace.join(R__namespace.homedir(),".config","opencrater");p__namespace.mkdirSync(e,{recursive:!0}),p__namespace.writeFileSync(m__namespace.join(e,"activity.signal"),String(Date.now()));}catch{}}var Rn=1440*60*1e3;function _n(){try{let e=m__namespace.join(R__namespace.homedir(),".config","opencrater"),t=m__namespace.join(e,".last-host-check"),n=m__namespace.join(e,".known-hosts"),r=ie().sort(),o=[];try{let c=JSON.parse(p__namespace.readFileSync(n,"utf8"));Array.isArray(c)&&(o=c.filter(a=>typeof a=="string"));}catch{}if(!r.some(c=>!o.includes(c)))try{if(Date.now()-p__namespace.statSync(t).mtimeMs<Rn)return}catch{}p__namespace.mkdirSync(e,{recursive:!0});try{p__namespace.writeFileSync(t,String(Date.now()));}catch{return}let s=ee();try{p__namespace.writeFileSync(n,JSON.stringify(r));}catch{}if(s.optOut)return;if(s.devToken)try{se();}catch{}for(let c of s.integrations)try{se(c.key,c.package);}catch{}}catch{}}async function On(){let e=pn(process.argv.slice(2));if(de=e.host,process.env.GROK_HOOK_EVENT&&de!=="grok_cli")return;Tn(),En(),_n();let t=await dn(ln),n={};if(t)try{n=JSON.parse(t);let u=n.hook_event_name;!e.placement&&typeof u=="string"&&(e.placement=u);}catch{}let r=e.placement??"SessionStart",o=ee();y(`state=${J()} devToken=${o.devToken?"present":"MISSING"}`,`host=${e.host} placement=${r}`);let i=Xe({env:process.env,state:o,now:Date.now()},{skipTTY:true});if(i!==null){if(i==="frequency"){let u=ue(n);u.length>0&&S({...o,sessionTopics:pe(o.sessionTopics,u,Date.now())});}y("hook suppressed:",i);return}if(o={...o,sessionTopics:pe(o.sessionTopics,ue(n),Date.now())},!vn(o,e.package,e.host,r)){S(o),y("hook gated: placement",r,"not selected for",e.package);return}let s=Q(o.cachedConfig),c=B(),a={origin:c,timeoutMs:Math.min(s.serveTimeoutMs,un),installId:o.installId,topics:Ze(o.sessionTopics,Date.now())};if(o.devToken){let u=await be(o.devToken,{publisherKey:e.key??"",packageName:e.package??"",placement:r,host:e.host},a);if(u){if(o={...o,cachedConfig:u.config,configFetchedAt:Date.now()},tt(I,u.config.minSdkVersion)&&nt(),an);let _=e.host??"claude_code",b=Fe(_,r),v=o.computeCards??{turns:0,lastLimitAt:0,lastDepletedAt:0,lastBackupAt:0};b&&(v.turns+=1);let k=Je({balanceMicroUsd:typeof u.computeBalanceMicroUsd=="number"?u.computeBalanceMicroUsd:null,weeklyGrantMicroUsd:typeof u.weeklyGrantMicroUsd=="number"?u.weeklyGrantMicroUsd:null,pendingMicroUsd:typeof u.pendingMicroUsd=="number"?u.pendingMicroUsd:null,onGateway:(process.env.ANTHROPIC_BASE_URL??"").includes("/gateway")||process.env.OPENCRATER_ON_GATEWAY==="1",turnEnd:b,hostName:_,host:Be(_),cc:v,now:Date.now()}),ot=(u.config.displayDurationSeconds??25)*1e3,O=u.fill&&u.blip&&!K(u.blip.campaignId)&&!W(u.blip.campaignId)?u.blip:null;if((k||O)&&!Qe(ot)&&et())if(k){let x=Date.now();k.kind==="limit"?v.lastLimitAt=x:k.kind==="depleted"?v.lastDepletedAt=x:k.kind==="backup"&&(v.lastBackupAt=x),o=await U({...k.card,label:"OpenCrater"},o);}else O&&(Y(O.campaignId),o=await U(F(O),o,O.creative,O.impressionId,O.campaignId,o.devToken?{kind:"dev",token:o.devToken}:void 0));o={...o,computeCards:v};}S(o);return}let{blip:l,pool:f}=ne(o,Date.now());for(;l&&(K(l.campaignId)||W(l.campaignId));)y("hook: pooled blip skipped \u2014 campaign inside a local cooldown"),{blip:l,pool:f}=ne({pool:f},Date.now());if((l||e.key)&&Qe((s.displayDurationSeconds??25)*1e3)){S(o),y("hook: a card is already on screen \u2014 not rendering another");return}if((l||e.key)&&!et()){S(o),y("hook: render slot already claimed by a concurrent fire");return}if(l){Y(l.campaignId),o=await U(F(l),{...o,pool:f},l.creative,l.impressionId,l.campaignId,{kind:"publisher"}),S(o);return}if(f.length!==o.pool.length&&(o={...o,pool:f}),!e.key||!e.package){S(o),y("hook: pool empty and no --key/--package; nothing to render");return}let d=await Se({publisherKey:e.key,packageName:e.package,placement:r,host:e.host},a);if(!d){S(o);return}if(o={...o,cachedConfig:d.config,configFetchedAt:Date.now()},tt(I,d.config.minSdkVersion)&&(y(`SDK ${I} below floor ${d.config.minSdkVersion} \u2014 forcing runtime update`),nt()),e.package&&d.allowedPlacements&&(o={...o,allowedPlacements:{...o.allowedPlacements,[`${e.package}:${e.host}`]:d.allowedPlacements}}),d.fill&&d.blip){if(K(d.blip.campaignId)||W(d.blip.campaignId)){y("hook: served blip suppressed \u2014 campaign inside a local cooldown"),S(o);return}Y(d.blip.campaignId),o=await U(F(d.blip),o,d.blip.creative,d.blip.impressionId,d.blip.campaignId,{kind:"publisher"}),S(o);return}d.fallback&&(o=await U(we(d.fallback),o)),S(o);}if(typeof P<"u"&&typeof module<"u"&&P.main===module){let e=setTimeout(()=>process.exit(0),cn);On().catch(t=>y(`opencrater-hook v${I} error:`,t)).finally(()=>{clearTimeout(e),process.exit(0);});}
12
- exports.decodeTtyNr=hn;exports.painterSpawnOptions=kn;exports.parseArgs=pn;exports.parseProcStat=yn;exports.parsePsLine=gn;exports.resolveTtyPath=bn;exports.ttyNameToDevPath=mn;
12
+ `;}return o}function Xt(t){try{let o=b__namespace.join(pe("grok_cli",t),"config.toml"),e="";try{e=h__namespace.readFileSync(o,"utf8");}catch{}let r=Vt(e);if(r===e)return;h__namespace.mkdirSync(b__namespace.dirname(o),{recursive:!0}),h__namespace.writeFileSync(o,r,"utf8");}catch{}}function Zt(t,o,e){let r=Ve(t);return r.length===0?"nochange":(t==="grok_cli"&&Xt(process.env),t==="copilot_cli"?Yt(t,o,e,r):Jt(t,o,e,r))}function ge(t,o,e=process.env){return me(e).map(r=>{try{let n=Zt(r,t,o);return {host:r,status:n,events:Ve(r)}}catch(n){return {host:r,status:"error",events:[],error:n.message}}})}function en(){return b__namespace.join(I__namespace.homedir(),".config","opencrater","runtime")}function tn(t){return ["install","--prefix",t,"opencrater@latest","--silent","--no-audit","--no-fund"]}function he(t=en()){child_process.spawn("npm",tn(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=I__namespace.homedir()){try{if(t==="claude_code")return nn(o);if(t==="codex")return on(o)}catch{}return et}function nn(t){let o=h__namespace.readFileSync(b__namespace.join(t,".claude.json"),"utf8"),e=JSON.parse(o),r=e.hasAvailableSubscription===false||e.cachedExtraUsageDisabledReason==="out_of_credits",n=null,u=e.cachedGrowthBookFeatures?.tengu_saffron_lattice?.planLimitsEndDate;if(typeof u=="string"){let d=Date.parse(u);Number.isFinite(d)&&(n=d);}return {atLimit:r,resetAt:n}}function on(t){return h__namespace.accessSync(b__namespace.join(t,".codex","auth.json")),et}function nt(t,o){switch(t){case "antigravity":return o==="AfterAgent";case "copilot_cli":return o==="agentStop";default:return o==="Stop"}}var ot=36e5,rn=30*6e4,sn=30*6e4,an=4*ot,cn=3,ne="https://opencrater.to/dashboard";function F(t){return `${Math.round(t/1e3).toLocaleString()} tokens`}function ln(t){let o=t/1e3;return o>0&&o<10?`${(Math.round(o*10)/10).toFixed(1)} tokens`:`${Math.round(o).toLocaleString()} tokens`}function fn(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 oe="opencrater claude";function un(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:u,now:d}=t;if(o===null)return null;let a=fn(c),p=e&&e>0?` (+${ln(e)} pending)`:"";return o<=0?d-(u.lastDepletedAt??0)<sn?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"}.`+un(f.resetAt,d),url:ne,cta:"Earn more"}}:r?!n||(u.turns??0)%cn!==0?null:{kind:"hud",card:{sponsorLabel:"OpenCrater",title:"Running on OpenCrater compute",body:`${F(o)} compute available${p}.`,url:ne,cta:"Wallet"}}:f.atLimit?d-(u.lastLimitAt??0)<rn?null:{kind:"limit",card:{sponsorLabel:"OpenCrater",title:"Hit your limit? You've got compute",body:a?`${F(o)} of OpenCrater compute is ready. Continue this ${a.name} session now: ${a.resume}`:`${F(o)} of OpenCrater compute is ready. Run your coding agent on it: ${oe}`,url:ne,cta:a?a.resume:oe}}:d-(u.lastBackupAt??0)>=an?{kind:"backup",card:{sponsorLabel:"OpenCrater",title:"Backup compute ready",body:a?`${F(o)} of OpenCrater compute waiting${p}. When you hit your limit: ${a.resume}`:`${F(o)} of OpenCrater compute waiting${p}. Spend it any time: ${oe}`,url:ne,cta:a?a.resume:oe}}:null}var gn=["CI","CONTINUOUS_INTEGRATION","GITHUB_ACTIONS","GITLAB_CI","CIRCLECI","TRAVIS","BUILDKITE","JENKINS_URL","TEAMCITY_VERSION","TF_BUILD","APPVEYOR","CODEBUILD_BUILD_ID","DRONE","NETLIFY","VERCEL"];function be(t){return t!==void 0&&t!==""&&t!=="0"&&t.toLowerCase()!=="false"}function hn(t){return be(t.OPENCRATER_DISABLE)||be(t.TSN_DISABLE)}function yn(t){return gn.some(o=>be(t[o]))}function ie(t){return t?{...B,...t}:B}function ut(t,o={}){if(hn(t.env))return "env_disabled";if(t.state.optOut)return "opt_out";let e=ie(t.state.cachedConfig);if(e.killSwitch)return "kill_switch";if(yn(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 bn=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 kn(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 wn(t,o=12){let e=[];for(let r of t.slice(0,2e3).split(/\s+/))if(!(!r||kn(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)||bn.has(c))&&!e.includes(c)&&(e.push(c),e.length>=o))return e}return e}function ke(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 wn(o.join(" "))}function we(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 xn=false,Cn=process.platform==="win32"?8e3:3200,Tn=150,jn=2800,Se="claude_code";function Rn(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 En(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 On(t){return !t||t==="?"||t==="??"||t==="-"?null:t.startsWith("/")?t:`/dev/${t}`}function An(t){let o=t.match(/^\s*(\d+)\s+(\S+)/);return o?{ppid:Number(o[1]),tty:o[2]}:null}function Pn(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 In(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 Nn(t){try{let o=In(h__namespace.readFileSync(`/proc/${t}/stat`,"utf8"));if(o)return {ppid:o.ppid,ttyPath:Pn(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=An(o);return e?{ppid:e.ppid,ttyPath:On(e.tty)}:null}catch{return null}}function $n(){if(process.platform==="win32")return {path:_n,ownerPid:null};let t=process.pid;for(let o=0;o<12&&t>1;o++){let e=Nn(t);if(!e)return null;if(e.ttyPath)return {path:e.ttyPath,ownerPid:t};t=e.ppid;}return null}function Mn(t){return t==="win32"?{detached:false,stdio:"ignore",windowsHide:false}:{detached:true,stdio:"ignore",windowsHide:false}}async function q(t,o,e,r,n,c){try{let f=b__namespace.join(__dirname,"paint.js"),u,d;if(c&&r){let g=G();c.kind==="dev"?(u=`${g}/v1/dev/impression`,d=c.token):u=`${g}/v1/events/impression`;}let a=ie(o.cachedConfig),p=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:G(),reportImpressionUrl:u,reportImpressionAuth:d,durationMs:p*1e3,disclosure:!o.disclosureShown,host:Se},i={...process.env,OPENCRATER_PAINT:JSON.stringify(s)};if(!i.OPENCRATER_TTY){let g=$n();g&&(i.OPENCRATER_TTY=g.path,g.ownerPid!==null&&(i.OPENCRATER_HOST_PID=String(g.ownerPid)));}let y=child_process.spawn(process.execPath,[f],{...Mn(process.platform),env:i});process.platform==="win32"?await new Promise(g=>{let m=!1,l=()=>{m||(m=!0,g());};y.on("exit",l),y.on("error",l),setTimeout(l,7500);}):y.unref();}catch{}return {...o,lastShownAt:Date.now(),disclosureShown:true}}function pt(t){if(process.platform!=="win32")return false;try{let o=b__namespace.join(I__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 Ln=8e3;function mt(){let t=b__namespace.join(I__namespace.homedir(),".config","opencrater","render.lock");try{let o=h__namespace.statSync(t);if(Date.now()-o.mtimeMs<Ln)return !1;h__namespace.unlinkSync(t);}catch{}try{return h__namespace.mkdirSync(b__namespace.join(I__namespace.homedir(),".config","opencrater"),{recursive:!0}),h__namespace.writeFileSync(t,String(process.pid),{flag:"wx"}),!0}catch{return false}}function Dn(t,o,e,r){if(!o)return true;let n=t.allowedPlacements[`${o}:${e}`];return n?n.includes(r):o==="opencrater"?Te[e].includes(r):true}var Wn=1440*60*1e3;function Bn(){try{let t=b__namespace.join(I__namespace.homedir(),".config","opencrater","runtime"),o=b__namespace.join(t,"node_modules","opencrater","dist","hook.js"),e=b__namespace.join(t,".last-update");if(h__namespace.existsSync(o)){try{if(Date.now()-h__namespace.statSync(e).mtimeMs<Wn)return}catch{}try{h__namespace.writeFileSync(e,String(Date.now()));}catch{return}}else {let r=b__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()));}he(t);}catch{}}function gt(t,o){if(!o)return false;let e=f=>f.split(/[-+]/)[0].split(".").map(u=>parseInt(u,10)||0),r=e(t),n=e(o),c=Math.max(r.length,n.length);for(let f=0;f<c;f++){let u=r[f]??0,d=n[f]??0;if(u!==d)return u<d}return false}function ht(){try{let t=b__namespace.join(I__namespace.homedir(),".config","opencrater","runtime"),o=b__namespace.join(t,".last-update"),e=b__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{}he(t);}catch{}}function Hn(){try{let t=b__namespace.join(I__namespace.homedir(),".config","opencrater");h__namespace.mkdirSync(t,{recursive:!0}),h__namespace.writeFileSync(b__namespace.join(t,"activity.signal"),String(Date.now()));}catch{}}var Un=1440*60*1e3;function Fn(){try{let t=b__namespace.join(I__namespace.homedir(),".config","opencrater"),o=b__namespace.join(t,".last-host-check"),e=b__namespace.join(t,".known-hosts"),r=me().sort(),n=[];try{let u=JSON.parse(h__namespace.readFileSync(e,"utf8"));Array.isArray(u)&&(n=u.filter(d=>typeof d=="string"));}catch{}if(!r.some(u=>!n.includes(u)))try{if(Date.now()-h__namespace.statSync(o).mtimeMs<Un)return}catch{}h__namespace.mkdirSync(t,{recursive:!0});try{h__namespace.writeFileSync(o,String(Date.now()));}catch{return}let f=le();try{h__namespace.writeFileSync(e,JSON.stringify(r));}catch{}if(f.optOut)return;if(f.devToken)try{ge();}catch{}for(let u of f.integrations)try{ge(u.key,u.package);}catch{}}catch{}}async function qn(){let t=Rn(process.argv.slice(2));if(Se=t.host,process.env.GROK_HOOK_EVENT&&Se!=="grok_cli")return;Hn(),Bn(),Fn();let o=await En(Tn),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=le();x(`state=${V()} 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=ke(e);m.length>0&&C({...n,sessionTopics:we(n.sessionTopics,m,Date.now())});}x("hook suppressed:",c);return}if(n={...n,sessionTopics:we(n.sessionTopics,ke(e),Date.now())},!Dn(n,t.package,t.host,r)){C(n),x("hook gated: placement",r,"not selected for",t.package);return}let f=ie(n.cachedConfig),u=G(),d=typeof e?.cwd=="string"&&e.cwd||process.cwd(),a=Pe(d),p=n.attrTags??[];if(n.attrTagsCwd!==a||!n.attrTagsAt||Date.now()-n.attrTagsAt>J){try{p=Ie(d);}catch{p=[];}n={...n,attrTags:p,attrTagsCwd:a,attrTagsAt:Date.now()};}let s={origin:u,timeoutMs:Math.min(f.serveTimeoutMs,jn),installId:n.installId,topics:dt(n.sessionTopics,Date.now()),tags:p};if(n.devToken){let m=await Ae(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(N,m.config.minSdkVersion)&&ht(),xn);let l=t.host??"claude_code",A=nt(l,r),k=n.computeCards??{turns:0,lastLimitAt:0,lastDepletedAt:0,lastBackupAt:0};A&&(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:A,hostName:l,host:tt(l),cc:k,now:Date.now()}),se=(m.config.displayDurationSeconds??25)*1e3,T=m.fill&&m.blip&&!X(m.blip.campaignId)&&!Q(m.blip.campaignId)?m.blip:null;if((j||T)&&!pt(se)&&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 q({...j.card,label:"OpenCrater"},n);}else T&&(Z(T.campaignId),n=await q(K(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:y}=ue(n,Date.now());for(;i&&(X(i.campaignId)||Q(i.campaignId));)x("hook: pooled blip skipped \u2014 campaign inside a local cooldown"),{blip:i,pool:y}=ue({pool:y},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){Z(i.campaignId),n=await q(K(i),{...n,pool:y},i.creative,i.impressionId,i.campaignId,{kind:"publisher"}),C(n);return}if(y.length!==n.pool.length&&(n={...n,pool:y}),!t.key||!t.package){C(n),x("hook: pool empty and no --key/--package; nothing to render");return}let g=await Oe({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(N,g.config.minSdkVersion)&&(x(`SDK ${N} 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(X(g.blip.campaignId)||Q(g.blip.campaignId)){x("hook: served blip suppressed \u2014 campaign inside a local cooldown"),C(n);return}Z(g.blip.campaignId),n=await q(K(g.blip),n,g.blip.creative,g.blip.impressionId,g.blip.campaignId,{kind:"publisher"}),C(n);return}g.fallback&&(n=await q($e(g.fallback),n)),C(n);}if(typeof M<"u"&&typeof module<"u"&&M.main===module){let t=setTimeout(()=>process.exit(0),Cn);qn().catch(o=>x(`opencrater-hook v${N} error:`,o)).finally(()=>{clearTimeout(t),process.exit(0);});}
13
+ exports.decodeTtyNr=Pn;exports.painterSpawnOptions=Mn;exports.parseArgs=Rn;exports.parseProcStat=In;exports.parsePsLine=An;exports.resolveTtyPath=$n;exports.ttyNameToDevPath=On;
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
1
  /** Host environment the SDK is running inside. */
2
- type Host = "claude_code" | "codex" | "openclaw" | "gemini_cli" | "copilot_cli" | "grok_cli" | "generic";
2
+ type Host = "claude_code" | "codex" | "openclaw" | "antigravity" | "copilot_cli" | "grok_cli" | "generic";
3
3
  /** Creative formats the serve API can return. Text always renders; rich
4
4
  * media degrades to the text fallback when the terminal can't display it. */
5
5
  type CreativeFormat = "text" | "logo" | "image" | "gif" | "video" | "audio";
@@ -110,6 +110,11 @@ interface OpenCraterState {
110
110
  topic: string;
111
111
  at: number;
112
112
  }[];
113
+ /** Cached developer-attribute tags (ns:value) detected from the project,
114
+ * keyed by the cwd they were scanned from, with a timestamp for TTL. */
115
+ attrTags?: string[];
116
+ attrTagsCwd?: string;
117
+ attrTagsAt?: number;
113
118
  /**
114
119
  * Publisher integrations wired on this machine: each is the (key, package)
115
120
  * a `opencrater on --key … --package …` ran with. The auto-integrator
@@ -227,7 +232,7 @@ declare function renderBlip(blip: Blip, opts?: MediaRenderOptions): Promise<stri
227
232
 
228
233
  /** Keep in sync with package.json (bundled, so we avoid a runtime fs read).
229
234
  * AUTO-GENERATED by scripts/sync-version.mjs on `npm version`. */
230
- declare const SDK_VERSION = "1.1.42";
235
+ declare const SDK_VERSION = "1.3.0";
231
236
 
232
237
  /** Public API. Every method is fail-silent: it never throws. */
233
238
  declare const sponsor: {
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /** Host environment the SDK is running inside. */
2
- type Host = "claude_code" | "codex" | "openclaw" | "gemini_cli" | "copilot_cli" | "grok_cli" | "generic";
2
+ type Host = "claude_code" | "codex" | "openclaw" | "antigravity" | "copilot_cli" | "grok_cli" | "generic";
3
3
  /** Creative formats the serve API can return. Text always renders; rich
4
4
  * media degrades to the text fallback when the terminal can't display it. */
5
5
  type CreativeFormat = "text" | "logo" | "image" | "gif" | "video" | "audio";
@@ -110,6 +110,11 @@ interface OpenCraterState {
110
110
  topic: string;
111
111
  at: number;
112
112
  }[];
113
+ /** Cached developer-attribute tags (ns:value) detected from the project,
114
+ * keyed by the cwd they were scanned from, with a timestamp for TTL. */
115
+ attrTags?: string[];
116
+ attrTagsCwd?: string;
117
+ attrTagsAt?: number;
113
118
  /**
114
119
  * Publisher integrations wired on this machine: each is the (key, package)
115
120
  * a `opencrater on --key … --package …` ran with. The auto-integrator
@@ -227,7 +232,7 @@ declare function renderBlip(blip: Blip, opts?: MediaRenderOptions): Promise<stri
227
232
 
228
233
  /** Keep in sync with package.json (bundled, so we avoid a runtime fs read).
229
234
  * AUTO-GENERATED by scripts/sync-version.mjs on `npm version`. */
230
- declare const SDK_VERSION = "1.1.42";
235
+ declare const SDK_VERSION = "1.3.0";
231
236
 
232
237
  /** Public API. Every method is fail-silent: it never throws. */
233
238
  declare const sponsor: {
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
- 'use strict';var crypto=require('crypto'),f=require('fs'),te=require('os'),C=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 f__namespace=/*#__PURE__*/_interopNamespace(f);var te__namespace=/*#__PURE__*/_interopNamespace(te);var C__namespace=/*#__PURE__*/_interopNamespace(C);var F=(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 b={minIntervalSeconds:600,serveTimeoutMs:2500,preloadPoolSize:3,killSwitch:false,displayDurationSeconds:25,minSdkVersion:""};var se=["SessionStart","SessionEnd","Stop","PostToolUse","Notification"];var D="1.1.42";var ae="https://api.opencrater.to";function V(e,t=process.env){let n=t.OPENCRATER_API_ORIGIN;return (e??(n&&n.trim()!==""?n:ae)).replace(/\/+$/,"")}function c(...e){try{if(process.env.OPENCRATER_DEBUG!=="1")return;console.error("[opencrater]",...e);try{let t=F("os"),n=F("fs"),r=F("path");n.appendFileSync(r.join(t.homedir(),".config","opencrater","hook.log"),`${new Date().toISOString()} [opencrater] ${e.map(o=>String(o)).join(" ")}
2
- `);}catch{}}catch{}}function v(e){return typeof e=="number"&&Number.isFinite(e)}function W(e){let t=b;if(typeof e!="object"||e===null)return {...t};let n=e;return {minIntervalSeconds:v(n.minIntervalSeconds)?n.minIntervalSeconds:t.minIntervalSeconds,serveTimeoutMs:v(n.serveTimeoutMs)?n.serveTimeoutMs:t.serveTimeoutMs,preloadPoolSize:v(n.preloadPoolSize)?n.preloadPoolSize:t.preloadPoolSize,killSwitch:n.killSwitch===true,displayDurationSeconds:v(n.displayDurationSeconds)?n.displayDurationSeconds:t.displayDurationSeconds,minSdkVersion:typeof n.minSdkVersion=="string"?n.minSdkVersion:t.minSdkVersion}}async function U(e,t,n,r,o){try{let i=await fetch(`${e}${t}`,{method:"POST",headers:{"content-type":"application/json",...o??{}},body:JSON.stringify(n),signal:AbortSignal.timeout(r)});return i.ok?await i.json():(c(`POST ${t} -> HTTP ${i.status}`),null)}catch(i){return c(`POST ${t} failed:`,i),null}}function q(e,t){let n=e.host??"generic";return {publisherKey:e.publisherKey,packageName:e.packageName,placement:e.placement,host:n,sdkVersion:D,installId:t.installId,os:process.platform,termProgram:process.env.TERM_PROGRAM??void 0,topics:t.topics&&t.topics.length>0?t.topics:void 0}}function le(e){if(typeof e!="object"||e===null)return null;let t=e;if(typeof t.fill!="boolean")return null;let n={fill:t.fill,fallback:t.fallback??null,config:W(t.config),...Array.isArray(t.allowedPlacements)?{allowedPlacements:t.allowedPlacements.filter(r=>typeof r=="string")}:{}};return t.blip!==void 0&&t.blip!==null&&(n.blip=t.blip),typeof t.computeBalanceMicroUsd=="number"&&(n.computeBalanceMicroUsd=t.computeBalanceMicroUsd),typeof t.weeklyGrantMicroUsd=="number"&&(n.weeklyGrantMicroUsd=t.weeklyGrantMicroUsd),typeof t.pendingMicroUsd=="number"&&(n.pendingMicroUsd=t.pendingMicroUsd),n}async function j(e,t){let n=await U(t.origin,"/v1/serve",q(e,t),t.timeoutMs);return le(n)}async function J(e,t,n){let r=await U(n.origin,"/v1/serve/batch",{...q(e,n),count:t},n.timeoutMs);if(typeof r!="object"||r===null)return null;let o=r;return Array.isArray(o.blips)?{blips:o.blips,fallback:o.fallback??null,config:W(o.config),...Array.isArray(o.allowedPlacements)?{allowedPlacements:o.allowedPlacements.filter(i=>typeof i=="string")}:{}}:null}function Y(e,t){return U(t.origin,"/v1/events/impression",{impressionId:e},t.timeoutMs).then(()=>{}).catch(()=>{})}var ce=new RegExp("\x1B\\[[0-9;]*m|\x1B\\]8;;[^\x07\x1B]*(?:\x07|\x1B\\\\)","g"),k={dim:"\x1B[2m",bold:"\x1B[1m",reset:"\x1B[0m"},ue=60,pe=24,de="\u2139 This project is supported by Blips via OpenCrater. Opt out: `npx opencrater off` or OPENCRATER_DISABLE=1";function fe(e){return e.replace(ce,"").length}function y(e,t){return t<=0?"":e.length<=t?e:t===1?"\u2026":e.slice(0,t-1).trimEnd()+"\u2026"}function me(e,t,n){let r=e.split(/\s+/).filter(l=>l.length>0),o=[],i="";for(let l of r){let p=i===""?l:`${i} ${l}`;if(p.length<=t)i=p;else if(i!==""&&o.push(i),i=l.length>t?y(l,t):l,o.length>=n)break}i!==""&&o.length<n&&o.push(i),o.length>n&&(o.length=n);let s=o.join(" "),a=o.length-1,u=o[a];return u!==void 0&&s.length<r.join(" ").length&&(o[a]=y(`${u}\u2026`,t)),o}function O(e=process.env,t=!!process.stdout.isTTY){if(!t)return false;if(e.FORCE_HYPERLINK!==void 0&&e.FORCE_HYPERLINK!=="0")return true;let n=e.TERM_PROGRAM??"";return !!(["iTerm.app","WezTerm","ghostty","Hyper","vscode","Tabby"].includes(n)||e.KITTY_WINDOW_ID||e.WT_SESSION||Number(e.VTE_VERSION??"0")>=5e3)}function P(e=process.env,t=!!process.stdout.isTTY){return !(e.NO_COLOR!==void 0&&e.NO_COLOR!==""||!t||(e.TERM??"")==="dumb")}function ge(e,t){return `\x1B]8;;${e}\x07${t}\x1B]8;;\x07`}function A(e){let t={sponsorLabel:e.sponsorLabel,title:e.creative.title,body:e.creative.body,url:e.clickUrl};return e.creative.cta!==void 0&&(t.cta=e.creative.cta),t}function X(e){return {sponsorLabel:"",title:e.title,body:e.body,url:e.url}}function g(e,t={}){let n=t.width??process.stdout.columns??80,o=Math.max(pe,Math.min(n,ue))-4,i=t.color??P(),s=t.hyperlinks??O(),a=(m,$)=>i?`${$}${m}${k.reset}`:m,u=e.label?y(e.label,o):e.sponsorLabel?y(`Sponsored Blips \xB7 ${e.sponsorLabel}`,o):"Sponsored Blips",l=[];l.push(a(u,k.dim)),e.title!==e.sponsorLabel&&l.push(a(y(e.title,o),k.bold));for(let m of me(e.body,o,2))l.push(m);let p="\u2192 ";if(s){let m=y(e.cta??e.url,o-p.length);l.push(p+a(ge(e.url,m),k.dim));}else e.cta&&l.push(y(e.cta,o)),l.push(p+a(y(e.url,o-p.length),k.dim));let R=`\u256D${"\u2500".repeat(o+2)}\u256E`,E=`\u2570${"\u2500".repeat(o+2)}\u256F`,L=l.map(m=>{let $=" ".repeat(Math.max(0,o-fe(m)));return `\u2502 ${m}${$} \u2502`}),h=[];return t.disclosure&&h.push(a(de,k.dim)),h.push(R,...L,E),h.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.3.0";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(`
3
3
  `)+`
4
- `}function Z(e){return e!==void 0&&e!==""}function G(e=process.env,t=!!process.stdout.isTTY){if(!t)return "none";let n=e.TERM??"";if(Z(e.TMUX)||n.startsWith("tmux")||n.startsWith("screen"))return "none";let r=e.TERM_PROGRAM??"";return r==="iTerm.app"||e.LC_TERMINAL==="iTerm2"||r==="WezTerm"?"iterm2":n==="xterm-kitty"||Z(e.KITTY_WINDOW_ID)?"kitty":"none"}var w="\x1B",Se="\x07",ye=2e3,he=2*1024*1024,be=new Set(["image/png","image/jpeg","image/gif","image/webp"]),x=4096;async function ke(e,t=fetch,n={}){let r=n.timeoutMs??ye,o=n.maxBytes??he;try{let i=await t(e,{signal:AbortSignal.timeout(r)});if(!i.ok)return c(`media: HTTP ${i.status} for ${e}`),null;let s=(i.headers.get("content-type")??"").split(";")[0].trim().toLowerCase();if(!be.has(s))return c(`media: disallowed content-type "${s}" for ${e}`),null;let a=Number(i.headers.get("content-length")??"0");if(Number.isFinite(a)&&a>o)return c(`media: content-length ${a} exceeds ${o} for ${e}`),null;let u=i.body;if(u&&typeof u.getReader=="function"){let p=u.getReader(),R=[],E=0;for(;;){let{done:L,value:h}=await p.read();if(L)break;if(h!==void 0){if(E+=h.byteLength,E>o)return await p.cancel().catch(()=>{}),c(`media: stream exceeded ${o} bytes for ${e}`),null;R.push(h);}}return Buffer.concat(R)}let l=Buffer.from(await i.arrayBuffer());return l.byteLength>o?(c(`media: body ${l.byteLength} bytes exceeds ${o} for ${e}`),null):l}catch(i){return c(`media: fetch failed for ${e}:`,i),null}}function Ce(e){let t=e.toString("base64");return `${w}]1337;File=inline=1;size=${e.byteLength};width=auto:${t}${Se}`}function we(e){let t=e.toString("base64");if(t.length<=x)return `${w}_Gf=100,a=T;${t}${w}\\`;let n=[];for(let r=0;r<t.length;r+=x){let o=t.slice(r,r+x),s=`m=${r+x>=t.length?0:1}`,a=r===0?`f=100,a=T,${s}`:s;n.push(`${w}_G${a};${o}${w}\\`);}return n.join("")}function B(e){let t=A(e),n=e.creative;switch(n.format){case "image":case "gif":return {...t,body:n.textFallback??t.body};case "video":return {...t,body:n.textFallback??t.body,cta:t.cta??"\u25B6 Watch"};case "audio":return {...t,body:n.textFallback??t.body,cta:t.cta??"\u{1F50A} Listen"};default:return t}}async function H(e,t={}){try{let n=e.creative;if(n.format!=="image"&&n.format!=="gif")return g(B(e),t);let r=t.protocol??G();if(r==="none"||n.mediaUrl===void 0||n.mediaUrl==="")return g(B(e),t);let o={};t.timeoutMs!==void 0&&(o.timeoutMs=t.timeoutMs),t.maxBytes!==void 0&&(o.maxBytes=t.maxBytes);let i=await ke(n.mediaUrl,t.fetchImpl??fetch,o);return i===null||i.byteLength===0?g(B(e),t):(r==="kitty"?we(i):Ce(i))+`
5
- `+g(A(e),t)}catch(n){return c("media: render failed, falling back to text:",n),g(A(e),t)}}function Te(e,t){return e.filter(n=>n.renderBy>t)}function Q(e,t,n=18e5){return e.filter(r=>r&&typeof r.impressionId=="string"&&typeof r.clickUrl=="string"&&r.creative&&typeof r.creative.title=="string").map(r=>({blip:r,renderBy:t+n}))}function ee(e,t){let n=Te(e.pool,t),r=n.shift();return {blip:r?r.blip:null,pool:n}}function Re(e=process.env){return C__namespace.join(te__namespace.homedir(),".config","opencrater")}function ne(e=process.env){return C__namespace.join(Re(e),"state.json")}function _(){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 S(e){return typeof e=="number"&&Number.isFinite(e)}var oe=new Set(["EPERM","EACCES","EBUSY","EEXIST"]);function re(e){for(let t=0;;t++)try{return {text:f__namespace.readFileSync(e,"utf8")}}catch(n){let r=n.code??"";if(!(r==="ENOENT"||oe.has(r)))return {locked:true};if(t>=4)return r==="ENOENT"?{missing:true}:{locked:true};try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(t+1));}catch{}}}function Ee(e){if(typeof e!="object"||e===null)return null;let t=e;return !S(t.minIntervalSeconds)||!S(t.serveTimeoutMs)||!S(t.preloadPoolSize)||typeof t.killSwitch!="boolean"?null:{minIntervalSeconds:t.minIntervalSeconds,serveTimeoutMs:t.serveTimeoutMs,preloadPoolSize:t.preloadPoolSize,killSwitch:t.killSwitch,displayDurationSeconds:S(t.displayDurationSeconds)?t.displayDurationSeconds:25,minSdkVersion:typeof t.minSdkVersion=="string"?t.minSdkVersion:""}}function ve(e){if(!Array.isArray(e))return [];let t=[];for(let n of e){if(typeof n!="object"||n===null)continue;let r=n,o=r.blip;if(!S(r.renderBy)||typeof o!="object"||o===null||typeof o.impressionId!="string"||typeof o.clickUrl!="string"||typeof o.sponsorLabel!="string"||typeof o.creative!="object"||o.creative===null)continue;let i=o.creative;typeof i.title!="string"||typeof i.body!="string"||t.push({blip:{impressionId:o.impressionId,...typeof o.campaignId=="string"?{campaignId:o.campaignId}:{},clickUrl:o.clickUrl,sponsorLabel:o.sponsorLabel,creative:{format:"text",title:i.title,body:i.body,...typeof i.cta=="string"?{cta:i.cta}:{}}},renderBy:r.renderBy});}return t}function Oe(e){if(typeof e!="object"||e===null||Array.isArray(e))return {};let t={};for(let[n,r]of Object.entries(e)){if(!Array.isArray(r))continue;let o=r.filter(i=>typeof i=="string"&&i.length<=64);t[n]=o.slice(0,64);}return t}function Pe(e){if(!Array.isArray(e))return [];let t=[];for(let n of e){if(typeof n!="object"||n===null)continue;let r=n;if(!(typeof r.topic!="string"||!S(r.at))&&(t.push({topic:r.topic.slice(0,32),at:r.at}),t.length>=24))break}return t}function Ae(e){if(!Array.isArray(e))return [];let t=[],n=new Set;for(let r of e){if(typeof r!="object"||r===null)continue;let o=r;if(typeof o.key!="string"||typeof o.package!="string"||o.key===""||o.package==="")continue;let i=`${o.package}\0${o.key}`;if(!n.has(i)&&(n.add(i),t.push({key:o.key,package:o.package}),t.length>=32))break}return t}function xe(e){if(typeof e!="object"||e===null)return null;let t=e,n={};if(typeof t.savedEnv=="object"&&t.savedEnv!==null)for(let[r,o]of Object.entries(t.savedEnv))(typeof o=="string"||o===null)&&(n[r]=o);return {active:t.active===true,savedEnv:n}}function Be(e){if(typeof e!="object"||e===null)return null;let t=e,n=r=>S(r)&&r>=0?r:0;return {turns:n(t.turns),lastLimitAt:n(t.lastLimitAt),lastDepletedAt:n(t.lastDepletedAt),lastBackupAt:n(t.lastBackupAt)}}function _e(e){let t=_();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:S(n.lastShownAt)&&n.lastShownAt>=0?n.lastShownAt:0,optOut:n.optOut===true,disclosureShown:n.disclosureShown===true,cachedConfig:Ee(n.cachedConfig),allowedPlacements:Oe(n.allowedPlacements),sessionTopics:Pe(n.sessionTopics),integrations:Ae(n.integrations),devToken:typeof n.devToken=="string"?n.devToken:null,computeRouting:xe(n.computeRouting),computeCards:Be(n.computeCards),configFetchedAt:S(n.configFetchedAt)&&n.configFetchedAt>=0?n.configFetchedAt:0,pool:ve(n.pool)}}function T(e=process.env){let t=ne(e),n=re(t);if(n.text!==void 0)try{return _e(JSON.parse(n.text))}catch{let r=_();try{d(r,e);}catch{}return r}if(n.missing){let r=_();try{d(r,e);}catch{}return r}return _()}function d(e,t=process.env,n={}){let r=ne(t),o=C__namespace.dirname(r);f__namespace.mkdirSync(o,{recursive:true});let i=re(r),s=null;if(i.text!==void 0)try{s=JSON.parse(i.text);}catch{s=null;}if(s)typeof s.lastShownAt=="number"&&s.lastShownAt>e.lastShownAt&&(e={...e,lastShownAt:s.lastShownAt}),!n.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(!n.allowClearToken&&e.devToken==null&&i.text===void 0&&!i.missing)return;let a=C__namespace.join(o,`.state.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`);f__namespace.writeFileSync(a,JSON.stringify(e,null,2)+`
6
- `,"utf8");for(let u=0;;u++)try{f__namespace.renameSync(a,r);return}catch(l){let p=l.code??"";if(u>=4||!oe.has(p)){try{f__namespace.rmSync(a,{force:!0});}catch{}if(u>=4)return;throw l}try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(u+1));}catch{}}}var Me=["CI","CONTINUOUS_INTEGRATION","GITHUB_ACTIONS","GITLAB_CI","CIRCLECI","TRAVIS","BUILDKITE","JENKINS_URL","TEAMCITY_VERSION","TF_BUILD","APPVEYOR","CODEBUILD_BUILD_ID","DRONE","NETLIFY","VERCEL"];function z(e){return e!==void 0&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}function Ne(e){return z(e.OPENCRATER_DISABLE)||z(e.TSN_DISABLE)}function Le(e){return Me.some(t=>z(e[t]))}function K(e){return e?{...b,...e}:b}function I(e,t={}){if(Ne(e.env))return "env_disabled";if(e.state.optOut)return "opt_out";let n=K(e.state.cachedConfig);if(n.killSwitch)return "kill_switch";if(Le(e.env))return "ci";if(!t.skipTTY&&!e.isTTY)return "not_tty";if(!t.skipFrequency){let r=n.minIntervalSeconds*1e3;if(e.state.lastShownAt>0&&e.now-e.state.lastShownAt<r)return "frequency"}return null}async function M(e){try{return await e()}catch(t){return c("suppressed error:",t),null}}function N(e,t){let n=K(t.cachedConfig);return {origin:V(e.apiOrigin),timeoutMs:n.serveTimeoutMs,installId:t.installId,config:n}}function $e(e,t){let n=!t.disclosureShown,r=g(e,{width:process.stdout.columns??80,color:P(),hyperlinks:O(),disclosure:n});return process.stdout.write(r),{...t,lastShownAt:Date.now(),disclosureShown:true}}async function ie(e,t){let n=await H(e,{width:process.stdout.columns??80,color:P(),hyperlinks:O(),disclosure:!t.disclosureShown});return process.stdout.write(n),{...t,lastShownAt:Date.now(),disclosureShown:true}}async function Fe(e){let t=T(),n=I({env:process.env,isTTY:!!process.stdout.isTTY,state:t,now:Date.now()},{skipFrequency:true});if(n!==null)return c("fetch suppressed:",n),null;let r=N(e,t),o=await j(e,r);return o?(d({...t,cachedConfig:o.config,configFetchedAt:Date.now()}),o.fill&&o.blip?o.blip:null):null}async function De(e){let t=T(),n=I({env:process.env,isTTY:!!process.stdout.isTTY,state:t,now:Date.now()});if(n!==null)return c("suppressed:",n),false;let r=N(e,t),o=await j(e,r);return o?(t={...t,cachedConfig:o.config,configFetchedAt:Date.now()},o.fill&&o.blip?(t=await ie(o.blip,t),d(t),Y(o.blip.impressionId,r),true):o.fallback?(t=$e(X(o.fallback),t),d(t),true):(d(t),false)):false}async function Ue(e){let t=T(),n=I({env:process.env,isTTY:!!process.stdout.isTTY,state:t,now:Date.now()},{skipTTY:true,skipFrequency:true});if(n!==null)return c("preload suppressed:",n),0;let r=N(e,t),o=Math.max(1,r.config.preloadPoolSize),i=await J(e,o,r);if(!i)return 0;let s=Date.now(),a=Q(i.blips,s);return d({...t,pool:a,cachedConfig:i.config,configFetchedAt:s}),a.length}async function je(e){let t=T(),n=Date.now(),r=I({env:process.env,isTTY:!!process.stdout.isTTY,state:t,now:n});if(r!==null)return c("renderFromPool suppressed:",r),false;let{blip:o,pool:i}=ee(t,n);if(!o)return d({...t,pool:i}),false;let s=await ie(o,{...t,pool:i});d(s);let a=N(e,t);return Y(o.impressionId,a),true}var pt={show(e){return M(()=>De(e)).then(t=>t??false)},fetch(e){return M(()=>Fe(e))},preload(e){return M(()=>Ue(e)).then(t=>t??0)},renderFromPool(e){return M(()=>je(e)).then(t=>t??false)}};exports.DEFAULT_CONFIG=b;exports.HOOK_CATALOG=se;exports.SDK_VERSION=D;exports.detectImageProtocol=G;exports.renderBlip=H;exports.renderCard=g;exports.sponsor=pt;exports.textCardForBlip=B;
4
+ `}function Q(e){return e!==void 0&&e!==""}function z(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 U(e,n={}){try{let t=e.creative;if(t.format!=="image"&&t.format!=="gif")return h(A(e),n);let o=n.protocol??z();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
+ `+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 U(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 ze(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 Ue(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(()=>ze(e)).then(n=>n??false)},fetch(e){return B(()=>$e(e))},preload(e){return B(()=>Ue(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=z;exports.renderBlip=U;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 f from'fs';import*as te from'os';import*as C from'path';var F=(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 b={minIntervalSeconds:600,serveTimeoutMs:2500,preloadPoolSize:3,killSwitch:false,displayDurationSeconds:25,minSdkVersion:""};var se=["SessionStart","SessionEnd","Stop","PostToolUse","Notification"];var D="1.1.42";var ae="https://api.opencrater.to";function V(e,t=process.env){let n=t.OPENCRATER_API_ORIGIN;return (e??(n&&n.trim()!==""?n:ae)).replace(/\/+$/,"")}function c(...e){try{if(process.env.OPENCRATER_DEBUG!=="1")return;console.error("[opencrater]",...e);try{let t=F("os"),n=F("fs"),r=F("path");n.appendFileSync(r.join(t.homedir(),".config","opencrater","hook.log"),`${new Date().toISOString()} [opencrater] ${e.map(o=>String(o)).join(" ")}
2
- `);}catch{}}catch{}}function v(e){return typeof e=="number"&&Number.isFinite(e)}function W(e){let t=b;if(typeof e!="object"||e===null)return {...t};let n=e;return {minIntervalSeconds:v(n.minIntervalSeconds)?n.minIntervalSeconds:t.minIntervalSeconds,serveTimeoutMs:v(n.serveTimeoutMs)?n.serveTimeoutMs:t.serveTimeoutMs,preloadPoolSize:v(n.preloadPoolSize)?n.preloadPoolSize:t.preloadPoolSize,killSwitch:n.killSwitch===true,displayDurationSeconds:v(n.displayDurationSeconds)?n.displayDurationSeconds:t.displayDurationSeconds,minSdkVersion:typeof n.minSdkVersion=="string"?n.minSdkVersion:t.minSdkVersion}}async function U(e,t,n,r,o){try{let i=await fetch(`${e}${t}`,{method:"POST",headers:{"content-type":"application/json",...o??{}},body:JSON.stringify(n),signal:AbortSignal.timeout(r)});return i.ok?await i.json():(c(`POST ${t} -> HTTP ${i.status}`),null)}catch(i){return c(`POST ${t} failed:`,i),null}}function q(e,t){let n=e.host??"generic";return {publisherKey:e.publisherKey,packageName:e.packageName,placement:e.placement,host:n,sdkVersion:D,installId:t.installId,os:process.platform,termProgram:process.env.TERM_PROGRAM??void 0,topics:t.topics&&t.topics.length>0?t.topics:void 0}}function le(e){if(typeof e!="object"||e===null)return null;let t=e;if(typeof t.fill!="boolean")return null;let n={fill:t.fill,fallback:t.fallback??null,config:W(t.config),...Array.isArray(t.allowedPlacements)?{allowedPlacements:t.allowedPlacements.filter(r=>typeof r=="string")}:{}};return t.blip!==void 0&&t.blip!==null&&(n.blip=t.blip),typeof t.computeBalanceMicroUsd=="number"&&(n.computeBalanceMicroUsd=t.computeBalanceMicroUsd),typeof t.weeklyGrantMicroUsd=="number"&&(n.weeklyGrantMicroUsd=t.weeklyGrantMicroUsd),typeof t.pendingMicroUsd=="number"&&(n.pendingMicroUsd=t.pendingMicroUsd),n}async function j(e,t){let n=await U(t.origin,"/v1/serve",q(e,t),t.timeoutMs);return le(n)}async function J(e,t,n){let r=await U(n.origin,"/v1/serve/batch",{...q(e,n),count:t},n.timeoutMs);if(typeof r!="object"||r===null)return null;let o=r;return Array.isArray(o.blips)?{blips:o.blips,fallback:o.fallback??null,config:W(o.config),...Array.isArray(o.allowedPlacements)?{allowedPlacements:o.allowedPlacements.filter(i=>typeof i=="string")}:{}}:null}function Y(e,t){return U(t.origin,"/v1/events/impression",{impressionId:e},t.timeoutMs).then(()=>{}).catch(()=>{})}var ce=new RegExp("\x1B\\[[0-9;]*m|\x1B\\]8;;[^\x07\x1B]*(?:\x07|\x1B\\\\)","g"),k={dim:"\x1B[2m",bold:"\x1B[1m",reset:"\x1B[0m"},ue=60,pe=24,de="\u2139 This project is supported by Blips via OpenCrater. Opt out: `npx opencrater off` or OPENCRATER_DISABLE=1";function fe(e){return e.replace(ce,"").length}function y(e,t){return t<=0?"":e.length<=t?e:t===1?"\u2026":e.slice(0,t-1).trimEnd()+"\u2026"}function me(e,t,n){let r=e.split(/\s+/).filter(l=>l.length>0),o=[],i="";for(let l of r){let p=i===""?l:`${i} ${l}`;if(p.length<=t)i=p;else if(i!==""&&o.push(i),i=l.length>t?y(l,t):l,o.length>=n)break}i!==""&&o.length<n&&o.push(i),o.length>n&&(o.length=n);let s=o.join(" "),a=o.length-1,u=o[a];return u!==void 0&&s.length<r.join(" ").length&&(o[a]=y(`${u}\u2026`,t)),o}function O(e=process.env,t=!!process.stdout.isTTY){if(!t)return false;if(e.FORCE_HYPERLINK!==void 0&&e.FORCE_HYPERLINK!=="0")return true;let n=e.TERM_PROGRAM??"";return !!(["iTerm.app","WezTerm","ghostty","Hyper","vscode","Tabby"].includes(n)||e.KITTY_WINDOW_ID||e.WT_SESSION||Number(e.VTE_VERSION??"0")>=5e3)}function P(e=process.env,t=!!process.stdout.isTTY){return !(e.NO_COLOR!==void 0&&e.NO_COLOR!==""||!t||(e.TERM??"")==="dumb")}function ge(e,t){return `\x1B]8;;${e}\x07${t}\x1B]8;;\x07`}function A(e){let t={sponsorLabel:e.sponsorLabel,title:e.creative.title,body:e.creative.body,url:e.clickUrl};return e.creative.cta!==void 0&&(t.cta=e.creative.cta),t}function X(e){return {sponsorLabel:"",title:e.title,body:e.body,url:e.url}}function g(e,t={}){let n=t.width??process.stdout.columns??80,o=Math.max(pe,Math.min(n,ue))-4,i=t.color??P(),s=t.hyperlinks??O(),a=(m,$)=>i?`${$}${m}${k.reset}`:m,u=e.label?y(e.label,o):e.sponsorLabel?y(`Sponsored Blips \xB7 ${e.sponsorLabel}`,o):"Sponsored Blips",l=[];l.push(a(u,k.dim)),e.title!==e.sponsorLabel&&l.push(a(y(e.title,o),k.bold));for(let m of me(e.body,o,2))l.push(m);let p="\u2192 ";if(s){let m=y(e.cta??e.url,o-p.length);l.push(p+a(ge(e.url,m),k.dim));}else e.cta&&l.push(y(e.cta,o)),l.push(p+a(y(e.url,o-p.length),k.dim));let R=`\u256D${"\u2500".repeat(o+2)}\u256E`,E=`\u2570${"\u2500".repeat(o+2)}\u256F`,L=l.map(m=>{let $=" ".repeat(Math.max(0,o-fe(m)));return `\u2502 ${m}${$} \u2502`}),h=[];return t.disclosure&&h.push(a(de,k.dim)),h.push(R,...L,E),h.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.3.0";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(`
3
3
  `)+`
4
- `}function Z(e){return e!==void 0&&e!==""}function G(e=process.env,t=!!process.stdout.isTTY){if(!t)return "none";let n=e.TERM??"";if(Z(e.TMUX)||n.startsWith("tmux")||n.startsWith("screen"))return "none";let r=e.TERM_PROGRAM??"";return r==="iTerm.app"||e.LC_TERMINAL==="iTerm2"||r==="WezTerm"?"iterm2":n==="xterm-kitty"||Z(e.KITTY_WINDOW_ID)?"kitty":"none"}var w="\x1B",Se="\x07",ye=2e3,he=2*1024*1024,be=new Set(["image/png","image/jpeg","image/gif","image/webp"]),x=4096;async function ke(e,t=fetch,n={}){let r=n.timeoutMs??ye,o=n.maxBytes??he;try{let i=await t(e,{signal:AbortSignal.timeout(r)});if(!i.ok)return c(`media: HTTP ${i.status} for ${e}`),null;let s=(i.headers.get("content-type")??"").split(";")[0].trim().toLowerCase();if(!be.has(s))return c(`media: disallowed content-type "${s}" for ${e}`),null;let a=Number(i.headers.get("content-length")??"0");if(Number.isFinite(a)&&a>o)return c(`media: content-length ${a} exceeds ${o} for ${e}`),null;let u=i.body;if(u&&typeof u.getReader=="function"){let p=u.getReader(),R=[],E=0;for(;;){let{done:L,value:h}=await p.read();if(L)break;if(h!==void 0){if(E+=h.byteLength,E>o)return await p.cancel().catch(()=>{}),c(`media: stream exceeded ${o} bytes for ${e}`),null;R.push(h);}}return Buffer.concat(R)}let l=Buffer.from(await i.arrayBuffer());return l.byteLength>o?(c(`media: body ${l.byteLength} bytes exceeds ${o} for ${e}`),null):l}catch(i){return c(`media: fetch failed for ${e}:`,i),null}}function Ce(e){let t=e.toString("base64");return `${w}]1337;File=inline=1;size=${e.byteLength};width=auto:${t}${Se}`}function we(e){let t=e.toString("base64");if(t.length<=x)return `${w}_Gf=100,a=T;${t}${w}\\`;let n=[];for(let r=0;r<t.length;r+=x){let o=t.slice(r,r+x),s=`m=${r+x>=t.length?0:1}`,a=r===0?`f=100,a=T,${s}`:s;n.push(`${w}_G${a};${o}${w}\\`);}return n.join("")}function B(e){let t=A(e),n=e.creative;switch(n.format){case "image":case "gif":return {...t,body:n.textFallback??t.body};case "video":return {...t,body:n.textFallback??t.body,cta:t.cta??"\u25B6 Watch"};case "audio":return {...t,body:n.textFallback??t.body,cta:t.cta??"\u{1F50A} Listen"};default:return t}}async function H(e,t={}){try{let n=e.creative;if(n.format!=="image"&&n.format!=="gif")return g(B(e),t);let r=t.protocol??G();if(r==="none"||n.mediaUrl===void 0||n.mediaUrl==="")return g(B(e),t);let o={};t.timeoutMs!==void 0&&(o.timeoutMs=t.timeoutMs),t.maxBytes!==void 0&&(o.maxBytes=t.maxBytes);let i=await ke(n.mediaUrl,t.fetchImpl??fetch,o);return i===null||i.byteLength===0?g(B(e),t):(r==="kitty"?we(i):Ce(i))+`
5
- `+g(A(e),t)}catch(n){return c("media: render failed, falling back to text:",n),g(A(e),t)}}function Te(e,t){return e.filter(n=>n.renderBy>t)}function Q(e,t,n=18e5){return e.filter(r=>r&&typeof r.impressionId=="string"&&typeof r.clickUrl=="string"&&r.creative&&typeof r.creative.title=="string").map(r=>({blip:r,renderBy:t+n}))}function ee(e,t){let n=Te(e.pool,t),r=n.shift();return {blip:r?r.blip:null,pool:n}}function Re(e=process.env){return C.join(te.homedir(),".config","opencrater")}function ne(e=process.env){return C.join(Re(e),"state.json")}function _(){return {installId:randomUUID(),lastShownAt:0,optOut:false,disclosureShown:false,cachedConfig:null,configFetchedAt:0,pool:[],allowedPlacements:{},sessionTopics:[],integrations:[],devToken:null,computeRouting:null,computeCards:null}}function S(e){return typeof e=="number"&&Number.isFinite(e)}var oe=new Set(["EPERM","EACCES","EBUSY","EEXIST"]);function re(e){for(let t=0;;t++)try{return {text:f.readFileSync(e,"utf8")}}catch(n){let r=n.code??"";if(!(r==="ENOENT"||oe.has(r)))return {locked:true};if(t>=4)return r==="ENOENT"?{missing:true}:{locked:true};try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(t+1));}catch{}}}function Ee(e){if(typeof e!="object"||e===null)return null;let t=e;return !S(t.minIntervalSeconds)||!S(t.serveTimeoutMs)||!S(t.preloadPoolSize)||typeof t.killSwitch!="boolean"?null:{minIntervalSeconds:t.minIntervalSeconds,serveTimeoutMs:t.serveTimeoutMs,preloadPoolSize:t.preloadPoolSize,killSwitch:t.killSwitch,displayDurationSeconds:S(t.displayDurationSeconds)?t.displayDurationSeconds:25,minSdkVersion:typeof t.minSdkVersion=="string"?t.minSdkVersion:""}}function ve(e){if(!Array.isArray(e))return [];let t=[];for(let n of e){if(typeof n!="object"||n===null)continue;let r=n,o=r.blip;if(!S(r.renderBy)||typeof o!="object"||o===null||typeof o.impressionId!="string"||typeof o.clickUrl!="string"||typeof o.sponsorLabel!="string"||typeof o.creative!="object"||o.creative===null)continue;let i=o.creative;typeof i.title!="string"||typeof i.body!="string"||t.push({blip:{impressionId:o.impressionId,...typeof o.campaignId=="string"?{campaignId:o.campaignId}:{},clickUrl:o.clickUrl,sponsorLabel:o.sponsorLabel,creative:{format:"text",title:i.title,body:i.body,...typeof i.cta=="string"?{cta:i.cta}:{}}},renderBy:r.renderBy});}return t}function Oe(e){if(typeof e!="object"||e===null||Array.isArray(e))return {};let t={};for(let[n,r]of Object.entries(e)){if(!Array.isArray(r))continue;let o=r.filter(i=>typeof i=="string"&&i.length<=64);t[n]=o.slice(0,64);}return t}function Pe(e){if(!Array.isArray(e))return [];let t=[];for(let n of e){if(typeof n!="object"||n===null)continue;let r=n;if(!(typeof r.topic!="string"||!S(r.at))&&(t.push({topic:r.topic.slice(0,32),at:r.at}),t.length>=24))break}return t}function Ae(e){if(!Array.isArray(e))return [];let t=[],n=new Set;for(let r of e){if(typeof r!="object"||r===null)continue;let o=r;if(typeof o.key!="string"||typeof o.package!="string"||o.key===""||o.package==="")continue;let i=`${o.package}\0${o.key}`;if(!n.has(i)&&(n.add(i),t.push({key:o.key,package:o.package}),t.length>=32))break}return t}function xe(e){if(typeof e!="object"||e===null)return null;let t=e,n={};if(typeof t.savedEnv=="object"&&t.savedEnv!==null)for(let[r,o]of Object.entries(t.savedEnv))(typeof o=="string"||o===null)&&(n[r]=o);return {active:t.active===true,savedEnv:n}}function Be(e){if(typeof e!="object"||e===null)return null;let t=e,n=r=>S(r)&&r>=0?r:0;return {turns:n(t.turns),lastLimitAt:n(t.lastLimitAt),lastDepletedAt:n(t.lastDepletedAt),lastBackupAt:n(t.lastBackupAt)}}function _e(e){let t=_();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:S(n.lastShownAt)&&n.lastShownAt>=0?n.lastShownAt:0,optOut:n.optOut===true,disclosureShown:n.disclosureShown===true,cachedConfig:Ee(n.cachedConfig),allowedPlacements:Oe(n.allowedPlacements),sessionTopics:Pe(n.sessionTopics),integrations:Ae(n.integrations),devToken:typeof n.devToken=="string"?n.devToken:null,computeRouting:xe(n.computeRouting),computeCards:Be(n.computeCards),configFetchedAt:S(n.configFetchedAt)&&n.configFetchedAt>=0?n.configFetchedAt:0,pool:ve(n.pool)}}function T(e=process.env){let t=ne(e),n=re(t);if(n.text!==void 0)try{return _e(JSON.parse(n.text))}catch{let r=_();try{d(r,e);}catch{}return r}if(n.missing){let r=_();try{d(r,e);}catch{}return r}return _()}function d(e,t=process.env,n={}){let r=ne(t),o=C.dirname(r);f.mkdirSync(o,{recursive:true});let i=re(r),s=null;if(i.text!==void 0)try{s=JSON.parse(i.text);}catch{s=null;}if(s)typeof s.lastShownAt=="number"&&s.lastShownAt>e.lastShownAt&&(e={...e,lastShownAt:s.lastShownAt}),!n.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(!n.allowClearToken&&e.devToken==null&&i.text===void 0&&!i.missing)return;let a=C.join(o,`.state.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`);f.writeFileSync(a,JSON.stringify(e,null,2)+`
6
- `,"utf8");for(let u=0;;u++)try{f.renameSync(a,r);return}catch(l){let p=l.code??"";if(u>=4||!oe.has(p)){try{f.rmSync(a,{force:!0});}catch{}if(u>=4)return;throw l}try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(u+1));}catch{}}}var Me=["CI","CONTINUOUS_INTEGRATION","GITHUB_ACTIONS","GITLAB_CI","CIRCLECI","TRAVIS","BUILDKITE","JENKINS_URL","TEAMCITY_VERSION","TF_BUILD","APPVEYOR","CODEBUILD_BUILD_ID","DRONE","NETLIFY","VERCEL"];function z(e){return e!==void 0&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}function Ne(e){return z(e.OPENCRATER_DISABLE)||z(e.TSN_DISABLE)}function Le(e){return Me.some(t=>z(e[t]))}function K(e){return e?{...b,...e}:b}function I(e,t={}){if(Ne(e.env))return "env_disabled";if(e.state.optOut)return "opt_out";let n=K(e.state.cachedConfig);if(n.killSwitch)return "kill_switch";if(Le(e.env))return "ci";if(!t.skipTTY&&!e.isTTY)return "not_tty";if(!t.skipFrequency){let r=n.minIntervalSeconds*1e3;if(e.state.lastShownAt>0&&e.now-e.state.lastShownAt<r)return "frequency"}return null}async function M(e){try{return await e()}catch(t){return c("suppressed error:",t),null}}function N(e,t){let n=K(t.cachedConfig);return {origin:V(e.apiOrigin),timeoutMs:n.serveTimeoutMs,installId:t.installId,config:n}}function $e(e,t){let n=!t.disclosureShown,r=g(e,{width:process.stdout.columns??80,color:P(),hyperlinks:O(),disclosure:n});return process.stdout.write(r),{...t,lastShownAt:Date.now(),disclosureShown:true}}async function ie(e,t){let n=await H(e,{width:process.stdout.columns??80,color:P(),hyperlinks:O(),disclosure:!t.disclosureShown});return process.stdout.write(n),{...t,lastShownAt:Date.now(),disclosureShown:true}}async function Fe(e){let t=T(),n=I({env:process.env,isTTY:!!process.stdout.isTTY,state:t,now:Date.now()},{skipFrequency:true});if(n!==null)return c("fetch suppressed:",n),null;let r=N(e,t),o=await j(e,r);return o?(d({...t,cachedConfig:o.config,configFetchedAt:Date.now()}),o.fill&&o.blip?o.blip:null):null}async function De(e){let t=T(),n=I({env:process.env,isTTY:!!process.stdout.isTTY,state:t,now:Date.now()});if(n!==null)return c("suppressed:",n),false;let r=N(e,t),o=await j(e,r);return o?(t={...t,cachedConfig:o.config,configFetchedAt:Date.now()},o.fill&&o.blip?(t=await ie(o.blip,t),d(t),Y(o.blip.impressionId,r),true):o.fallback?(t=$e(X(o.fallback),t),d(t),true):(d(t),false)):false}async function Ue(e){let t=T(),n=I({env:process.env,isTTY:!!process.stdout.isTTY,state:t,now:Date.now()},{skipTTY:true,skipFrequency:true});if(n!==null)return c("preload suppressed:",n),0;let r=N(e,t),o=Math.max(1,r.config.preloadPoolSize),i=await J(e,o,r);if(!i)return 0;let s=Date.now(),a=Q(i.blips,s);return d({...t,pool:a,cachedConfig:i.config,configFetchedAt:s}),a.length}async function je(e){let t=T(),n=Date.now(),r=I({env:process.env,isTTY:!!process.stdout.isTTY,state:t,now:n});if(r!==null)return c("renderFromPool suppressed:",r),false;let{blip:o,pool:i}=ee(t,n);if(!o)return d({...t,pool:i}),false;let s=await ie(o,{...t,pool:i});d(s);let a=N(e,t);return Y(o.impressionId,a),true}var pt={show(e){return M(()=>De(e)).then(t=>t??false)},fetch(e){return M(()=>Fe(e))},preload(e){return M(()=>Ue(e)).then(t=>t??0)},renderFromPool(e){return M(()=>je(e)).then(t=>t??false)}};export{b as DEFAULT_CONFIG,se as HOOK_CATALOG,D as SDK_VERSION,G as detectImageProtocol,H as renderBlip,g as renderCard,pt as sponsor,B as textCardForBlip};
4
+ `}function Q(e){return e!==void 0&&e!==""}function z(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 U(e,n={}){try{let t=e.creative;if(t.format!=="image"&&t.format!=="gif")return h(A(e),n);let o=n.protocol??z();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
+ `+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 U(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 ze(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 Ue(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(()=>ze(e)).then(n=>n??false)},fetch(e){return B(()=>$e(e))},preload(e){return B(()=>Ue(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,z as detectImageProtocol,U as renderBlip,h as renderCard,kn as sponsor,A as textCardForBlip};
package/dist/paint.js CHANGED
@@ -1,9 +1,9 @@
1
1
  #!/usr/bin/env node
2
- 'use strict';var child_process=require('child_process'),crypto=require('crypto'),Fe=require('http'),ot=require('fs'),Pe=require('os'),U=require('path'),zlib=require('zlib'),pe=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 Fe__namespace=/*#__PURE__*/_interopNamespace(Fe);var ot__namespace=/*#__PURE__*/_interopNamespace(ot);var Pe__namespace=/*#__PURE__*/_interopNamespace(Pe);var U__namespace=/*#__PURE__*/_interopNamespace(U);var pe__namespace=/*#__PURE__*/_interopNamespace(pe);var te=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});function Ce(t){return t>=21||t<8?.2:.4}function xe(t,e){let r=e.filter(i=>Number.isFinite(i)&&t-i<6e5&&i<=t);return r.length>=2?{play:false,next:r}:{play:true,next:[...r,t]}}function ne(t=process.env){return U__namespace.join(Pe__namespace.homedir(),".config","opencrater")}var cn=600*1e3;function re(){return U__namespace.join(ne(),"blocked-ads.json")}function oe(){return U__namespace.join(ne(),"reported-ads.json")}function ln(t,e){let r={};for(let[i,a]of Object.entries(t))typeof a=="number"&&Number.isFinite(a)&&a>e&&(r[i]=a);return r}function un(t){try{let e=JSON.parse(ot__namespace.readFileSync(re(),"utf8"));return ln(e&&typeof e=="object"?e:{},t)}catch{return {}}}function Dt(t,e=Date.now()){if(t)try{let r=un(e);r[t]=e+cn,ot__namespace.mkdirSync(U__namespace.dirname(re()),{recursive:!0}),ot__namespace.writeFileSync(re(),JSON.stringify(r));}catch{}}function pn(){try{let t=JSON.parse(ot__namespace.readFileSync(oe(),"utf8"));return t&&typeof t=="object"?t:{}}catch{return {}}}function Re(t,e=Date.now()){if(t)try{let r=pn();r[t]=e,ot__namespace.mkdirSync(U__namespace.dirname(oe()),{recursive:!0}),ot__namespace.writeFileSync(oe(),JSON.stringify(r));}catch{}}var dn=[137,80,78,71,13,10,26,10];function Me(t){try{if(t.length<45)return null;for(let x=0;x<8;x++)if(t[x]!==dn[x])return null;let e=new DataView(t.buffer,t.byteOffset,t.byteLength),r=8,i=0,a=0,p=0,n=-1,m=0,d=[];for(;r+8<=t.length;){let x=e.getUint32(r),D=String.fromCharCode(t[r+4],t[r+5],t[r+6],t[r+7]),F=t.subarray(r+8,r+8+x);if(D==="IHDR")i=e.getUint32(r+8),a=e.getUint32(r+12),p=t[r+16],n=t[r+17],m=t[r+20];else if(D==="IDAT")d.push(F);else if(D==="IEND")break;r+=12+x;}if(p!==8||n!==2&&n!==6||m!==0||i===0||a===0||i>1024||a>1024)return null;let y=n===6?4:3,h=i*y,l=zlib.inflateSync(Buffer.concat(d.map(x=>Buffer.from(x))));if(l.length<(h+1)*a)return null;let N=new Uint8Array(i*a*4),I=new Uint8Array(h),O=new Uint8Array(h);for(let x=0;x<a;x++){let D=x*(h+1),F=l[D];for(let C=0;C<h;C++){let k=l[D+1+C],b=C>=y?O[C-y]:0,S=I[C],B=C>=y?I[C-y]:0,$;switch(F){case 0:$=k;break;case 1:$=k+b;break;case 2:$=k+S;break;case 3:$=k+(b+S>>1);break;case 4:{let T=b+S-B,X=Math.abs(T-b),Ot=Math.abs(T-S),G=Math.abs(T-B);$=k+(X<=Ot&&X<=G?b:Ot<=G?S:B);break}default:return null}O[C]=$&255;}for(let C=0;C<i;C++){let k=C*y,b=(x*i+C)*4;N[b]=O[k],N[b+1]=O[k+1],N[b+2]=O[k+2],N[b+3]=y===4?O[k+3]:255;}I.set(O);}return {width:i,height:a,rgba:N}}catch{return null}}var Lt=300,Ee=140,se=12e3,vn=9;var In=1500,Ne=3*1024*1024,On=12*1024*1024,kn=12*1024*1024,An=6e3,Te=25e3,Ge=64,w="\x1B",Cn="\x07",_e=`${w}7`,De=`${w}8`;function Ut(t,e){return `${w}]8;;${t}${w}\\${e}${w}]8;;${w}\\`}function jt(t){return t.replace(/\x1b\[[0-9;]*m/g,"").replace(/\x1b\]8;;[^\x1b\x07]*(?:\x1b\\|\x07)/g,"").replace(/[︎️]/g,"").length}function mt(t,e){return t.length<=e?t:`${t.slice(0,Math.max(0,e-1))}\u2026`}function xn(t,e){let r=t.split(/\s+/).filter(Boolean),i=[],a="";for(let p of r)if(a===""?a=mt(p,e):a.length+1+p.length<=e?a+=` ${p}`:(i.push(a),a=mt(p,e)),i.length>=3)break;return a&&i.length<4&&i.push(a),i}var Y=process.platform==="win32";function it(t){return Y?`${t}\uFE0E`:t}function Pn(t){let e=()=>{try{ot.closeSync(t);}catch{}};return {write:r=>{try{ot.writeSync(t,r);}catch{}},close:e,closeAndWait:async()=>e()}}var Rn=["$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
- `);function He(){return `${process.env.SystemRoot||process.env.windir||"C:\\Windows"}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`}function Mn(){try{let t=Buffer.from(Rn,"utf16le").toString("base64"),e=He(),r="ignore";if(process.env.OPENCRATER_DEBUG==="1")try{r=ot.openSync(U__namespace.join(Pe.homedir(),".config","opencrater","pump-err.log"),"a");}catch{}_("spawning pump:",e);let i=child_process.spawn(e,["-NoProfile","-NonInteractive","-EncodedCommand",t],{stdio:["pipe","pipe",r],windowsHide:!0});i.on("error",m=>_("pump spawn error:",e,"-",m.message)),i.on("exit",m=>_("pump process exited code",m,"pid",i.pid));let a=i.stdin;if(!a)return _("pump: no stdin pipe"),null;a.on("error",()=>{});let p=!1;return i.on("exit",()=>{p=!0;}),{size:new Promise(m=>{let d="",y=!1,h=N=>{y||(y=!0,m(N));},l=i.stdout;if(!l)return h(null);l.setEncoding("utf8"),l.on("data",N=>{d+=N;let I=d.match(/OCWIN\s+(\d+)\s+(\d+)\s+(\d+)/);I&&(_("pump reported console pid",I[1],"size",I[2]+"x"+I[3]),h({pid:Number(I[1]),cols:Number(I[2]),rows:Number(I[3])}));}),l.on("error",()=>h(null)),l.on("end",()=>h(null)),setTimeout(()=>h(null),2500);}),write:m=>{try{a.write(m);}catch{}},close:()=>{try{a.end();}catch{}},closeAndWait:()=>new Promise(m=>{if(p)return m();let d=!1,y=()=>{d||(d=!0,m());};i.on("exit",y),setTimeout(y,5e3);try{a.end();}catch{y();}})}}catch(t){return _("pump: spawn threw",t.message),null}}function En(t){try{let e=t.replace(/'/g,"''"),r=`$ErrorActionPreference='Stop';try{$r=$null;try{$su=([wmiclass]'Win32_ProcessStartup').CreateInstance();$su.CreateFlags=[uint32]8;$r=([wmiclass]'Win32_Process').Create('${e}',$null,$su)}catch{};if($r -eq $null -or $r.ReturnValue -ne 0){$r=([wmiclass]'Win32_Process').Create('${e}')};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)}`,i=Buffer.from(r,"utf16le").toString("base64"),a=child_process.spawnSync(He(),["-NoProfile","-NonInteractive","-EncodedCommand",i],{timeout:5e3,encoding:"utf8"}),p=(a.stdout??"").match(/OCPID\s+(\d+)/);return p?Number(p[1]):(_("wmi spawn failed:",(a.stdout??"").trim(),"|",(a.stderr??"").trim()),0)}catch(e){return _("wmi spawn threw",e.message),0}}function Nn(t,e){try{let r=U__namespace.join(Pe.homedir(),".config","opencrater");ot.mkdirSync(r,{recursive:!0});let i=U__namespace.join(r,`paint-${process.pid}-${Date.now()}.json`);ot.writeFileSync(i,JSON.stringify({...t,_env:process.env}),"utf8");let a=m=>`"${m}"`,p=[a(process.execPath),a(__filename),"--persist","--payload-file",a(i),"--console-pid",String(e)];Wt&&p.push("--debug");let n=En(p.join(" "));return _("escape: wmi persistent painter pid",n),n>0}catch(r){return _("escape failed",r.message),false}}function lr(t){return !!(t.WT_SESSION||t.TERM_PROGRAM||t.ConEmuANSI==="ON"||t.ANSICON)}function Tn(){try{let t=child_process.spawnSync("mode",["con"],{timeout:1500,encoding:"utf8"}).stdout;if(!t)return null;let r=[...t.matchAll(/:\s*(\d+)/g)].map(i=>Number(i[1]))[1];return r&&r>0?r:null}catch{return null}}function _n(t){let e=t.TERM_PROGRAM??"",r=t.TERM??"";return t.TMUX?"none":e==="iTerm.app"||t.LC_TERMINAL==="iTerm2"||e==="WezTerm"?"iterm2":r==="xterm-kitty"||t.KITTY_WINDOW_ID?"kitty":"none"}function Le(t,e){let r=t.toString("base64");return `${w}]1337;File=inline=1;size=${t.length};width=${e.w};height=${e.h};preserveAspectRatio=1:${r}${Cn}`}function Dn(t,e){let r=t.toString("base64"),i=[];for(let p=0;p<r.length;p+=4096)i.push(r.slice(p,p+4096));let a="";for(let p=0;p<i.length;p++){let n=p===0,m=p===i.length-1,d=n?`a=T,f=100,c=${e.w},r=${e.h},m=${m?0:1}`:`m=${m?0:1}`;a+=`${w}_G${d};${i[p]}${w}\\`;}return a}function Ln(t){let e=(t.COLORTERM??"").toLowerCase();if(e.includes("truecolor")||e.includes("24bit"))return true;let r=t.TERM_PROGRAM??"";return ["iTerm.app","WezTerm","vscode","ghostty","Apple_Terminal"].includes(r)}function ae(t,e,r){if(Math.abs(t-e)<12&&Math.abs(e-r)<12&&Math.abs(t-r)<12)return t<8?16:t>248?231:232+Math.round((t-8)/247*23);let i=a=>Math.round(a/255*5);return 16+36*i(t)+6*i(e)+i(r)}var Un=[" ","\u2598","\u259D","\u2580","\u2596","\u258C","\u259E","\u259B","\u2597","\u259A","\u2590","\u259C","\u2584","\u2599","\u259F","\u2588"];function ze(t,e,r,i){let a=[],p=(m,d)=>{let y=(d*e+m)*3;return [t[y],t[y+1],t[y+2]]},n=(m,d)=>{let y=m[0]-d[0],h=m[1]-d[1],l=m[2]-d[2];return y*y+h*h+l*l};for(let m=0;m+1<r;m+=2){let d="",y="";for(let h=0;h+1<e;h+=2){let l=[p(h,m),p(h+1,m),p(h,m+1),p(h+1,m+1)],N=0,I=1,O=-1;for(let $=0;$<4;$++)for(let T=$+1;T<4;T++){let X=n(l[$],l[T]);X>O&&(O=X,N=$,I=T);}let x=0,D=[0,0,0],F=[0,0,0],C=0,k=0;for(let $=0;$<4;$++)n(l[$],l[N])<=n(l[$],l[I])?(x|=1<<$,D[0]+=l[$][0],D[1]+=l[$][1],D[2]+=l[$][2],C++):(F[0]+=l[$][0],F[1]+=l[$][1],F[2]+=l[$][2],k++);if(O<1e3){let $=Ot=>Ot&-8,T=[$(Math.round((l[0][0]+l[1][0]+l[2][0]+l[3][0])/4)),$(Math.round((l[0][1]+l[1][1]+l[2][1]+l[3][1])/4)),$(Math.round((l[0][2]+l[1][2]+l[2][2]+l[3][2])/4))],X=i?`${w}[48;2;${T[0]};${T[1]};${T[2]}m`:`${w}[48;5;${ae(T[0],T[1],T[2])}m`;X!==y&&(d+=X,y=X),d+=" ";continue}let b=C?[Math.round(D[0]/C),Math.round(D[1]/C),Math.round(D[2]/C)]:[0,0,0],S=k?[Math.round(F[0]/k),Math.round(F[1]/k),Math.round(F[2]/k)]:b,B=i?`${w}[38;2;${b[0]};${b[1]};${b[2]};48;2;${S[0]};${S[1]};${S[2]}m`:`${w}[38;5;${ae(b[0],b[1],b[2])};48;5;${ae(S[0],S[1],S[2])}m`;B!==y&&(d+=B,y=B),d+=Un[x];}d+=`${w}[0m`,a.push(d);}return a}function jn(t,e,r,i,a,p){let n=e*2,m=r*2,d=`${p?`${p},`:""}scale=${n}:${m}:flags=lanczos+accurate_rnd`,y=["-y","-i",t];i?y.push("-t","6","-vf",`fps=7,${d}`):y.push("-frames:v","1","-vf",d),y.push("-f","rawvideo","-pix_fmt","rgb24","-");let h=child_process.spawnSync("ffmpeg",y,{timeout:12e3,maxBuffer:64*1024*1024});if(h.status!==0||!h.stdout||h.stdout.length===0)return null;let l=n*m*3,N=Math.min(Math.floor(h.stdout.length/l),Ge);if(N===0)return null;let I=[];for(let O=0;O<N;O++)I.push(ze(h.stdout.subarray(O*l,(O+1)*l),n,m,a));return I}function Wn(t,e,r,i,a,p){if(!et("chafa"))return null;let n=U__namespace.join(e,"fr_%03d.png"),m=["-y","-i",t],d=[];if(a?(m.push("-t","6"),d.push("fps=5")):m.push("-frames:v","1"),p&&d.push(p),d.length>0&&m.push("-vf",d.join(",")),m.push(n),child_process.spawnSync("ffmpeg",m,{timeout:12e3}).status!==0)return null;let h=[];for(let l=1;l<=Ge;l++){let N=U__namespace.join(e,`fr_${String(l).padStart(3,"0")}.png`),I;try{I=child_process.spawnSync("chafa",a?["-f","symbols","-s",`${r}x${i}`,"--stretch","--symbols","vhalf","--colors","full",N]:["-f","symbols","-s",`${r}x${i}`,"--stretch","--colors","full",N],{timeout:5e3,maxBuffer:8*1024*1024,encoding:"utf8"});}catch{break}if(I.status!==0||!I.stdout)break;let x=I.stdout.replace(/\x1b\[\?25[lh]/g,"").split(`
4
- `).filter(k=>k.length>0);if(x.length===0)break;let D=" ".repeat(r),F=Math.floor((i-x.length)/2),C=[];for(let k=0;k<i;k++){let b=x[k-F];if(b===void 0)C.push(D);else {let S=" ".repeat(Math.max(0,r-jt(b)));C.push(b+S);}}h.push(C);}return h.length>0?h:null}function Je(t){try{let e=child_process.spawnSync("ffprobe",["-v","quiet","-select_streams","v:0","-show_entries","stream=width,height","-of","csv=p=0",t],{timeout:5e3,encoding:"utf8"});if(e.status!==0||!e.stdout)return null;let r=e.stdout.trim().match(/^(\d+),(\d+)/);if(!r)return null;let i=Number(r[1]),a=Number(r[2]);return i>0&&a>0?{w:i,h:a}:null}catch{return null}}function Fn(t){try{let r=(child_process.spawnSync("ffmpeg",["-t","2","-i",t,"-vf","cropdetect=24:2:1","-f","null","-"],{timeout:8e3,encoding:"utf8"}).stderr??"").match(/crop=(\d+):(\d+):(\d+):(\d+)/g);if(!r||r.length===0)return null;let i=r[r.length-1],a=i.match(/crop=(\d+):(\d+):(\d+):(\d+)/),p=Number(a[1]),n=Number(a[2]);if(p<8||n<8)return null;let m=Je(t);if(m){let d=p*n/(m.w*m.h);if(d<.55||d>.92)return null}return i}catch{return null}}function et(t){try{return Y?child_process.spawnSync("where",[t],{timeout:2e3}).status===0:child_process.spawnSync("sh",["-c",'command -v -- "$1" >/dev/null 2>&1',"sh",t],{timeout:2e3}).status===0}catch{return false}}async function Ue(t,e){try{let r=await fetch(t,{signal:AbortSignal.timeout(An)});if(!r.ok)return null;let i=(r.headers.get("content-type")??"").split(";")[0].trim().toLowerCase();if(Number(r.headers.get("content-length")??"0")>e)return null;let p=Buffer.from(await r.arrayBuffer());return p.length===0||p.length>e?null:{data:p,type:i}}catch{return null}}var It=U__namespace.join(Pe.homedir(),".config","opencrater","painter.lock"),Bn=6e3;function je(t){try{if(!ot.existsSync(It))return;let e=JSON.parse(ot.readFileSync(It,"utf8"));if(e.pid&&e.pid!==process.pid){if(e.startedAt&&Date.now()-e.startedAt<Bn){let i=!0;try{process.kill(e.pid,0);}catch{i=!1;}i&&(t.close(),process.exit(0));}let r=!0;try{process.kill(e.pid,"SIGTERM");}catch{r=!1;}try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,250);}catch{}if(e.rows>0&&e.width>0){let i="\x1B7\x1B[0m",a=" ".repeat(e.width);for(let p=0;p<e.rows;p++)i+=`\x1B[${e.row+p};${e.col}H${a}`;i+="\x1B8",t.write(i);}}}catch{}}var We="";function Gn(t){let e=JSON.stringify(t);if(e!==We){We=e;try{ot.mkdirSync(U__namespace.dirname(It),{recursive:!0}),ot.writeFileSync(It,JSON.stringify(t));}catch{}}}function Hn(){try{JSON.parse(ot.readFileSync(It,"utf8")).pid===process.pid&&ot.unlinkSync(It);}catch{}}var Wt=process.env.OPENCRATER_DEBUG==="1";function _(...t){try{if(!Wt)return;let e=`[opencrater-paint] ${t.map(r=>String(r)).join(" ")}`;console.error(e);try{ot.appendFileSync(U__namespace.join(Pe.homedir(),".config","opencrater","paint.log"),`${new Date().toISOString()} ${e}
5
- `);}catch{}}catch{}}function zn(){let t=process.argv.slice(2),e=o=>{let s=t.indexOf(o);return s>=0?t[s+1]:void 0};t.includes("--debug")&&(Wt=true,process.env.OPENCRATER_DEBUG="1");let r=t.includes("--persist")||process.env.OPENCRATER_WIN_PERSIST==="1",i=Number(e("--console-pid")??"0");i>0&&(process.env.OPENCRATER_WIN_CONSOLE_PID=String(i));let a=e("--payload-file"),p=process.env.OPENCRATER_PAINT;if(a)try{p=ot.readFileSync(a,"utf8");}catch(o){_("payload-file unreadable:",o.message);}if(!p){_("no paint payload (env or --payload-file) \u2014 nothing to draw");return}let n;try{let o=JSON.parse(p);if(o._env&&typeof o._env=="object"){let s=process.env.OPENCRATER_WIN_CONSOLE_PID;Object.assign(process.env,o._env),s&&(process.env.OPENCRATER_WIN_CONSOLE_PID=s),process.env.OPENCRATER_DEBUG==="1"&&(Wt=!0),delete o._env;}n=o;}catch(o){_("paint payload is not valid JSON:",o.message);return}let m=process.env.OPENCRATER_TTY??"/dev/tty",d,y=-1;if(Y){let o=Mn();if(!o){_("Windows: could not start the console pump (powershell.exe)");return}d=o;}else {try{y=ot.openSync(m,"w");}catch(o){_("could not open output device",m,"-",o.message);return}d=Pn(y);}_("painting via",Y?"Windows console pump":m,"format",n.format??"text"),process.env.OPENCRATER_FLOW!=="1"&&!Y&&je(d);let h=0;if(Y)h=Tn()??0;else try{let o=new pe__namespace.WriteStream(y);o.columns&&(h=o.columns);}catch{}h||(h=80);let l=process.env.NO_COLOR===void 0,N=l&&Ln(process.env),I=(n.format??"text").toLowerCase(),O=I==="image"||I==="logo",x=I==="gif"||I==="video",D=x?72:56,F=Y?24:40;if(Y)process.stdout.rows&&(F=process.stdout.rows);else try{let o=new pe__namespace.WriteStream(ot.openSync(m,"w"));o.rows&&(F=o.rows);}catch{}let C=x?Math.max(8,Math.min(16,Math.floor((F-14)/2)*2)):vn,k=O?5:C,b=Math.min(D,h-4);if(b<24){d.close();return}let S=b-4,B=Math.max(1,h-b-1),$=2,T=Date.now(),X=l?`${w}[2m`:"",G=l?`${w}[38;5;214m`:"",L=l?`${w}[0m`:"",M=I,kt=_n(process.env),xt=process.env.OPENCRATER_FLOW==="1",Ye=process.env.OPENCRATER_MUTE==="1",st=n.apiOrigin??"https://api.opencrater.to",At=M==="video"?`${it("\u25B6")} `:M==="audio"?`${it("\u266A")} `:"",fe=false,de=o=>{if(n.impressionId)try{fetch(`${st}/v1/events/engagement`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({impressionId:n.impressionId,events:o}),signal:AbortSignal.timeout(1500)}).catch(()=>{});}catch{}};if(n.reportImpressionUrl&&n.impressionId&&!n.replay)try{fetch(n.reportImpressionUrl,{method:"POST",headers:{"content-type":"application/json",...n.reportImpressionAuth?{authorization:`Bearer ${n.reportImpressionAuth}`}:{}},body:JSON.stringify({impressionId:n.impressionId}),signal:AbortSignal.timeout(8e3)}).catch(()=>{});}catch{}let rt=null,H=null,Pt=0,pt=0,q=null,J="none",Ft=null,Bt=null,at=null,Gt=0,me=0,Z=null,E=0,P=0,Xe=(o,s)=>{let u=o/s,c=O?Math.min(10,Math.floor(S*.35)):S;E=Math.max(4,Math.min(c,Math.round(2*u*k))),P=Math.max(2,Math.min(k,Math.round(c/(2*u))||k)),O&&(P=Math.min(P,k));let f=Math.min(1,o/(E*2),s/(P*2));f<1&&(E=Math.max(8,Math.floor(E*f)),P=Math.max(2,Math.floor(P*f)));},ht=0,qe=()=>{let o=(n.label??"").trim(),s=(n.sponsorLabel??"").trim(),u=s.toLowerCase()===n.title.trim().toLowerCase(),c=o||(s&&!u?`Sponsored Blips \xB7 ${s}`:"Sponsored Blips"),f=[],g=gt??`${st}/x/${n.impressionId}`,v=n.impressionId||n.replay&&gt?Ut(g,it("\u2715")):"",z=ht>0&&!xt?Math.max(0,Math.ceil((ht-Date.now())/1e3)):0,j=z>0?`Auto dismiss in: ${z}s `:"",R=l?z<=5?`${w}[1;38;5;196m`:z<=12?`${w}[1;38;5;178m`:`${w}[1;38;5;35m`:"",A=mt(c,Math.max(8,S-2-j.length)),W=" ".repeat(Math.max(1,S-A.length-j.length-1));f.push(`${X}${A}${L}${W}${R}${j}${L}${G}${v}${L}`);let Q=l?kt!=="none"||(process.env.COLORTERM??"").includes("truecolor")?`${w}[1;38;2;255;184;48m`:`${w}[1;38;5;214m`:"",tt=O&&P>0?S-E-2:S;O||f.push(""),f.push(`${Q}${mt(n.title.toUpperCase(),tt)}${L}`);for(let V of xn(n.body,tt))f.push(V);if(J!=="none"){let V=J==="playing"?`${it("\u23F8")} pause`:J==="paused"?`${it("\u25B6")} play`:`${it("\u25B6")} replay`,ft=Math.max(6,Math.min(14,tt-V.length-5)),dt="\u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588",Tt="";for(let _t=0;_t<ft;_t++){let an=J==="playing"?Math.abs(Math.sin(pt*.9+_t*1.7)*.55+Math.sin(pt*.37+_t*.53)*.45):.05;Tt+=dt[Math.max(0,Math.min(7,Math.floor(an*8)))];}let sn=Ft?Ut(Ft,V):V;f.push(`${it("\u266A")} ${G}${Tt}${L} ${G}${sn}${L}`);}let Xt=process.env.TERM_PROGRAM??"",en=process.env.TERM??"",qt=kt!=="none"||["vscode","ghostty","iTerm.app","WezTerm","Hyper","WarpTerminal","rio","Tabby"].includes(Xt)||/kitty|wezterm|alacritty|foot|rio|ghostty/i.test(en)||process.env.WT_SESSION!==void 0||process.env.ConEmuANSI==="ON"||process.env.VTE_VERSION!==void 0,Kt=(V,ft,dt)=>l?`${w}[48;2;${ft[0]};${ft[1]};${ft[2]};38;2;${dt[0]};${dt[1]};${dt[2]};1m ${V} ${w}[0m`:`[ ${V} ]`,yt=[240,178,50],Zt=[12,12,10],Qt=n.impressionId?`${st}/k/${n.impressionId}`:n.url,$t=[];if(qt){let V=mt(n.cta&&n.cta.trim()!==""?n.cta:"visit sponsor",S-6-At.length);$t.push(Ut(n.url,Kt(`${At}${V} \u2192`,yt,Zt)));}else {let V=(n.cta&&n.cta.trim()!==""?n.cta.trim():"VISIT").toUpperCase();At.length+V.length+1+Qt.length<=S?$t.push(Kt(`${V} ${At}${Qt}`,yt,Zt)):$t.push(Kt(`${At}${Qt}`,yt,Zt));let ft=process.platform==="darwin"?"\u2318-click":"Ctrl-click",dt=mt(`${it("\u2191")} ${ft} the link to open`,S),Tt=l?`${w}[38;2;${yt[0]};${yt[1]};${yt[2]}m`:"";$t.push(`${Tt}${dt}${L}`);}let ke=Bt??(n.impressionId?`${st}/r/${n.impressionId}`:null),Ae=ke&&qt?` \xB7 ${Ut(ke,`${it("\u2691")} report`)}`:"",on=qt?"dismiss: click \u2715 or npx opencrater x \xB7 opt out: npx opencrater off":"dismiss: npx opencrater x \xB7 opt out: npx opencrater off";return $t.push(`${X}${mt(on,Math.max(0,S-jt(Ae)))}${Ae}${L}`),{head:f,tail:$t}},he=0,ge=()=>{let{head:o,tail:s}=qe(),u=`${G}\u256D${"\u2500".repeat(b-2)}\u256E${L}`,c=`${G}\u2570${"\u2500".repeat(b-2)}\u256F${L}`,f=v=>{let z=" ".repeat(Math.max(0,S-jt(v)));return `${G}\u2502${L} ${v}${z} ${G}\u2502${L}`},g;if(O&&P>0&&(H||rt)){let v=S-E-2,z=o[0]??"",j=o.slice(1),R=H?H[Pt%H.length]:null;g=[u,f(z)];let A=Math.max(j.length,P);for(let W=0;W<A;W++){let Q=j[W]??"",tt=" ".repeat(Math.max(0,v-jt(Q))),Xt=W<P&&R?R[W]??" ".repeat(E):" ".repeat(E);g.push(`${G}\u2502${L} ${Q}${tt} ${Xt} ${G}\u2502${L}`);}}else {g=[u,...o.map(f)];let v=Math.max(0,Math.floor((S-E)/2)),z=Math.max(0,S-E-v);if(H&&P>0){let j=H[Pt%H.length];for(let R=0;R<P;R++){let A=j[R]??" ".repeat(E);g.push(`${G}\u2502${L} ${" ".repeat(v)}${A}${" ".repeat(z)} ${G}\u2502${L}`);}}else if(rt&&P>0)for(let j=0;j<P;j++)g.push(`${G}\u2502${L} ${" ".repeat(S)} ${G}\u2502${L}`);}return g.push(...s.map(f)),g.push(c),he=s.length+1,g},Ht=0,be=`${w}[?2026h`,ye=`${w}[?2026l`,$e=0,we=2e3,Ze=8,zt=()=>{let o=ge();Ht=Math.max(Ht,o.length),Gn({pid:process.pid,row:$,col:B,width:b,rows:o.length,startedAt:T,...n.impressionId?{impressionId:n.impressionId}:{},...gt?{dismissUrl:gt}:{}});let s=be+_e,u=Date.now()<$e,c=Math.max(1,$-(u?Ze:2));for(let f=c;f<$;f++)s+=`${w}[${f};${B}H${w}[0m${" ".repeat(b)}`;for(let f=0;f<o.length;f++)s+=`${w}[${$+f};${B}H${o[f]}`;if(rt&&pt%(u?1:3)===0&&P>0){let f=O?$+2:$+o.length-he-P,g=O?B+2+(S-E):B+2+Math.max(0,Math.floor((S-E)/2));s+=`${w}[${f};${g}H${rt}`;}return s+=De+ye,pt++,H&&H.length>1&&Pt++,s},ct=()=>{d.write(zt());},Se=()=>{let o=be+_e+`${w}[0m`,s=" ".repeat(b);for(let u=0;u<Ht;u++)o+=`${w}[${$+u};${B}H${s}`;o+=De+ye,d.write(o);},lt=null,Rt=null,Mt=null,Et=null,gt=null,K=o=>{if(_("cleanup wipe="+o+" elapsed="+(Date.now()-T)+"ms"),fe||(fe=true,de([{type:"dwell",ms:Date.now()-T}])),lt&&clearInterval(lt),Rt&&clearInterval(Rt),Mt&&clearInterval(Mt),o){let s=Number(process.env.OPENCRATER_HOST_PID??0);s>1&&!Y&&setTimeout(()=>{try{process.kill(s,"SIGWINCH");}catch{}},80);}if(Et){try{Et.close();}catch{}Et=null;}if(lt=null,Rt=null,Mt=null,q){try{q.kill("SIGKILL");}catch{}q=null;}if(Z){try{ot.rmSync(Z,{recursive:!0,force:!0});}catch{}Z=null;}if(Se(),Hn(),Y){let s=false,u=()=>{s||(s=true,process.exit(0));};d.closeAndWait().then(u),setTimeout(u,1500).unref?.();return}d.close(),process.exit(0);},Qe=()=>{lt&&clearInterval(lt);let s=E*P>1100?200:Ee;lt=setInterval(ct,H&&H.length>1?s:Lt);},Nt=()=>(Z||(Z=ot.mkdtempSync(U__namespace.join(Pe.tmpdir(),"ocpaint-"))),Z),Jt=async()=>{if(n.mediaPixelUrl&&(I==="image"||I==="logo"))try{let R=await fetch(n.mediaPixelUrl,{signal:AbortSignal.timeout(2500)});if(R.ok){let A=Me(new Uint8Array(await R.arrayBuffer()));if(A&&A.width>=4&&A.height>=2){let W=Buffer.alloc(A.width*A.height*3);for(let Q=0,tt=0;Q<A.rgba.length;Q+=4,tt+=3)W[tt]=A.rgba[Q],W[tt+1]=A.rgba[Q+1],W[tt+2]=A.rgba[Q+2];E=Math.floor(A.width/2),P=Math.floor(A.height/2),H=[ze(W,A.width,A.height,N)];return}}}catch{}if(!n.mediaUrl)return;let o=M==="video",s=await Ue(n.mediaUrl,o?On:Ne);if(!s||!(o?s.type.startsWith("video/"):s.type.startsWith("image/")))return;let c=U__namespace.join(Nt(),"in");try{ot.writeFileSync(c,s.data);}catch{return}let f=Je(c),g=et("ffmpeg")?Fn(c):null,v=g?.match(/crop=(\d+):(\d+)/),z=v?Number(v[1]):f?.w??16,j=v?Number(v[2]):f?.h??9;if(O&&et("ffmpeg")&&z>0&&j>0){let R=Math.min(z,j),A=Math.floor((z-R)/2),W=Math.floor((j-R)/2);g=`crop=${R}:${R}:${A}:${W}`,z=R,j=R,v=null;}if(Xe(z,j),!o&&kt==="iterm2"){rt=Le(s.data,{w:E,h:P}),pt=0;return}if(!o&&kt==="kitty"&&s.type==="image/png"){rt=Dn(s.data,{w:E,h:P}),pt=0;return}if(o&&kt==="iterm2"&&et("ffmpeg"))try{let R=U__namespace.join(Nt(),"out.gif");if(child_process.spawnSync("ffmpeg",["-y","-i",c,"-t","6","-vf","fps=8,scale=280:-1:flags=lanczos","-loop","0",R],{timeout:12e3}).status===0){let W=ot.readFileSync(R);if(W.length<=Ne){rt=Le(W,{w:E,h:P}),pt=0;return}}}catch{}if(et("ffmpeg"))try{let R=o||s.type==="image/gif",A=Wn(c,Nt(),E,P,R,g)??jn(c,E,P,R,N,g);A&&A.length>0&&(H=A,Pt=0,Qe());}catch{}},Yt=(o=0)=>{if(!at)return;let{kind:s,file:u,vol:c}=at,f=Math.max(0,o/1e3),g,v;s==="afplay"?(g="afplay",v=["-v",c.toFixed(2),u]):s==="ffplay"?(g="ffplay",v=["-nodisp","-autoexit","-volume",String(Math.round(c*100))],f>.2&&v.push("-ss",f.toFixed(2)),v.push(u)):s==="mpv"?(g="mpv",v=["--no-video","--really-quiet",`--volume=${Math.round(c*100)}`],f>.2&&v.push(`--start=${f.toFixed(2)}`),v.push(u)):s==="paplay"?(g="paplay",v=[`--volume=${Math.round(c*65536)}`,u]):(g="mpg123",v=["-q","-f",String(Math.round(32768*c))],f>.2&&v.push("-k",String(Math.round(o/26.12))),v.push(u));try{q=Y?child_process.spawn(g,v,{stdio:"ignore",detached:!0,windowsHide:!0}):child_process.spawn(g,v,{stdio:"ignore"}),J="playing",me=Date.now(),q.on("exit",()=>{J!=="paused"&&(J="ended",Gt=0);});}catch{J="none";}},tn=()=>{try{J==="playing"&&q?(J="paused",Gt+=Date.now()-me,q.kill("SIGKILL"),q=null,de([{type:"sound_muted"}])):J==="paused"?at?.canSeek&&Yt(Gt):J==="ended"&&Yt(0);}catch{}ct();},bt=async(o=n.mediaUrl)=>{if(!o||Ye)return;let s=U__namespace.join(Pe.homedir(),".config","opencrater","audio-plays.json");try{let c=[];try{c=JSON.parse(ot.readFileSync(s,"utf8")),Array.isArray(c)||(c=[]);}catch{}let f=xe(Date.now(),c);if(ot.writeFileSync(s,JSON.stringify(f.next)),!f.play)return}catch{}let u=await Ue(o,kn);if(!(!u||!u.type.startsWith("audio/")))try{let c=u.type.includes("wav")?"wav":u.type.includes("ogg")?"ogg":"mp3",f=U__namespace.join(Nt(),`ad.${c}`);ot.writeFileSync(f,u.data);let g=Ce(new Date().getHours());if(et("ffplay"))at={kind:"ffplay",file:f,vol:g,canSeek:!0};else if(!Y&&et("mpv"))at={kind:"mpv",file:f,vol:g,canSeek:!0};else if(process.platform==="darwin"&&et("afplay"))at={kind:"afplay",file:f,vol:g,canSeek:!1};else if(!Y&&et("mpg123")&&c==="mp3")at={kind:"mpg123",file:f,vol:g,canSeek:!0};else if(!Y&&c!=="mp3"&&et("paplay"))at={kind:"paplay",file:f,vol:g,canSeek:!1};else return;Yt(),setTimeout(()=>{try{q?.kill("SIGKILL");}catch{}(J==="playing"||J==="paused")&&(J="ended");},Te).unref?.();}catch{}},ve=()=>{if(!n.impressionId||n.replay)return;let o=U__namespace.join(Pe.homedir(),".config","opencrater","dismiss.signal"),s=Date.now();Rt=setInterval(()=>{try{let u=ot.readFileSync(o,"utf8"),c=JSON.parse(u),f=typeof c.at=="number"&&c.at>=s-5e3,g=!c.impressionId||c.impressionId===n.impressionId;if(f&&g){try{ot.unlinkSync(o);}catch{}Dt(n.campaignId),fetch(`${st}/x/${n.impressionId}`,{signal:AbortSignal.timeout(1500)}).catch(()=>{}),K(!0);return}}catch{}(async()=>{try{let u=await fetch(`${st}/v1/events/dismissed/${n.impressionId}`,{signal:AbortSignal.timeout(1200)});if(!u.ok)return;(await u.json()).dismissed&&(Dt(n.campaignId),K(!0));}catch{}})();},In);},Ie=()=>{if(xt)return;let o=U__namespace.join(Pe.homedir(),".config","opencrater","activity.signal"),s=Date.now(),u=1500;Mt=setInterval(()=>{try{let c=ot.statSync(o).mtimeMs;c>s+u&&c>Date.now()-we&&($e=c+we,ct());}catch{}},150);};if(Y){(async()=>{let o=d.size?await d.size:null;if(o&&o.cols>=24&&(h=o.cols,b=Math.min(D,h-4),S=b-4,B=Math.max(1,h-b-1),_("windows geometry from pump:","cols",h,"width",b,"col",B,"ownerPid",o.pid)),M==="image"||M==="logo"||M==="gif"||M==="video"?await Jt():M==="audio"&&await bt(),n.audioUrl&&M!=="audio"&&bt(n.audioUrl),r){let f=Math.min(Math.max(n.durationMs??se,3e3),12e4);if(ht=Date.now()+f,a)try{ot.unlinkSync(a);}catch{}je(d);let g=H,v=!!(g&&g.length>1);ct(),lt=setInterval(ct,v?Ee:Lt),Ie(),Oe(),ve(),process.on("SIGINT",()=>K(true)),process.on("SIGHUP",()=>K(true)),setTimeout(()=>K(true),f);return}let s=o?.pid??0;s>0&&Nn(n,s)&&(d.close(),process.exit(0)),_("no job-escape (ownerPid",s,") \u2014 bounded toast fallback");let u=Number(process.env.OPENCRATER_WIN_HOLD_MS),c=u>0?u:Math.min(n.durationMs??se,5e3);if(ht=Date.now()+c,d.write(zt()),await new Promise(f=>{let g=setInterval(()=>{if(Date.now()>=ht){clearInterval(g),f();return}d.write(zt());},Lt);}),Se(),Z)try{ot.rmSync(Z,{recursive:!0,force:!0});}catch{}await d.closeAndWait(),process.exit(0);})();return}if(xt){(async()=>{M==="image"||M==="logo"||M==="gif"||M==="video"?await Jt():M==="audio"&&await bt(),n.audioUrl&&M!=="audio"&&bt(n.audioUrl);let o=H;o&&o.length>1&&(H=[o[0]]);let s=ge(),u=" ".repeat(Math.max(0,h-b-2)),c=`\r
6
- `;for(let g of s)c+=`${u}${g}\r
7
- `;rt&&P>0&&(c+=`${u}${rt}\r
8
- `),d.write(c);let f=q?Te+1e3:250;setTimeout(()=>{if(q)try{q.kill("SIGKILL");}catch{}if(Z)try{ot.rmSync(Z,{recursive:!0,force:!0});}catch{}d.close(),process.exit(0);},f);})();return}ct(),lt=setInterval(ct,Lt);function Oe(){if(!(!n.impressionId&&!n.replay||xt))try{let o=crypto.randomBytes(8).toString("hex"),s=Fe__namespace.createServer((u,c)=>{if(!u.url||!u.url.includes(o)){c.writeHead(404).end();return}if(u.url.startsWith("/p/")){Re(n.campaignId),n.impressionId?(c.writeHead(302,{location:`${st}/r/${n.impressionId}`}),c.end()):(c.writeHead(200,{"content-type":"text/html; charset=utf-8"}),c.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(u.url.startsWith("/a/")){tn(),c.writeHead(200,{"content-type":"text/html; charset=utf-8"}),c.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}c.writeHead(200,{"content-type":"text/html; charset=utf-8"}),c.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>'),Dt(n.campaignId),!n.replay&&n.impressionId&&fetch(`${st}/x/${n.impressionId}`,{signal:AbortSignal.timeout(2e3)}).catch(()=>{}),setTimeout(()=>K(!0),150);});s.unref(),s.listen(0,"127.0.0.1",()=>{let u=s.address();u&&typeof u=="object"&&(gt=`http://127.0.0.1:${u.port}/x/${o}`,Ft=`http://127.0.0.1:${u.port}/a/${o}`,Bt=`http://127.0.0.1:${u.port}/p/${o}`,Et=s,ct());}),s.on("error",()=>{gt=null,Bt=null;});}catch{}}try{ot.writeFileSync(U__namespace.join(Pe.homedir(),".config","opencrater","last-ad.json"),JSON.stringify({payload:n,at:Date.now()}));}catch{}Oe(),ve(),Ie(),M==="image"||M==="logo"||M==="gif"||M==="video"?Jt():M==="audio"&&bt(),n.audioUrl&&M!=="audio"&&bt(n.audioUrl);let Vt=n.durationMs??(M==="video"?18e3:M==="audio"?16e3:se);ht=Date.now()+Vt,setTimeout(()=>K(true),Vt),process.on("SIGTERM",()=>K(true)),process.on("SIGINT",()=>K(true)),process.on("SIGHUP",()=>K(true)),setTimeout(()=>K(true),Vt+5e3).unref?.();}typeof te<"u"&&typeof module<"u"&&te.main===module&&zn();
9
- exports.windowsVtOk=lr;
2
+ 'use strict';var child_process=require('child_process'),crypto=require('crypto'),Ft=require('http'),re=require('fs'),Pt=require('os'),L=require('path'),zlib=require('zlib'),dt=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 Ft__namespace=/*#__PURE__*/_interopNamespace(Ft);var re__namespace=/*#__PURE__*/_interopNamespace(re);var Pt__namespace=/*#__PURE__*/_interopNamespace(Pt);var L__namespace=/*#__PURE__*/_interopNamespace(L);var dt__namespace=/*#__PURE__*/_interopNamespace(dt);var et=(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 At(e){return e>=21||e<8?.2:.4}function Ot(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 it(e=process.env){return L__namespace.join(Pt__namespace.homedir(),".config","opencrater")}var un=600*1e3;function rt(){return L__namespace.join(it(),"blocked-ads.json")}function ot(){return L__namespace.join(it(),"reported-ads.json")}function dn(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 pn(e){try{let t=JSON.parse(re__namespace.readFileSync(rt(),"utf8"));return dn(t&&typeof t=="object"?t:{},e)}catch{return {}}}function Ne(e,t=Date.now()){if(e)try{let i=pn(t);i[e]=t+un,re__namespace.mkdirSync(L__namespace.dirname(rt()),{recursive:!0}),re__namespace.writeFileSync(rt(),JSON.stringify(i));}catch{}}function mn(){try{let e=JSON.parse(re__namespace.readFileSync(ot(),"utf8"));return e&&typeof e=="object"?e:{}}catch{return {}}}function Rt(e,t=Date.now()){if(e)try{let i=mn();i[e]=t,re__namespace.mkdirSync(L__namespace.dirname(ot()),{recursive:!0}),re__namespace.writeFileSync(ot(),JSON.stringify(i));}catch{}}var hn=[137,80,78,71,13,10,26,10];function Tt(e){try{if(e.length<45)return null;for(let A=0;A<8;A++)if(e[A]!==hn[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,Mt=140,at=12e3,In=9;var Cn=1500,Wt=3*1024*1024,jn=12*1024*1024,An=12*1024*1024,On=6e3,Et=25e3,zt=64,k="\x1B",Pn="\x07",Nt=`${k}7`,_t=`${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 Rn(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 J=process.platform==="win32";function oe(e){return J?`${e}\uFE0E`:e}function Tn(e){let t=()=>{try{re.closeSync(e);}catch{}};return {write:i=>{try{re.writeSync(e,i);}catch{}},close:t,closeAndWait:async()=>t()}}var Mn=["$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
+ `);function Gt(){return `${process.env.SystemRoot||process.env.windir||"C:\\Windows"}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`}function Wn(){try{let e=Buffer.from(Mn,"utf16le").toString("base64"),t=Gt(),i="ignore";if(process.env.OPENCRATER_DEBUG==="1")try{i=re.openSync(L__namespace.join(Pt.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 En(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(Gt(),["-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 Nn(e,t){try{let i=L__namespace.join(Pt.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=En(u.join(" "));return E("escape: wmi persistent painter pid",n),n>0}catch(i){return E("escape failed",i.message),false}}function hi(e){return !!(e.WT_SESSION||e.TERM_PROGRAM||e.ConEmuANSI==="ON"||e.ANSICON)}function _n(){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 Ln(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 Lt(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}${Pn}`}function Dn(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 qn(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 lt(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 Un=[" ","\u2598","\u259D","\u2580","\u2596","\u258C","\u259E","\u259B","\u2597","\u259A","\u2590","\u259C","\u2584","\u2599","\u259F","\u2588"];function Ht(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;${lt(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;${lt(b[0],b[1],b[2])};48;5;${lt($[0],$[1],$[2])}m`;F!==y&&(p+=F,y=F),p+=Un[A];}p+=`${k}[0m`,a.push(p);}return a}function Fn(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),zt);if(M===0)return null;let S=[];for(let x=0;x<M;x++)S.push(Ht(g.stdout.subarray(x*c,(x+1)*c),n,m,a));return S}function Bn(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<=zt;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
+ `).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 Jt(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 zn(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=Jt(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 J?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 Dt(e,t){try{let i=await fetch(e,{signal:AbortSignal.timeout(On)});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(Pt.homedir(),".config","opencrater","painter.lock"),Gn=6e3;function qt(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<Gn){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 Ut="";function Hn(e){let t=JSON.stringify(e);if(t!==Ut){Ut=t;try{re.mkdirSync(L__namespace.dirname(Se),{recursive:!0}),re.writeFileSync(Se,JSON.stringify(e));}catch{}}}function Jn(){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(Pt.homedir(),".config","opencrater","paint.log"),`${new Date().toISOString()} ${t}
5
+ `);}catch{}}catch{}}function Yn(){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(J){let r=Wn();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=Tn(y);}E("painting via",J?"Windows console pump":m,"format",n.format??"text"),process.env.OPENCRATER_FLOW!=="1"&&!J&&qt(p);let g=0;if(J)g=_n()??0;else try{let r=new dt__namespace.WriteStream(y);r.columns&&(g=r.columns);}catch{}g||(g=80);let c=process.env.NO_COLOR===void 0,M=c&&qn(process.env),S=(n.format??"text").toLowerCase(),x=S==="image"||S==="logo",A=S==="gif"||S==="video",N=A?72:56,U=J?24:40;if(J)process.stdout.rows&&(U=process.stdout.rows);else try{let r=new dt__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)):In,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=Ln(process.env),Ae=process.env.OPENCRATER_FLOW==="1",Yt=process.env.OPENCRATER_MUTE==="1",se=n.apiOrigin??"https://api.opencrater.to",Ce=R==="video"?`${oe("\u25B6")} `:R==="audio"?`${oe("\u266A")} `:"",pt=false,mt=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{}};if(n.reportImpressionUrl&&n.impressionId&&!n.replay)try{fetch(n.reportImpressionUrl,{method:"POST",headers:{"content-type":"application/json",...n.reportImpressionAuth?{authorization:`Bearer ${n.reportImpressionAuth}`}:{}},body:JSON.stringify({impressionId:n.impressionId}),signal:AbortSignal.timeout(8e3)}).catch(()=>{});}catch{}let ie=null,z=null,Oe=0,ue=0,X=null,H="none",Ue=null,Fe=null,ae=null,Be=0,gt=0,Z=null,T=0,O=0,Xt=(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,Kt=()=>{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 Rn(n.body,ee))d.push(Y);if(H!=="none"){let Y=H==="playing"?`${oe("\u23F8")} pause`:H==="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 ln=H==="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(ln*8)))];}let an=Ue?Le(Ue,Y):Y;d.push(`${oe("\u266A")} ${B}${We}${_} ${B}${an}${_}`);}let Ve=process.env.TERM_PROGRAM??"",nn=process.env.TERM??"",Xe=Ie!=="none"||["vscode","ghostty","iTerm.app","WezTerm","Hyper","WarpTerminal","rio","Tabby"].includes(Ve)||/kitty|wezterm|alacritty|foot|rio|ghostty/i.test(nn)||process.env.WT_SESSION!==void 0||process.env.ConEmuANSI==="ON"||process.env.VTE_VERSION!==void 0,Ke=(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],Ze=[12,12,10],Qe=n.impressionId?`${se}/k/${n.impressionId}`:n.url,we=[];if(Xe){let Y=me(n.cta&&n.cta.trim()!==""?n.cta:"visit sponsor",$-6-Ce.length);we.push(Le(n.url,Ke(`${Ce}${Y} \u2192`,ye,Ze)));}else {let Y=(n.cta&&n.cta.trim()!==""?n.cta.trim():"VISIT").toUpperCase();Ce.length+Y.length+1+Qe.length<=$?we.push(Ke(`${Y} ${Ce}${Qe}`,ye,Ze)):we.push(Ke(`${Ce}${Qe}`,ye,Ze));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 Ct=Fe??(n.impressionId?`${se}/r/${n.impressionId}`:null),jt=Ct&&Xe?` \xB7 ${Le(Ct,`${oe("\u2691")} report`)}`:"",sn=Xe?"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(sn,Math.max(0,$-De(jt)))}${jt}${_}`),{head:d,tail:we}},ht=0,bt=()=>{let{head:r,tail:s}=Kt(),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))),Ve=q<O&&P?P[q]??" ".repeat(T):" ".repeat(T);h.push(`${B}\u2502${_} ${Q}${ee} ${Ve} ${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),ht=s.length+1,h},ze=0,yt=`${k}[?2026h`,wt=`${k}[?2026l`,kt=0,$t=2e3,Qt=8,Ge=()=>{let r=bt();ze=Math.max(ze,r.length),Hn({pid:process.pid,row:w,col:F,width:b,rows:r.length,startedAt:W,...n.impressionId?{impressionId:n.impressionId}:{},...he?{dismissUrl:he}:{}});let s=yt+Nt,f=Date.now()<kt,l=Math.max(1,w-(f?Qt: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-ht-O,h=x?F+2+($-T):F+2+Math.max(0,Math.floor(($-T)/2));s+=`${k}[${d};${h}H${ie}`;}return s+=_t+wt,ue++,z&&z.length>1&&Oe++,s},le=()=>{p.write(Ge());},vt=()=>{let r=yt+Nt+`${k}[0m`,s=" ".repeat(b);for(let f=0;f<ze;f++)r+=`${k}[${w+f};${F}H${s}`;r+=_t+wt,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"),pt||(pt=true,mt([{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&&!J&&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(vt(),Jn(),J){let s=false,f=()=>{s||(s=true,process.exit(0));};p.closeAndWait().then(f),setTimeout(f,1500).unref?.();return}p.close(),process.exit(0);},en=()=>{ce&&clearInterval(ce);let s=T*O>1100?200:Mt;ce=setInterval(le,z&&z.length>1?s:_e);},Me=()=>(Z||(Z=re.mkdtempSync(L__namespace.join(Pt.tmpdir(),"ocpaint-"))),Z),He=async()=>{if(n.mediaPixelUrl&&(S==="image"||S==="logo"))try{let P=await fetch(n.mediaPixelUrl,{signal:AbortSignal.timeout(2500)});if(P.ok){let C=Tt(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=[Ht(q,C.width,C.height,M)];return}}}catch{}if(!n.mediaUrl)return;let r=R==="video",s=await Dt(n.mediaUrl,r?jn:Wt);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=Jt(l),h=te("ffmpeg")?zn(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(Xt(G,D),!r&&Ie==="iterm2"){ie=Lt(s.data,{w:T,h:O}),ue=0;return}if(!r&&Ie==="kitty"&&s.type==="image/png"){ie=Dn(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<=Wt){ie=Lt(q,{w:T,h:O}),ue=0;return}}}catch{}if(te("ffmpeg"))try{let P=r||s.type==="image/gif",C=Bn(l,Me(),T,O,P,h)??Fn(l,T,O,P,M,h);C&&C.length>0&&(z=C,Oe=0,en());}catch{}},Je=(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=J?child_process.spawn(h,v,{stdio:"ignore",detached:!0,windowsHide:!0}):child_process.spawn(h,v,{stdio:"ignore"}),H="playing",gt=Date.now(),X.on("exit",()=>{H!=="paused"&&(H="ended",Be=0);});}catch{H="none";}},tn=()=>{try{H==="playing"&&X?(H="paused",Be+=Date.now()-gt,X.kill("SIGKILL"),X=null,mt([{type:"sound_muted"}])):H==="paused"?ae?.canSeek&&Je(Be):H==="ended"&&Je(0);}catch{}le();},be=async(r=n.mediaUrl)=>{if(!r||Yt)return;let s=L__namespace.join(Pt.homedir(),".config","opencrater","audio-plays.json");try{let l=[];try{l=JSON.parse(re.readFileSync(s,"utf8")),Array.isArray(l)||(l=[]);}catch{}let d=Ot(Date.now(),l);if(re.writeFileSync(s,JSON.stringify(d.next)),!d.play)return}catch{}let f=await Dt(r,An);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=At(new Date().getHours());if(te("ffplay"))ae={kind:"ffplay",file:d,vol:h,canSeek:!0};else if(!J&&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(!J&&te("mpg123")&&l==="mp3")ae={kind:"mpg123",file:d,vol:h,canSeek:!0};else if(!J&&l!=="mp3"&&te("paplay"))ae={kind:"paplay",file:d,vol:h,canSeek:!1};else return;Je(),setTimeout(()=>{try{X?.kill("SIGKILL");}catch{}(H==="playing"||H==="paused")&&(H="ended");},Et).unref?.();}catch{}},St=()=>{if(!n.impressionId||n.replay)return;let r=L__namespace.join(Pt.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{}})();},Cn);},xt=()=>{if(Ae)return;let r=L__namespace.join(Pt.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()-$t&&(kt=l+$t,le());}catch{}},150);};if(J){(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 He():R==="audio"&&await be(),n.audioUrl&&R!=="audio"&&be(n.audioUrl),i){let d=Math.min(Math.max(n.durationMs??at,3e3),12e4);if(ge=Date.now()+d,a)try{re.unlinkSync(a);}catch{}qt(p);let h=z,v=!!(h&&h.length>1);le(),ce=setInterval(le,v?Mt:_e),xt(),It(),St(),process.on("SIGINT",()=>K(true)),process.on("SIGHUP",()=>K(true)),setTimeout(()=>K(true),d);return}let s=r?.pid??0;s>0&&Nn(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??at,5e3);if(ge=Date.now()+l,p.write(Ge()),await new Promise(d=>{let h=setInterval(()=>{if(Date.now()>=ge){clearInterval(h),d();return}p.write(Ge());},_e);}),vt(),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 He():R==="audio"&&await be(),n.audioUrl&&R!=="audio"&&be(n.audioUrl);let r=z;r&&r.length>1&&(z=[r[0]]);let s=bt(),f=" ".repeat(Math.max(0,g-b-2)),l=`\r
6
+ `;for(let h of s)l+=`${f}${h}\r
7
+ `;ie&&O>0&&(l+=`${f}${ie}\r
8
+ `),p.write(l);let d=X?Et+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 It(){if(!(!n.impressionId&&!n.replay||Ae))try{let r=crypto.randomBytes(8).toString("hex"),s=Ft__namespace.createServer((f,l)=>{if(!f.url||!f.url.includes(r)){l.writeHead(404).end();return}if(f.url.startsWith("/p/")){Rt(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/")){tn(),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}`,Ue=`http://127.0.0.1:${f.port}/a/${r}`,Fe=`http://127.0.0.1:${f.port}/p/${r}`,Te=s,le());}),s.on("error",()=>{he=null,Fe=null;});}catch{}}try{re.writeFileSync(L__namespace.join(Pt.homedir(),".config","opencrater","last-ad.json"),JSON.stringify({payload:n,at:Date.now()}));}catch{}It(),St(),xt(),R==="image"||R==="logo"||R==="gif"||R==="video"?He():R==="audio"&&be(),n.audioUrl&&R!=="audio"&&be(n.audioUrl);let Ye=n.durationMs??(R==="video"?18e3:R==="audio"?16e3:at);ge=Date.now()+Ye,setTimeout(()=>K(true),Ye),process.on("SIGTERM",()=>K(true)),process.on("SIGINT",()=>K(true)),process.on("SIGHUP",()=>K(true)),setTimeout(()=>K(true),Ye+5e3).unref?.();}typeof et<"u"&&typeof module<"u"&&et.main===module&&Yn();
9
+ exports.windowsVtOk=hi;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencrater",
3
- "version": "1.1.42",
3
+ "version": "1.3.0",
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",