opencrater 1.1.22 → 1.1.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,9 +1,9 @@
1
1
  #!/usr/bin/env node
2
- 'use strict';var crypto=require('crypto'),d=require('fs'),z=require('os'),u=require('path'),child_process=require('child_process'),se=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 z__namespace=/*#__PURE__*/_interopNamespace(z);var u__namespace=/*#__PURE__*/_interopNamespace(u);var se__namespace=/*#__PURE__*/_interopNamespace(se);var _=(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')});function ue(e=process.env){return u__namespace.join(z__namespace.homedir(),".config","opencrater")}function C(e=process.env){return u__namespace.join(ue(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 y(e){return typeof e=="number"&&Number.isFinite(e)}function pe(e){if(typeof e!="object"||e===null)return null;let t=e;return !y(t.minIntervalSeconds)||!y(t.serveTimeoutMs)||!y(t.preloadPoolSize)||typeof t.killSwitch!="boolean"?null:{minIntervalSeconds:t.minIntervalSeconds,serveTimeoutMs:t.serveTimeoutMs,preloadPoolSize:t.preloadPoolSize,killSwitch:t.killSwitch,displayDurationSeconds:y(t.displayDurationSeconds)?t.displayDurationSeconds:25,minSdkVersion:typeof t.minSdkVersion=="string"?t.minSdkVersion:""}}function de(e){if(!Array.isArray(e))return [];let t=[];for(let n of e){if(typeof n!="object"||n===null)continue;let o=n,r=o.blip;if(!y(o.renderBy)||typeof r!="object"||r===null||typeof r.impressionId!="string"||typeof r.clickUrl!="string"||typeof r.sponsorLabel!="string"||typeof r.creative!="object"||r.creative===null)continue;let s=r.creative;typeof s.title!="string"||typeof s.body!="string"||t.push({blip:{impressionId:r.impressionId,...typeof r.campaignId=="string"?{campaignId:r.campaignId}:{},clickUrl:r.clickUrl,sponsorLabel:r.sponsorLabel,creative:{format:"text",title:s.title,body:s.body,...typeof s.cta=="string"?{cta:s.cta}:{}}},renderBy:o.renderBy});}return t}function fe(e){if(typeof e!="object"||e===null||Array.isArray(e))return {};let t={};for(let[n,o]of Object.entries(e)){if(!Array.isArray(o))continue;let r=o.filter(s=>typeof s=="string"&&s.length<=64);t[n]=r.slice(0,64);}return t}function ge(e){if(!Array.isArray(e))return [];let t=[];for(let n of e){if(typeof n!="object"||n===null)continue;let o=n;if(!(typeof o.topic!="string"||!y(o.at))&&(t.push({topic:o.topic.slice(0,32),at:o.at}),t.length>=24))break}return t}function me(e){if(!Array.isArray(e))return [];let t=[],n=new Set;for(let o of e){if(typeof o!="object"||o===null)continue;let r=o;if(typeof r.key!="string"||typeof r.package!="string"||r.key===""||r.package==="")continue;let s=`${r.package}\0${r.key}`;if(!n.has(s)&&(n.add(s),t.push({key:r.key,package:r.package}),t.length>=32))break}return t}function he(e){if(typeof e!="object"||e===null)return null;let t=e,n={};if(typeof t.savedEnv=="object"&&t.savedEnv!==null)for(let[o,r]of Object.entries(t.savedEnv))(typeof r=="string"||r===null)&&(n[o]=r);return {active:t.active===true,savedEnv:n}}function ye(e){if(typeof e!="object"||e===null)return null;let t=e,n=o=>y(o)&&o>=0?o:0;return {turns:n(t.turns),lastLimitAt:n(t.lastLimitAt),lastDepletedAt:n(t.lastDepletedAt),lastBackupAt:n(t.lastBackupAt)}}function ke(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:y(n.lastShownAt)&&n.lastShownAt>=0?n.lastShownAt:0,optOut:n.optOut===true,disclosureShown:n.disclosureShown===true,cachedConfig:pe(n.cachedConfig),allowedPlacements:fe(n.allowedPlacements),sessionTopics:ge(n.sessionTopics),integrations:me(n.integrations),devToken:typeof n.devToken=="string"?n.devToken:null,computeRouting:he(n.computeRouting),computeCards:ye(n.computeCards),configFetchedAt:y(n.configFetchedAt)&&n.configFetchedAt>=0?n.configFetchedAt:0,pool:de(n.pool)}}function m(e=process.env){let t=C(e);try{let n=d__namespace.readFileSync(t,"utf8"),o=JSON.parse(n);return ke(o)}catch{let n=G();try{R(n,e);}catch{}return n}}function R(e,t=process.env,n={}){let o=C(t),r=u__namespace.dirname(o);d__namespace.mkdirSync(r,{recursive:true});try{let c=JSON.parse(d__namespace.readFileSync(o,"utf8"));typeof c.lastShownAt=="number"&&c.lastShownAt>e.lastShownAt&&(e={...e,lastShownAt:c.lastShownAt}),!n.allowClearToken&&typeof c.devToken=="string"&&e.devToken==null&&(e={...e,devToken:c.devToken});}catch{}let s=u__namespace.join(r,`.state.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`);d__namespace.writeFileSync(s,JSON.stringify(e,null,2)+`
3
- `,"utf8");let i=new Set(["EPERM","EACCES","EBUSY","EEXIST"]);for(let c=0;;c++)try{d__namespace.renameSync(s,o);return}catch(a){let p=a.code??"";if(c>=4||!i.has(p)){try{d__namespace.rmSync(s,{force:!0});}catch{}if(c>=4)return;throw a}try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(c+1));}catch{}}}function w(e,t=process.env){let n={...m(t),...e};return R(n,t),n}var K={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"],generic:["SessionStart","Stop"]};var k=["claude_code","codex","gemini_cli","copilot_cli"];function b(e){return e.includes("opencrater-hook")}function Se(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function we(e,t){return b(e)&&new RegExp(`--package ['"]?${Se(t)}['"]?`).test(e)}function Z(e,t){return t?we(e,t):b(e)&&!/--package\b/.test(e)}function V(e){return /^[A-Za-z0-9@_./:-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}var q='"$HOME/.config/opencrater/runtime/node_modules/opencrater/dist/hook.js"',W="$env:USERPROFILE\\.config\\opencrater\\runtime\\node_modules\\opencrater\\dist\\hook.js";function H(e,t,n,o){let r=`--placement ${t}`;return n&&(r+=` --key ${V(n)}`),o&&(r+=` --package ${V(o)}`),r+=` --host ${e}`,`{ if [ -f ${q} ]; then node ${q} ${r}; else npx -y -p opencrater opencrater-hook ${r}; fi; } 2>/dev/null || true`}function be(e,t,n,o){let r=`--placement ${t}`;return n&&(r+=` --key '${n}'`),o&&(r+=` --package '${o}'`),r+=` --host ${e}`,`try { if (Test-Path "${W}") { node "${W}" ${r} } else { npx -y -p opencrater opencrater-hook ${r} } } catch {}`}function Y(e,t,n,o){return H(e,t,n,o)}function ee(e,t){let n=z__namespace.homedir();switch(e){case "claude_code":{let o=t.CLAUDE_CONFIG_DIR;return o&&o.trim()!==""?o:u__namespace.join(n,".claude")}case "codex":{let o=t.CODEX_HOME;return o&&o.trim()!==""?o:u__namespace.join(n,".codex")}case "gemini_cli":return u__namespace.join(n,".gemini");case "copilot_cli":{let o=t.COPILOT_HOME;return o&&o.trim()!==""?o:u__namespace.join(n,".copilot")}default:return u__namespace.join(n,".opencrater-unknown")}}function E(e,t=process.env){let n=ee(e,t);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");default:return u__namespace.join(n,"hooks.json")}}var ve={claude_code:["claude"],codex:["codex"],gemini_cli:["gemini"],copilot_cli:["copilot"]};function Ce(e,t){if(e.length===0)return false;let n=(t.PATH??t.Path??"").split(u__namespace.delimiter).filter(Boolean),o=process.platform==="win32"?["",".exe",".cmd",".bat"]:[""];for(let r of n)for(let s of e)for(let i of o)try{if(d__namespace.existsSync(u__namespace.join(r,s+i)))return !0}catch{}return false}function Oe(e,t=process.env){try{if(d__namespace.existsSync(ee(e,t)))return !0}catch{}return Ce(ve[e]??[],t)}function M(e=process.env){return k.filter(t=>Oe(t,e))}function I(e){let t;try{t=d__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 U(e,t){let n=u__namespace.dirname(e);d__namespace.mkdirSync(n,{recursive:true});let o=u__namespace.join(n,`.${u__namespace.basename(e)}.${process.pid}.tmp`);d__namespace.writeFileSync(o,JSON.stringify(t,null,2)+`
4
- `,"utf8"),d__namespace.renameSync(o,e);}function Ae(e,t){return Array.isArray(e.hooks)&&e.hooks.some(n=>typeof n.command=="string"&&Z(n.command,t))}function Pe(e,t,n,o){let r=E(e),s=I(r),i=s.hooks&&typeof s.hooks=="object"?s.hooks:{};if(o.every(a=>{let p=Y(e,a,t,n);return (Array.isArray(i[a])?i[a]:[]).some(l=>Array.isArray(l.hooks)&&l.hooks.some(h=>h.command===p))}))return "nochange";for(let a of o){let l=(Array.isArray(i[a])?i[a]:[]).filter(h=>!Ae(h,n));l.push({matcher:"",hooks:[{type:"command",command:Y(e,a,t,n)}]}),i[a]=l;}return s.hooks=i,U(r,s),"wrote"}var X=12;function Re(e,t){return [e.bash,e.powershell,e.command].some(n=>typeof n=="string"&&Z(n,t))}function Ee(e,t,n,o){let r=E(e),s=I(r);typeof s.version!="number"&&(s.version=1);let i=s.hooks&&typeof s.hooks=="object"?s.hooks:{};if(o.every(a=>{let p=H(e,a,t,n);return (Array.isArray(i[a])?i[a]:[]).some(l=>l.bash===p&&l.timeoutSec===X)}))return "nochange";for(let a of o){let l=(Array.isArray(i[a])?i[a]:[]).filter(h=>!Re(h,n));l.push({type:"command",bash:H(e,a,t,n),powershell:be(e,a,t,n),timeoutSec:X}),i[a]=l;}return s.hooks=i,U(r,s),"wrote"}function $(e){return [...K[e]]}function B(e,t,n){let o=$(e);return o.length===0?"nochange":e==="copilot_cli"?Ee(e,t,n,o):Pe(e,t,n,o)}function O(e,t,n=process.env){return M(n).map(o=>{try{let r=B(o,e,t);return {host:o,status:r,events:$(o)}}catch(r){return {host:o,status:"error",events:[],error:r.message}}})}function F(e=process.env){let t=[];for(let n of k){let o;try{o=I(E(n,e));}catch{continue}let r=o.hooks;if(!(!r||typeof r!="object"))for(let[s,i]of Object.entries(r))for(let c of Array.isArray(i)?i:[]){let a=c,p=Array.isArray(a.hooks)?a.hooks.find(f=>typeof f.command=="string"&&b(f.command))?.command:void 0,l=[a.bash,a.command,a.powershell].find(f=>typeof f=="string"&&b(f)),h=p??l;h&&t.push({host:n,event:s,command:h});}}return t}function ne(e=process.env){let t=0;for(let n of k){let o=E(n,e),r;try{r=I(o);}catch{continue}let s=r.hooks;if(!s||typeof s!="object")continue;let i=s,c=false;for(let a of Object.keys(i)){let p=Array.isArray(i[a])?i[a]:[],l=p.filter(h=>{let f=h,J=Array.isArray(f.hooks)&&f.hooks.some(v=>typeof v.command=="string"&&b(v.command))||[f.bash,f.powershell,f.command].some(v=>typeof v=="string"&&b(v));return J&&t++,!J});l.length!==p.length&&(c=true,l.length>0?i[a]=l:delete i[a]);}if(c)try{let a=Object.keys(r).filter(l=>l!=="version"&&l!=="hooks"),p=n==="copilot_cli"||n==="codex";Object.keys(i).length===0&&a.length===0&&p?d__namespace.rmSync(o,{force:!0}):U(o,r);}catch{}}return t}var A="1.1.22";var Ie="https://api.opencrater.to";function x(e,t=process.env){let n=t.OPENCRATER_API_ORIGIN;return (e??(n&&n.trim()!==""?n:Ie)).replace(/\/+$/,"")}function xe(){return u__namespace.join(z__namespace.homedir(),".config","opencrater","runtime")}function Te(e){return ["install","--prefix",e,"opencrater@latest","--silent","--no-audit","--no-fund"]}function T(e=xe()){if(process.env.VITEST||process.env.OPENCRATER_DISABLE_RUNTIME_PIN)return false;try{return child_process.spawnSync("npm",Te(e),{stdio:"ignore",windowsHide:!0,shell:process.platform==="win32"}).status===0}catch{return false}}function Ne(){let e=process.env.OPENCRATER_WEB_ORIGIN;return e&&e.trim()!==""?e.replace(/\/$/,""):x().replace("//api.","//").replace(/\/$/,"")}function je(e){try{let t=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";child_process.spawn(t,[e],{stdio:"ignore",detached:!0,shell:process.platform==="win32"}).unref();}catch{}}function _e(e){let t=se__namespace.createInterface({input:process.stdin,output:process.stdout});return new Promise(n=>t.question(e,o=>(t.close(),n(o))))}function D(e){return `$${(e/1e6).toFixed(2)}`}async function L(e,t){try{let n=new URL(`${x()}/v1/dev/me`);t&&n.searchParams.set("installId",t);let o=await fetch(n,{headers:{authorization:`Bearer ${e}`}});return o.ok?await o.json():null}catch{return null}}async function He(){let e=`${Ne()}/dev/link`;console.log("Sign in and generate a CLI token here (we tried to open it):"),console.log(` ${e}
5
- `),je(e);let t=(await _e("Paste your token (ocd_\u2026): ")).trim();if(!t.startsWith("ocd_"))return console.error("That doesn't look like a token (should start with ocd_)."),1;let n=await L(t,m().installId);if(!n)return console.error("Couldn't verify that token \u2014 check it and try again."),1;w({devToken:t}),console.log(`
6
- \u2713 Signed in as ${n.displayName}.`),console.log(` Compute balance: ${D(n.balanceMicroUsd)} \xB7 tier: ${n.trustTier}`);let o=O().filter(r=>r.status!=="error").map(r=>r.host);return o.length?(console.log(` Wired into: ${o.join(", ")}`),process.stdout.write(" Pinning fast runtime (one-time, ~15s)\u2026 "),console.log(T()?"\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 Me(){let e=m().devToken;if(!e)return console.error("Not signed in. Run: opencrater login"),1;let t=await L(e,m().installId);return t?(console.log(`Compute balance: ${D(t.balanceMicroUsd)}`),console.log(` signed in as: ${t.displayName} \xB7 tier: ${t.trustTier}`),0):(console.error("Couldn't reach OpenCrater (or your session expired \u2014 try: opencrater login)."),1)}function Ue(){return R({...m(),devToken:null},process.env,{allowClearToken:true}),console.log("Signed out of the OpenCrater compute wallet on this machine."),0}async function Be(e){let t=m().devToken;if(!t)return console.error("Not signed in. Run: opencrater login"),1;let n=await L(t,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 o=`${x().replace(/\/$/,"")}/gateway`,r=u__namespace.join(u__namespace.dirname(C()),"claude-gateway.settings.json");try{d__namespace.mkdirSync(u__namespace.dirname(r),{recursive:!0}),d__namespace.writeFileSync(r,JSON.stringify({apiKeyHelper:`echo ${t}`}),{mode:384});}catch(c){return console.error(`Couldn't write gateway settings: ${c.message}`),1}n&&console.log(`Launching Claude Code on OpenCrater compute \xB7 balance ${D(n.balanceMicroUsd)}`);let s={...process.env,ANTHROPIC_BASE_URL:o};delete s.ANTHROPIC_API_KEY;let i=child_process.spawn("claude",[...e,"--settings",r],{stdio:"inherit",env:s,shell:process.platform==="win32"});return await new Promise(c=>{i.on("exit",a=>c(a??0)),i.on("error",a=>{console.error(`Couldn't launch claude: ${a.message}`),console.error("Is Claude Code installed? https://claude.com/claude-code"),c(127);});})}function ae(e){let t=new Map,n=[];for(let o=0;o<e.length;o++){let r=e[o];if(r!==void 0)if(r.startsWith("--")){let s=r.indexOf("=");if(s!==-1)t.set(r.slice(2,s),r.slice(s+1));else {let i=e[o+1];i!==void 0&&!i.startsWith("--")?(t.set(r.slice(2),i),o++):t.set(r.slice(2),"true");}}else n.push(r);}return {flags:t,rest:n}}function ce(e,t){let n=m();n.integrations.some(o=>o.key===e&&o.package===t)||w({integrations:[...n.integrations,{key:e,package:t}].slice(-32)});}function N(e,t){let n=t||"compute hooks";if(e.length===0){console.log(`No supported AI CLIs detected yet \u2014 OpenCrater will wire ${n} automatically the moment you install one (it re-checks on the next session).`);return}console.log(`OpenCrater wired ${n} into:`);for(let o of e)if(o.status==="error")console.log(` \u2717 ${o.host}: ${o.error}`);else {let r=o.status==="nochange"?" \u2014 already set up":"";console.log(` \u2022 ${o.host} (${o.events.join(", ")})${r}`);}}function Fe(){return w({optOut:true}),console.log("OpenCrater Blips are now OFF for this machine."),console.log("Re-enable any time with: npx opencrater on"),0}function De(e){let{flags:t}=ae(e),n=t.get("key"),o=t.get("package");return w({optOut:false}),n&&o?(ce(n,o),N(O(n,o),o),process.stdout.write("Pinning fast runtime (one-time, ~15s)\u2026 "),console.log(T()?"\u2713":"skipped (npm unavailable \u2014 hooks use npx fallback)")):m().devToken?(N(O()),process.stdout.write("Pinning fast runtime (one-time, ~15s)\u2026 "),console.log(T()?"\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 Le(){let e=m(),t=e.lastShownAt>0?new Date(e.lastShownAt).toISOString():"never";console.log(`opencrater v${A}`),console.log(` state file: ${C()}`),console.log(` install id: ${e.installId}`),console.log(` opted out: ${e.optOut?"yes":"no"}`),console.log(` last shown: ${t}`),console.log(` pooled Blips: ${e.pool.length}`),console.log(` hosts found: ${M().join(", ")||"(none)"}`),console.log(` integrations: ${e.integrations.map(o=>o.package).join(", ")||"(none)"}`);let n=F();return console.log(` wired hooks: ${n.length}`),0}function Je(e){let{flags:t}=ae(e),n=t.get("key"),o=t.get("package");if(!n||!o)return console.error("Usage: opencrater hooks install --key <publisherKey> --package <name> [--host <host>]"),1;ce(n,o);let r=t.get("host");if(r&&r!=="true"){if(!k.includes(r))return console.error(`Unknown host "${r}". Supported: ${k.join(", ")}`),1;let s=r;try{let i=B(s,n,o);N([{host:s,status:i,events:$(s)}],o);}catch(i){return console.error(`Could not wire ${s}: ${i.message}`),1}}else N(O(n,o),o);return console.log("Remove with: npx opencrater hooks uninstall"),0}function ze(){let e=ne();return w({integrations:[]}),console.log(e>0?`Removed ${e} OpenCrater hook${e===1?"":"s"} across all hosts.`:"No OpenCrater hooks installed."),0}function Ge(){let e=F();if(e.length===0)return console.log("No OpenCrater hooks installed."),0;for(let t of e)console.log(`${t.host} ${t.event}: ${t.command}`);return 0}function re(){return console.log(`opencrater v${A} \u2014 OpenCrater Blips
2
+ 'use strict';var crypto=require('crypto'),d=require('fs'),G=require('os'),l=require('path'),child_process=require('child_process'),ae=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 G__namespace=/*#__PURE__*/_interopNamespace(G);var l__namespace=/*#__PURE__*/_interopNamespace(l);var ae__namespace=/*#__PURE__*/_interopNamespace(ae);var H=(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')});function de(e=process.env){return l__namespace.join(G__namespace.homedir(),".config","opencrater")}function O(e=process.env){return l__namespace.join(de(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 y(e){return typeof e=="number"&&Number.isFinite(e)}var K=new Set(["EPERM","EACCES","EBUSY","EEXIST"]);function V(e){for(let t=0;;t++)try{return {text:d__namespace.readFileSync(e,"utf8")}}catch(n){let o=n.code??"";if(!(o==="ENOENT"||K.has(o)))return {locked:true};if(t>=4)return o==="ENOENT"?{missing:true}:{locked:true};try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(t+1));}catch{}}}function fe(e){if(typeof e!="object"||e===null)return null;let t=e;return !y(t.minIntervalSeconds)||!y(t.serveTimeoutMs)||!y(t.preloadPoolSize)||typeof t.killSwitch!="boolean"?null:{minIntervalSeconds:t.minIntervalSeconds,serveTimeoutMs:t.serveTimeoutMs,preloadPoolSize:t.preloadPoolSize,killSwitch:t.killSwitch,displayDurationSeconds:y(t.displayDurationSeconds)?t.displayDurationSeconds:25,minSdkVersion:typeof t.minSdkVersion=="string"?t.minSdkVersion:""}}function ge(e){if(!Array.isArray(e))return [];let t=[];for(let n of e){if(typeof n!="object"||n===null)continue;let o=n,r=o.blip;if(!y(o.renderBy)||typeof r!="object"||r===null||typeof r.impressionId!="string"||typeof r.clickUrl!="string"||typeof r.sponsorLabel!="string"||typeof r.creative!="object"||r.creative===null)continue;let s=r.creative;typeof s.title!="string"||typeof s.body!="string"||t.push({blip:{impressionId:r.impressionId,...typeof r.campaignId=="string"?{campaignId:r.campaignId}:{},clickUrl:r.clickUrl,sponsorLabel:r.sponsorLabel,creative:{format:"text",title:s.title,body:s.body,...typeof s.cta=="string"?{cta:s.cta}:{}}},renderBy:o.renderBy});}return t}function me(e){if(typeof e!="object"||e===null||Array.isArray(e))return {};let t={};for(let[n,o]of Object.entries(e)){if(!Array.isArray(o))continue;let r=o.filter(s=>typeof s=="string"&&s.length<=64);t[n]=r.slice(0,64);}return t}function he(e){if(!Array.isArray(e))return [];let t=[];for(let n of e){if(typeof n!="object"||n===null)continue;let o=n;if(!(typeof o.topic!="string"||!y(o.at))&&(t.push({topic:o.topic.slice(0,32),at:o.at}),t.length>=24))break}return t}function ye(e){if(!Array.isArray(e))return [];let t=[],n=new Set;for(let o of e){if(typeof o!="object"||o===null)continue;let r=o;if(typeof r.key!="string"||typeof r.package!="string"||r.key===""||r.package==="")continue;let s=`${r.package}\0${r.key}`;if(!n.has(s)&&(n.add(s),t.push({key:r.key,package:r.package}),t.length>=32))break}return t}function ke(e){if(typeof e!="object"||e===null)return null;let t=e,n={};if(typeof t.savedEnv=="object"&&t.savedEnv!==null)for(let[o,r]of Object.entries(t.savedEnv))(typeof r=="string"||r===null)&&(n[o]=r);return {active:t.active===true,savedEnv:n}}function Se(e){if(typeof e!="object"||e===null)return null;let t=e,n=o=>y(o)&&o>=0?o:0;return {turns:n(t.turns),lastLimitAt:n(t.lastLimitAt),lastDepletedAt:n(t.lastDepletedAt),lastBackupAt:n(t.lastBackupAt)}}function we(e){let t=I();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:y(n.lastShownAt)&&n.lastShownAt>=0?n.lastShownAt:0,optOut:n.optOut===true,disclosureShown:n.disclosureShown===true,cachedConfig:fe(n.cachedConfig),allowedPlacements:me(n.allowedPlacements),sessionTopics:he(n.sessionTopics),integrations:ye(n.integrations),devToken:typeof n.devToken=="string"?n.devToken:null,computeRouting:ke(n.computeRouting),computeCards:Se(n.computeCards),configFetchedAt:y(n.configFetchedAt)&&n.configFetchedAt>=0?n.configFetchedAt:0,pool:ge(n.pool)}}function g(e=process.env){let t=O(e),n=V(t);if(n.text!==void 0)try{return we(JSON.parse(n.text))}catch{let o=I();try{C(o,e);}catch{}return o}if(n.missing){let o=I();try{C(o,e);}catch{}return o}return I()}function C(e,t=process.env,n={}){let o=O(t),r=l__namespace.dirname(o);d__namespace.mkdirSync(r,{recursive:true});let s=V(o),i=null;if(s.text!==void 0)try{i=JSON.parse(s.text);}catch{i=null;}if(i)typeof i.lastShownAt=="number"&&i.lastShownAt>e.lastShownAt&&(e={...e,lastShownAt:i.lastShownAt}),!n.allowClearToken&&typeof i.devToken=="string"&&e.devToken==null&&(e={...e,devToken:i.devToken}),typeof i.installId=="string"&&i.installId.length>0&&i.installId!==e.installId&&(e={...e,installId:i.installId});else if(!n.allowClearToken&&e.devToken==null&&s.text===void 0&&!s.missing)return;let u=l__namespace.join(r,`.state.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`);d__namespace.writeFileSync(u,JSON.stringify(e,null,2)+`
3
+ `,"utf8");for(let a=0;;a++)try{d__namespace.renameSync(u,o);return}catch(p){let c=p.code??"";if(a>=4||!K.has(c)){try{d__namespace.rmSync(u,{force:!0});}catch{}if(a>=4)return;throw p}try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(a+1));}catch{}}}function w(e,t=process.env){let n={...g(t),...e};return C(n,t),n}var q={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"],generic:["SessionStart","Stop"]};var k=["claude_code","codex","gemini_cli","copilot_cli"];function b(e){return e.includes("opencrater-hook")}function be(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ve(e,t){return b(e)&&new RegExp(`--package ['"]?${be(t)}['"]?`).test(e)}function ne(e,t){return t?ve(e,t):b(e)&&!/--package\b/.test(e)}function W(e){return /^[A-Za-z0-9@_./:-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}var Y='"$HOME/.config/opencrater/runtime/node_modules/opencrater/dist/hook.js"',X="$env:USERPROFILE\\.config\\opencrater\\runtime\\node_modules\\opencrater\\dist\\hook.js";function M(e,t,n,o){let r=`--placement ${t}`;return n&&(r+=` --key ${W(n)}`),o&&(r+=` --package ${W(o)}`),r+=` --host ${e}`,`{ if [ -f ${Y} ]; then node ${Y} ${r}; else npx -y -p opencrater opencrater-hook ${r}; fi; } 2>/dev/null || true`}function Ce(e,t,n,o){let r=`--placement ${t}`;return n&&(r+=` --key '${n}'`),o&&(r+=` --package '${o}'`),r+=` --host ${e}`,`try { if (Test-Path "${X}") { node "${X}" ${r} } else { npx -y -p opencrater opencrater-hook ${r} } } catch {}`}function Q(e,t,n,o){return M(e,t,n,o)}function te(e,t){let n=G__namespace.homedir();switch(e){case "claude_code":{let o=t.CLAUDE_CONFIG_DIR;return o&&o.trim()!==""?o:l__namespace.join(n,".claude")}case "codex":{let o=t.CODEX_HOME;return o&&o.trim()!==""?o:l__namespace.join(n,".codex")}case "gemini_cli":return l__namespace.join(n,".gemini");case "copilot_cli":{let o=t.COPILOT_HOME;return o&&o.trim()!==""?o:l__namespace.join(n,".copilot")}default:return l__namespace.join(n,".opencrater-unknown")}}function E(e,t=process.env){let n=te(e,t);switch(e){case "claude_code":return l__namespace.join(n,"settings.json");case "codex":return l__namespace.join(n,"hooks.json");case "gemini_cli":return l__namespace.join(n,"settings.json");case "copilot_cli":return l__namespace.join(n,"hooks","hooks.json");default:return l__namespace.join(n,"hooks.json")}}var Oe={claude_code:["claude"],codex:["codex"],gemini_cli:["gemini"],copilot_cli:["copilot"]};function Ae(e,t){if(e.length===0)return false;let n=(t.PATH??t.Path??"").split(l__namespace.delimiter).filter(Boolean),o=process.platform==="win32"?["",".exe",".cmd",".bat"]:[""];for(let r of n)for(let s of e)for(let i of o)try{if(d__namespace.existsSync(l__namespace.join(r,s+i)))return !0}catch{}return false}function Pe(e,t=process.env){try{if(d__namespace.existsSync(te(e,t)))return !0}catch{}return Ae(Oe[e]??[],t)}function U(e=process.env){return k.filter(t=>Pe(t,e))}function x(e){let t;try{t=d__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 B(e,t){let n=l__namespace.dirname(e);d__namespace.mkdirSync(n,{recursive:true});let o=l__namespace.join(n,`.${l__namespace.basename(e)}.${process.pid}.tmp`);d__namespace.writeFileSync(o,JSON.stringify(t,null,2)+`
4
+ `,"utf8"),d__namespace.renameSync(o,e);}function Re(e,t){return Array.isArray(e.hooks)&&e.hooks.some(n=>typeof n.command=="string"&&ne(n.command,t))}function Ie(e,t,n,o){let r=E(e),s=x(r),i=s.hooks&&typeof s.hooks=="object"?s.hooks:{};if(o.every(a=>{let p=Q(e,a,t,n);return (Array.isArray(i[a])?i[a]:[]).some(c=>Array.isArray(c.hooks)&&c.hooks.some(m=>m.command===p))}))return "nochange";for(let a of o){let c=(Array.isArray(i[a])?i[a]:[]).filter(m=>!Re(m,n));c.push({matcher:"",hooks:[{type:"command",command:Q(e,a,t,n)}]}),i[a]=c;}return s.hooks=i,B(r,s),"wrote"}var Z=12;function Ee(e,t){return [e.bash,e.powershell,e.command].some(n=>typeof n=="string"&&ne(n,t))}function xe(e,t,n,o){let r=E(e),s=x(r);typeof s.version!="number"&&(s.version=1);let i=s.hooks&&typeof s.hooks=="object"?s.hooks:{};if(o.every(a=>{let p=M(e,a,t,n);return (Array.isArray(i[a])?i[a]:[]).some(c=>c.bash===p&&c.timeoutSec===Z)}))return "nochange";for(let a of o){let c=(Array.isArray(i[a])?i[a]:[]).filter(m=>!Ee(m,n));c.push({type:"command",bash:M(e,a,t,n),powershell:Ce(e,a,t,n),timeoutSec:Z}),i[a]=c;}return s.hooks=i,B(r,s),"wrote"}function T(e){return [...q[e]]}function F(e,t,n){let o=T(e);return o.length===0?"nochange":e==="copilot_cli"?xe(e,t,n,o):Ie(e,t,n,o)}function A(e,t,n=process.env){return U(n).map(o=>{try{let r=F(o,e,t);return {host:o,status:r,events:T(o)}}catch(r){return {host:o,status:"error",events:[],error:r.message}}})}function D(e=process.env){let t=[];for(let n of k){let o;try{o=x(E(n,e));}catch{continue}let r=o.hooks;if(!(!r||typeof r!="object"))for(let[s,i]of Object.entries(r))for(let u of Array.isArray(i)?i:[]){let a=u,p=Array.isArray(a.hooks)?a.hooks.find(f=>typeof f.command=="string"&&b(f.command))?.command:void 0,c=[a.bash,a.command,a.powershell].find(f=>typeof f=="string"&&b(f)),m=p??c;m&&t.push({host:n,event:s,command:m});}}return t}function oe(e=process.env){let t=0;for(let n of k){let o=E(n,e),r;try{r=x(o);}catch{continue}let s=r.hooks;if(!s||typeof s!="object")continue;let i=s,u=false;for(let a of Object.keys(i)){let p=Array.isArray(i[a])?i[a]:[],c=p.filter(m=>{let f=m,z=Array.isArray(f.hooks)&&f.hooks.some(v=>typeof v.command=="string"&&b(v.command))||[f.bash,f.powershell,f.command].some(v=>typeof v=="string"&&b(v));return z&&t++,!z});c.length!==p.length&&(u=true,c.length>0?i[a]=c:delete i[a]);}if(u)try{let a=Object.keys(r).filter(c=>c!=="version"&&c!=="hooks"),p=n==="copilot_cli"||n==="codex";Object.keys(i).length===0&&a.length===0&&p?d__namespace.rmSync(o,{force:!0}):B(o,r);}catch{}}return t}var P="1.1.24";var Te="https://api.opencrater.to";function $(e,t=process.env){let n=t.OPENCRATER_API_ORIGIN;return (e??(n&&n.trim()!==""?n:Te)).replace(/\/+$/,"")}function Ne(){return l__namespace.join(G__namespace.homedir(),".config","opencrater","runtime")}function je(e){return ["install","--prefix",e,"opencrater@latest","--silent","--no-audit","--no-fund"]}function N(e=Ne()){if(process.env.VITEST||process.env.OPENCRATER_DISABLE_RUNTIME_PIN)return false;try{return child_process.spawnSync("npm",je(e),{stdio:"ignore",windowsHide:!0,shell:process.platform==="win32"}).status===0}catch{return false}}function _e(){let e=process.env.OPENCRATER_WEB_ORIGIN;return e&&e.trim()!==""?e.replace(/\/$/,""):$().replace("//api.","//").replace(/\/$/,"")}function He(e){try{let t=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";child_process.spawn(t,[e],{stdio:"ignore",detached:!0,shell:process.platform==="win32"}).unref();}catch{}}function Me(e){let t=ae__namespace.createInterface({input:process.stdin,output:process.stdout});return new Promise(n=>t.question(e,o=>(t.close(),n(o))))}function L(e){return `$${(e/1e6).toFixed(2)}`}async function J(e,t){try{let n=new URL(`${$()}/v1/dev/me`);t&&n.searchParams.set("installId",t);let o=await fetch(n,{headers:{authorization:`Bearer ${e}`}});return o.ok?await o.json():null}catch{return null}}async function Ue(){let e=`${_e()}/dev/link`;console.log("Sign in and generate a CLI token here (we tried to open it):"),console.log(` ${e}
5
+ `),He(e);let t=(await Me("Paste your token (ocd_\u2026): ")).trim();if(!t.startsWith("ocd_"))return console.error("That doesn't look like a token (should start with ocd_)."),1;let n=await J(t,g().installId);if(!n)return console.error("Couldn't verify that token \u2014 check it and try again."),1;w({devToken:t}),console.log(`
6
+ \u2713 Signed in as ${n.displayName}.`),console.log(` Compute balance: ${L(n.balanceMicroUsd)} \xB7 tier: ${n.trustTier}`);let o=A().filter(r=>r.status!=="error").map(r=>r.host);return o.length?(console.log(` Wired into: ${o.join(", ")}`),process.stdout.write(" Pinning fast runtime (one-time, ~15s)\u2026 "),console.log(N()?"\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 Be(){let e=g().devToken;if(!e)return console.error("Not signed in. Run: opencrater login"),1;let t=await J(e,g().installId);return t?(console.log(`Compute balance: ${L(t.balanceMicroUsd)}`),console.log(` signed in as: ${t.displayName} \xB7 tier: ${t.trustTier}`),0):(console.error("Couldn't reach OpenCrater (or your session expired \u2014 try: opencrater login)."),1)}function Fe(){return C({...g(),devToken:null},process.env,{allowClearToken:true}),console.log("Signed out of the OpenCrater compute wallet on this machine."),0}async function De(e){let t=g().devToken;if(!t)return console.error("Not signed in. Run: opencrater login"),1;let n=await J(t,g().installId);if(n&&n.balanceMicroUsd<=0)return console.error("Your OpenCrater compute balance is empty \u2014 see Blips to earn more."),console.error("Check anytime with: opencrater balance"),1;let o=`${$().replace(/\/$/,"")}/gateway`,r=l__namespace.join(l__namespace.dirname(O()),"claude-gateway.settings.json");try{d__namespace.mkdirSync(l__namespace.dirname(r),{recursive:!0}),d__namespace.writeFileSync(r,JSON.stringify({apiKeyHelper:`echo ${t}`}),{mode:384});}catch(u){return console.error(`Couldn't write gateway settings: ${u.message}`),1}n&&console.log(`Launching Claude Code on OpenCrater compute \xB7 balance ${L(n.balanceMicroUsd)}`);let s={...process.env,ANTHROPIC_BASE_URL:o};delete s.ANTHROPIC_API_KEY;let i=child_process.spawn("claude",[...e,"--settings",r],{stdio:"inherit",env:s,shell:process.platform==="win32"});return await new Promise(u=>{i.on("exit",a=>u(a??0)),i.on("error",a=>{console.error(`Couldn't launch claude: ${a.message}`),console.error("Is Claude Code installed? https://claude.com/claude-code"),u(127);});})}function le(e){let t=new Map,n=[];for(let o=0;o<e.length;o++){let r=e[o];if(r!==void 0)if(r.startsWith("--")){let s=r.indexOf("=");if(s!==-1)t.set(r.slice(2,s),r.slice(s+1));else {let i=e[o+1];i!==void 0&&!i.startsWith("--")?(t.set(r.slice(2),i),o++):t.set(r.slice(2),"true");}}else n.push(r);}return {flags:t,rest:n}}function ue(e,t){let n=g();n.integrations.some(o=>o.key===e&&o.package===t)||w({integrations:[...n.integrations,{key:e,package:t}].slice(-32)});}function j(e,t){let n=t||"compute hooks";if(e.length===0){console.log(`No supported AI CLIs detected yet \u2014 OpenCrater will wire ${n} automatically the moment you install one (it re-checks on the next session).`);return}console.log(`OpenCrater wired ${n} into:`);for(let o of e)if(o.status==="error")console.log(` \u2717 ${o.host}: ${o.error}`);else {let r=o.status==="nochange"?" \u2014 already set up":"";console.log(` \u2022 ${o.host} (${o.events.join(", ")})${r}`);}}function Le(){return w({optOut:true}),console.log("OpenCrater Blips are now OFF for this machine."),console.log("Re-enable any time with: npx opencrater on"),0}function Je(e){let{flags:t}=le(e),n=t.get("key"),o=t.get("package");return w({optOut:false}),n&&o?(ue(n,o),j(A(n,o),o),process.stdout.write("Pinning fast runtime (one-time, ~15s)\u2026 "),console.log(N()?"\u2713":"skipped (npm unavailable \u2014 hooks use npx fallback)")):g().devToken?(j(A()),process.stdout.write("Pinning fast runtime (one-time, ~15s)\u2026 "),console.log(N()?"\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 ze(){let e=g(),t=e.lastShownAt>0?new Date(e.lastShownAt).toISOString():"never";console.log(`opencrater v${P}`),console.log(` state file: ${O()}`),console.log(` install id: ${e.installId}`),console.log(` opted out: ${e.optOut?"yes":"no"}`),console.log(` last shown: ${t}`),console.log(` pooled Blips: ${e.pool.length}`),console.log(` hosts found: ${U().join(", ")||"(none)"}`),console.log(` integrations: ${e.integrations.map(o=>o.package).join(", ")||"(none)"}`);let n=D();return console.log(` wired hooks: ${n.length}`),0}function Ge(e){let{flags:t}=le(e),n=t.get("key"),o=t.get("package");if(!n||!o)return console.error("Usage: opencrater hooks install --key <publisherKey> --package <name> [--host <host>]"),1;ue(n,o);let r=t.get("host");if(r&&r!=="true"){if(!k.includes(r))return console.error(`Unknown host "${r}". Supported: ${k.join(", ")}`),1;let s=r;try{let i=F(s,n,o);j([{host:s,status:i,events:T(s)}],o);}catch(i){return console.error(`Could not wire ${s}: ${i.message}`),1}}else j(A(n,o),o);return console.log("Remove with: npx opencrater hooks uninstall"),0}function Ke(){let e=oe();return w({integrations:[]}),console.log(e>0?`Removed ${e} OpenCrater hook${e===1?"":"s"} across all hosts.`:"No OpenCrater hooks installed."),0}function Ve(){let e=D();if(e.length===0)return console.log("No OpenCrater hooks installed."),0;for(let t of e)console.log(`${t.host} ${t.event}: ${t.command}`);return 0}function ie(){return console.log(`opencrater v${P} \u2014 OpenCrater Blips
7
7
 
8
8
  Usage:
9
9
  opencrater on [--key <ock_\u2026> --package <name>]
@@ -24,4 +24,4 @@ Usage:
24
24
  opencrater hooks list List installed OpenCrater hooks
25
25
 
26
26
  Hosts: ${k.join(", ")}
27
- Environment: OPENCRATER_DISABLE=1 disables everything; NO_COLOR respected.`),0}function Ke(e){let[t,...n]=e;switch(t){case "off":return Fe();case "on":return De(n);case "login":return He();case "balance":return Me();case "logout":return Ue();case "code":return Be(n);case "status":return Le();case "hooks":{let[o,...r]=n;switch(o){case "install":return Je(r);case "uninstall":return ze();case "list":return Ge();default:return console.error("Usage: opencrater hooks <install|uninstall|list>"),1}}case "version":case "--version":case "-v":return console.log(A),0;case void 0:case "help":case "--help":case "-h":return re();default:return console.error(`Unknown command: ${t}`),re(),1}}typeof _<"u"&&typeof module<"u"&&_.main===module&&Promise.resolve().then(()=>Ke(process.argv.slice(2))).then(e=>{process.exitCode=e;}).catch(e=>{console.error(`opencrater: ${e.message}`),process.exitCode=1;});exports.runCli=Ke;
27
+ Environment: OPENCRATER_DISABLE=1 disables everything; NO_COLOR respected.`),0}function qe(e){let[t,...n]=e;switch(t){case "off":return Le();case "on":return Je(n);case "login":return Ue();case "balance":return Be();case "logout":return Fe();case "code":return De(n);case "status":return ze();case "hooks":{let[o,...r]=n;switch(o){case "install":return Ge(r);case "uninstall":return Ke();case "list":return Ve();default:return console.error("Usage: opencrater hooks <install|uninstall|list>"),1}}case "version":case "--version":case "-v":return console.log(P),0;case void 0:case "help":case "--help":case "-h":return ie();default:return console.error(`Unknown command: ${t}`),ie(),1}}typeof H<"u"&&typeof module<"u"&&H.main===module&&Promise.resolve().then(()=>qe(process.argv.slice(2))).then(e=>{process.exitCode=e;}).catch(e=>{console.error(`opencrater: ${e.message}`),process.exitCode=1;});exports.runCli=qe;
package/dist/hook.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- 'use strict';var child_process=require('child_process'),u=require('fs'),E=require('os'),g=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 u__namespace=/*#__PURE__*/_interopNamespace(u);var E__namespace=/*#__PURE__*/_interopNamespace(E);var g__namespace=/*#__PURE__*/_interopNamespace(g);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:""},le={claude_code:["SessionStart","Stop","SessionEnd","Notification"],codex:["Stop"],openclaw:[],gemini_cli:["AfterAgent","SessionStart","SessionEnd"],copilot_cli:["agentStop","sessionStart","sessionEnd","notification"],generic:["SessionStart","Stop"]},ue={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"],generic:["SessionStart","Stop"]};var R="1.1.22";var ot="https://api.opencrater.to";function W(e,t=process.env){let n=t.OPENCRATER_API_ORIGIN;return ((n&&n.trim()!==""?n:ot)).replace(/\/+$/,"")}function h(...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 B(e){return typeof e=="number"&&Number.isFinite(e)}function rt(e){let t=M;if(typeof e!="object"||e===null)return {...t};let n=e;return {minIntervalSeconds:B(n.minIntervalSeconds)?n.minIntervalSeconds:t.minIntervalSeconds,serveTimeoutMs:B(n.serveTimeoutMs)?n.serveTimeoutMs:t.serveTimeoutMs,preloadPoolSize:B(n.preloadPoolSize)?n.preloadPoolSize:t.preloadPoolSize,killSwitch:n.killSwitch===true,displayDurationSeconds:B(n.displayDurationSeconds)?n.displayDurationSeconds:t.displayDurationSeconds,minSdkVersion:typeof n.minSdkVersion=="string"?n.minSdkVersion:t.minSdkVersion}}async function j(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():(h(`POST ${t} -> HTTP ${i.status}`),null)}catch(i){return h(`POST ${t} failed:`,i),null}}function pe(e,t){let n=e.host??"generic";return {publisherKey:e.publisherKey,packageName:e.packageName,placement:e.placement,host:n,sdkVersion:R,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 de(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:rt(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),n}async function fe(e,t){let n=await j(t.origin,"/v1/serve",pe(e,t),t.timeoutMs);return de(n)}async function me(e,t,n){let r={...pe(t,n),publisherKey:t.publisherKey??"",packageName:t.packageName??""},o=await j(n.origin,"/v1/dev/serve",r,n.timeoutMs,{authorization:`Bearer ${e}`});return de(o)}function ge(e,t,n){return j(n.origin,"/v1/dev/impression",{impressionId:t},n.timeoutMs,{authorization:`Bearer ${e}`}).then(()=>{}).catch(()=>{})}function q(e,t){return j(t.origin,"/v1/events/impression",{impressionId:e},t.timeoutMs).then(()=>{}).catch(()=>{})}function he(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 ye(e){return {sponsorLabel:"",title:e.title,body:e.body,url:e.url}}function H(e){let t=he(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 $(e=process.env){return g__namespace.join(E__namespace.homedir(),".config","opencrater")}function L(e=process.env){return g__namespace.join($(e),"state.json")}function be(){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)}function st(e){if(typeof e!="object"||e===null)return null;let t=e;return !k(t.minIntervalSeconds)||!k(t.serveTimeoutMs)||!k(t.preloadPoolSize)||typeof t.killSwitch!="boolean"?null:{minIntervalSeconds:t.minIntervalSeconds,serveTimeoutMs:t.serveTimeoutMs,preloadPoolSize:t.preloadPoolSize,killSwitch:t.killSwitch,displayDurationSeconds:k(t.displayDurationSeconds)?t.displayDurationSeconds:25,minSdkVersion:typeof t.minSdkVersion=="string"?t.minSdkVersion:""}}function at(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(!k(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 ct(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 lt(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"||!k(r.at))&&(t.push({topic:r.topic.slice(0,32),at:r.at}),t.length>=24))break}return t}function ut(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 pt(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 dt(e){if(typeof e!="object"||e===null)return null;let t=e,n=r=>k(r)&&r>=0?r:0;return {turns:n(t.turns),lastLimitAt:n(t.lastLimitAt),lastDepletedAt:n(t.lastDepletedAt),lastBackupAt:n(t.lastBackupAt)}}function ft(e){let t=be();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:k(n.lastShownAt)&&n.lastShownAt>=0?n.lastShownAt:0,optOut:n.optOut===true,disclosureShown:n.disclosureShown===true,cachedConfig:st(n.cachedConfig),allowedPlacements:ct(n.allowedPlacements),sessionTopics:lt(n.sessionTopics),integrations:ut(n.integrations),devToken:typeof n.devToken=="string"?n.devToken:null,computeRouting:pt(n.computeRouting),computeCards:dt(n.computeCards),configFetchedAt:k(n.configFetchedAt)&&n.configFetchedAt>=0?n.configFetchedAt:0,pool:at(n.pool)}}function X(e=process.env){let t=L(e);try{let n=u__namespace.readFileSync(t,"utf8"),r=JSON.parse(n);return ft(r)}catch{let n=be();try{y(n,e);}catch{}return n}}function y(e,t=process.env,n={}){let r=L(t),o=g__namespace.dirname(r);u__namespace.mkdirSync(o,{recursive:true});try{let a=JSON.parse(u__namespace.readFileSync(r,"utf8"));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});}catch{}let i=g__namespace.join(o,`.state.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`);u__namespace.writeFileSync(i,JSON.stringify(e,null,2)+`
4
- `,"utf8");let s=new Set(["EPERM","EACCES","EBUSY","EEXIST"]);for(let a=0;;a++)try{u__namespace.renameSync(i,r);return}catch(c){let d=c.code??"";if(a>=4||!s.has(d)){try{u__namespace.rmSync(i,{force:!0});}catch{}if(a>=4)return;throw c}try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(a+1));}catch{}}}var mt=300*1e3;function gt(){return g__namespace.join($(),"blocked-ads.json")}function Z(){return g__namespace.join($(),"recent-renders.json")}function ht(){return g__namespace.join($(),"reported-ads.json")}function ke(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 yt(e){try{let t=JSON.parse(u__namespace.readFileSync(gt(),"utf8"));return ke(t&&typeof t=="object"?t:{},e)}catch{return {}}}function St(){try{let e=JSON.parse(u__namespace.readFileSync(ht(),"utf8"));return e&&typeof e=="object"?e:{}}catch{return {}}}function bt(e){return e?St()[e]!==void 0:false}function U(e,t=Date.now()){return e?yt(t)[e]!==void 0||bt(e):false}function we(e){try{let t=JSON.parse(u__namespace.readFileSync(Z(),"utf8"));return ke(t&&typeof t=="object"?t:{},e)}catch{return {}}}function F(e,t=Date.now()){if(e)try{let n=we(t);n[e]=t+mt,u__namespace.mkdirSync(g__namespace.dirname(Z()),{recursive:!0}),u__namespace.writeFileSync(Z(),JSON.stringify(n));}catch{}}function G(e,t=Date.now()){return e?we(t)[e]!==void 0:false}function kt(e,t){return e.filter(n=>n.renderBy>t)}function Q(e,t){let n=kt(e.pool,t),r=n.shift();return {blip:r?r.blip:null,pool:n}}var wt=["claude_code","codex","gemini_cli","copilot_cli"];function _e(e){return e.includes("opencrater-hook")}function vt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ct(e,t){return _e(e)&&new RegExp(`--package ['"]?${vt(t)}['"]?`).test(e)}function Ie(e,t){return t?Ct(e,t):_e(e)&&!/--package\b/.test(e)}function ve(e){return /^[A-Za-z0-9@_./:-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}var Ce='"$HOME/.config/opencrater/runtime/node_modules/opencrater/dist/hook.js"',Ee="$env:USERPROFILE\\.config\\opencrater\\runtime\\node_modules\\opencrater\\dist\\hook.js";function ee(e,t,n,r){let o=`--placement ${t}`;return n&&(o+=` --key ${ve(n)}`),r&&(o+=` --package ${ve(r)}`),o+=` --host ${e}`,`{ if [ -f ${Ce} ]; then node ${Ce} ${o}; else npx -y -p opencrater opencrater-hook ${o}; fi; } 2>/dev/null || true`}function Et(e,t,n,r){let o=`--placement ${t}`;return n&&(o+=` --key '${n}'`),r&&(o+=` --package '${r}'`),o+=` --host ${e}`,`try { if (Test-Path "${Ee}") { node "${Ee}" ${o} } else { npx -y -p opencrater opencrater-hook ${o} } } catch {}`}function Re(e,t,n,r){return ee(e,t,n,r)}function Ae(e,t){let n=E__namespace.homedir();switch(e){case "claude_code":{let r=t.CLAUDE_CONFIG_DIR;return r&&r.trim()!==""?r:g__namespace.join(n,".claude")}case "codex":{let r=t.CODEX_HOME;return r&&r.trim()!==""?r:g__namespace.join(n,".codex")}case "gemini_cli":return g__namespace.join(n,".gemini");case "copilot_cli":{let r=t.COPILOT_HOME;return r&&r.trim()!==""?r:g__namespace.join(n,".copilot")}default:return g__namespace.join(n,".opencrater-unknown")}}function J(e,t=process.env){let n=Ae(e,t);switch(e){case "claude_code":return g__namespace.join(n,"settings.json");case "codex":return g__namespace.join(n,"hooks.json");case "gemini_cli":return g__namespace.join(n,"settings.json");case "copilot_cli":return g__namespace.join(n,"hooks","hooks.json");default:return g__namespace.join(n,"hooks.json")}}var Rt={claude_code:["claude"],codex:["codex"],gemini_cli:["gemini"],copilot_cli:["copilot"]};function Tt(e,t){if(e.length===0)return false;let n=(t.PATH??t.Path??"").split(g__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(u__namespace.existsSync(g__namespace.join(o,i+s)))return !0}catch{}return false}function Ot(e,t=process.env){try{if(u__namespace.existsSync(Ae(e,t)))return !0}catch{}return Tt(Rt[e]??[],t)}function te(e=process.env){return wt.filter(t=>Ot(t,e))}function Pe(e){let t;try{t=u__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 xe(e,t){let n=g__namespace.dirname(e);u__namespace.mkdirSync(n,{recursive:true});let r=g__namespace.join(n,`.${g__namespace.basename(e)}.${process.pid}.tmp`);u__namespace.writeFileSync(r,JSON.stringify(t,null,2)+`
5
- `,"utf8"),u__namespace.renameSync(r,e);}function _t(e,t){return Array.isArray(e.hooks)&&e.hooks.some(n=>typeof n.command=="string"&&Ie(n.command,t))}function It(e,t,n,r){let o=J(e),i=Pe(o),s=i.hooks&&typeof i.hooks=="object"?i.hooks:{};if(r.every(c=>{let d=Re(e,c,t,n);return (Array.isArray(s[c])?s[c]:[]).some(f=>Array.isArray(f.hooks)&&f.hooks.some(l=>l.command===d))}))return "nochange";for(let c of r){let f=(Array.isArray(s[c])?s[c]:[]).filter(l=>!_t(l,n));f.push({matcher:"",hooks:[{type:"command",command:Re(e,c,t,n)}]}),s[c]=f;}return i.hooks=s,xe(o,i),"wrote"}var Te=12;function At(e,t){return [e.bash,e.powershell,e.command].some(n=>typeof n=="string"&&Ie(n,t))}function Pt(e,t,n,r){let o=J(e),i=Pe(o);typeof i.version!="number"&&(i.version=1);let s=i.hooks&&typeof i.hooks=="object"?i.hooks:{};if(r.every(c=>{let d=ee(e,c,t,n);return (Array.isArray(s[c])?s[c]:[]).some(f=>f.bash===d&&f.timeoutSec===Te)}))return "nochange";for(let c of r){let f=(Array.isArray(s[c])?s[c]:[]).filter(l=>!At(l,n));f.push({type:"command",bash:ee(e,c,t,n),powershell:Et(e,c,t,n),timeoutSec:Te}),s[c]=f;}return i.hooks=s,xe(o,i),"wrote"}function Ne(e){return [...ue[e]]}function xt(e,t,n){let r=Ne(e);return r.length===0?"nochange":e==="copilot_cli"?Pt(e,t,n,r):It(e,t,n,r)}function ne(e,t,n=process.env){return te(n).map(r=>{try{let o=xt(r,e,t);return {host:r,status:o,events:Ne(r)}}catch(o){return {host:r,status:"error",events:[],error:o.message}}})}function Mt(){return g__namespace.join(E__namespace.homedir(),".config","opencrater","runtime")}function $t(e){return ["install","--prefix",e,"opencrater@latest","--silent","--no-audit","--no-fund"]}function oe(e=Mt()){child_process.spawn("npm",$t(e),process.platform==="win32"?{detached:false,stdio:"ignore",windowsHide:true,shell:true}:{detached:true,stdio:"ignore"}).unref();}var Be={atLimit:false,resetAt:null};function je(e,t=E__namespace.homedir()){try{if(e==="claude_code")return Dt(t);if(e==="codex")return Bt(t)}catch{}return Be}function Dt(e){let t=u__namespace.readFileSync(g__namespace.join(e,".claude.json"),"utf8"),n=JSON.parse(t),r=n.hasAvailableSubscription===false||n.cachedExtraUsageDisabledReason==="out_of_credits",o=null,a=n.cachedGrowthBookFeatures?.tengu_saffron_lattice?.planLimitsEndDate;if(typeof a=="string"){let c=Date.parse(a);Number.isFinite(c)&&(o=c);}return {atLimit:r,resetAt:o}}function Bt(e){return u__namespace.accessSync(g__namespace.join(e,".codex","auth.json")),Be}function He(e,t){switch(e){case "gemini_cli":return t==="AfterAgent";case "copilot_cli":return t==="agentStop";default:return t==="Stop"}}var Le=36e5,jt=30*6e4,Ht=30*6e4,Lt=4*Le,Ut=3,K="https://opencrater.to/dashboard";function Y(e){return `$${(e/1e6).toFixed(2)}`}function Ft(e,t){return t<=0?0:Math.max(0,Math.min(100,Math.round(e/t*100)))}function Gt(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/Le))}h`,o=new Date(e).toISOString().slice(0,10);return ` Your host limit resets in ${r} (${o}).`}function Ue(e){let{balanceMicroUsd:t,weeklyGrantMicroUsd:n,onGateway:r,turnEnd:o,host:i,cc:s,now:a}=e;if(t===null)return null;if(t<=0)return a-(s.lastDepletedAt??0)<Ht?null:{kind:"depleted",card:{sponsorLabel:"OpenCrater",title:"Compute used up",body:"Keep coding in Codex / Copilot to earn more compute, then switch back to Claude Code."+Gt(i.resetAt,a),url:K,cta:"Earn more"}};if(r){if(!o||(s.turns??0)%Ut!==0)return null;let c=n&&n>0?Ft(t,n):null;return {kind:"hud",card:{sponsorLabel:"OpenCrater",title:"Running on OpenCrater compute",body:c!==null?`${c}% of your weekly compute left \u2014 ${Y(t)} remaining.`:`${Y(t)} of compute remaining this week.`,url:K,cta:"Wallet"}}}return i.atLimit?a-(s.lastLimitAt??0)<jt?null:{kind:"limit",card:{sponsorLabel:"OpenCrater",title:"Hit your limit? You've got compute",body:`${Y(t)} of OpenCrater compute is ready. Continue this session now: opencrater code -c`,url:K,cta:"opencrater code -c"}}:a-(s.lastBackupAt??0)>=Lt?{kind:"backup",card:{sponsorLabel:"OpenCrater",title:"Backup compute ready",body:`${Y(t)} of OpenCrater compute waiting. When you hit your limit: opencrater code -c`,url:K,cta:"opencrater code -c"}}: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 ie(e){return e!==void 0&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}function Vt(e){return ie(e.OPENCRATER_DISABLE)||ie(e.TSN_DISABLE)}function Wt(e){return zt.some(t=>ie(e[t]))}function V(e){return e?{...M,...e}:M}function Ve(e,t={}){if(Vt(e.env))return "env_disabled";if(e.state.optOut)return "opt_out";let n=V(e.state.cachedConfig);if(n.killSwitch)return "kill_switch";if(Wt(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 qt=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 Xt(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 Zt(e,t=12){let n=[];for(let r of e.slice(0,2e3).split(/\s+/))if(!(!r||Xt(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)||qt.has(i))&&!n.includes(i)&&(n.push(i),n.length>=t))return n}return n}function se(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 Zt(t.join(" "))}function ae(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 We(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 tn=false,nn=process.platform==="win32"?8e3:3200,on=150,qe=250,rn=2800,tt="claude_code";function sn(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==="generic")&&(t.host=o,n++);break;}}return t}function an(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 cn="\\\\.\\CONOUT$";function ln(e){return !e||e==="?"||e==="??"||e==="-"?null:e.startsWith("/")?e:`/dev/${e}`}function un(e){let t=e.match(/^\s*(\d+)\s+(\S+)/);return t?{ppid:Number(t[1]),tty:t[2]}:null}function pn(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 dn(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 fn(e){try{let t=dn(u__namespace.readFileSync(`/proc/${e}/stat`,"utf8"));if(t)return {ppid:t.ppid,ttyPath:pn(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=un(t);return n?{ppid:n.ppid,ttyPath:ln(n.tty)}:null}catch{return null}}function mn(){if(process.platform==="win32")return {path:cn,ownerPid:null};let e=process.pid;for(let t=0;t<12&&e>1;t++){let n=fn(e);if(!n)return null;if(n.ttyPath)return {path:n.ttyPath,ownerPid:e};e=n.ppid;}return null}function gn(e){return e==="win32"?{detached:false,stdio:"ignore",windowsHide:false}:{detached:true,stdio:"ignore",windowsHide:false}}async function D(e,t,n,r,o){try{let i=g__namespace.join(__dirname,"paint.js"),s=V(t.cachedConfig),a=Math.min(Math.max(s.displayDurationSeconds??25,3),120),c={...e,format:n?.format,mediaUrl:n?.mediaUrl,mediaPixelUrl:n?.mediaPixelUrl,audioUrl:n?.audioUrl,impressionId:r,campaignId:o,apiOrigin:W(),durationMs:a*1e3,disclosure:!t.disclosureShown,host:tt},d={...process.env,OPENCRATER_PAINT:JSON.stringify(c)};if(!d.OPENCRATER_TTY){let l=mn();l&&(d.OPENCRATER_TTY=l.path,l.ownerPid!==null&&(d.OPENCRATER_HOST_PID=String(l.ownerPid)));}let f=child_process.spawn(process.execPath,[i],{...gn(process.platform),env:d});process.platform==="win32"?await new Promise(l=>{let p=!1,O=()=>{p||(p=!0,l());};f.on("exit",O),f.on("error",O),setTimeout(O,7500);}):f.unref();}catch{}return {...t,lastShownAt:Date.now(),disclosureShown:true}}function Xe(e){if(process.platform!=="win32")return false;try{let t=g__namespace.join(E__namespace.homedir(),".config","opencrater","painter.lock"),n=JSON.parse(u__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 hn=8e3;function Ze(){let e=g__namespace.join(E__namespace.homedir(),".config","opencrater","render.lock");try{let t=u__namespace.statSync(e);if(Date.now()-t.mtimeMs<hn)return !1;u__namespace.unlinkSync(e);}catch{}try{return u__namespace.mkdirSync(g__namespace.join(E__namespace.homedir(),".config","opencrater"),{recursive:!0}),u__namespace.writeFileSync(e,String(process.pid),{flag:"wx"}),!0}catch{return false}}function yn(e,t,n,r){if(!t)return true;let o=e.allowedPlacements[`${t}:${n}`];return o?o.includes(r):t==="opencrater"?le[n].includes(r):true}var Sn=1440*60*1e3;function bn(){try{let e=g__namespace.join(E__namespace.homedir(),".config","opencrater","runtime"),t=g__namespace.join(e,"node_modules","opencrater","dist","hook.js"),n=g__namespace.join(e,".last-update");if(u__namespace.existsSync(t)){try{if(Date.now()-u__namespace.statSync(n).mtimeMs<Sn)return}catch{}try{u__namespace.writeFileSync(n,String(Date.now()));}catch{return}}else {let r=g__namespace.join(e,".installing");try{u__namespace.mkdirSync(e,{recursive:!0});let o=u__namespace.statSync(r);if(Date.now()-o.mtimeMs<600*1e3)return}catch{}u__namespace.writeFileSync(r,String(Date.now()));}oe(e);}catch{}}function Qe(e,t){if(!t)return false;let n=s=>s.split(/[-+]/)[0].split(".").map(a=>parseInt(a,10)||0),r=n(e),o=n(t),i=Math.max(r.length,o.length);for(let s=0;s<i;s++){let a=r[s]??0,c=o[s]??0;if(a!==c)return a<c}return false}function et(){try{let e=g__namespace.join(E__namespace.homedir(),".config","opencrater","runtime"),t=g__namespace.join(e,".last-update"),n=g__namespace.join(e,".force-update");try{if(Date.now()-u__namespace.statSync(n).mtimeMs<600*1e3)return}catch{}u__namespace.mkdirSync(e,{recursive:!0}),u__namespace.writeFileSync(n,String(Date.now()));try{u__namespace.rmSync(t,{force:!0});}catch{}oe(e);}catch{}}function kn(){try{let e=g__namespace.join(E__namespace.homedir(),".config","opencrater");u__namespace.mkdirSync(e,{recursive:!0}),u__namespace.writeFileSync(g__namespace.join(e,"activity.signal"),String(Date.now()));}catch{}}var wn=1440*60*1e3;function vn(){try{let e=g__namespace.join(E__namespace.homedir(),".config","opencrater"),t=g__namespace.join(e,".last-host-check"),n=g__namespace.join(e,".known-hosts"),r=te().sort(),o=[];try{let a=JSON.parse(u__namespace.readFileSync(n,"utf8"));Array.isArray(a)&&(o=a.filter(c=>typeof c=="string"));}catch{}if(!r.some(a=>!o.includes(a)))try{if(Date.now()-u__namespace.statSync(t).mtimeMs<wn)return}catch{}u__namespace.mkdirSync(e,{recursive:!0});try{u__namespace.writeFileSync(t,String(Date.now()));}catch{return}let s=X();try{u__namespace.writeFileSync(n,JSON.stringify(r));}catch{}if(s.optOut)return;if(s.devToken)try{ne();}catch{}for(let a of s.integrations)try{ne(a.key,a.package);}catch{}}catch{}}async function Cn(){let e=sn(process.argv.slice(2));tt=e.host,kn(),bn(),vn();let t=await an(on),n={};if(t)try{n=JSON.parse(t);let p=n.hook_event_name;!e.placement&&typeof p=="string"&&(e.placement=p);}catch{}let r=e.placement??"SessionStart",o=X();h(`state=${L()} devToken=${o.devToken?"present":"MISSING"}`,`host=${e.host} placement=${r}`);let i=Ve({env:process.env,state:o,now:Date.now()},{skipTTY:true});if(i!==null){if(i==="frequency"){let p=se(n);p.length>0&&y({...o,sessionTopics:ae(o.sessionTopics,p,Date.now())});}h("hook suppressed:",i);return}if(o={...o,sessionTopics:ae(o.sessionTopics,se(n),Date.now())},!yn(o,e.package,e.host,r)){y(o),h("hook gated: placement",r,"not selected for",e.package);return}let s=V(o.cachedConfig),a=W(),c={origin:a,timeoutMs:Math.min(s.serveTimeoutMs,rn),installId:o.installId,topics:We(o.sessionTopics,Date.now())};if(o.devToken){let p=await me(o.devToken,{publisherKey:e.key??"",packageName:e.package??"",placement:r,host:e.host},c);if(p){if(o={...o,cachedConfig:p.config,configFetchedAt:Date.now()},Qe(R,p.config.minSdkVersion)&&et(),tn);let O=e.host??"claude_code",ce=He(O,r),_=o.computeCards??{turns:0,lastLimitAt:0,lastDepletedAt:0,lastBackupAt:0};ce&&(_.turns+=1);let I=Ue({balanceMicroUsd:typeof p.computeBalanceMicroUsd=="number"?p.computeBalanceMicroUsd:null,weeklyGrantMicroUsd:typeof p.weeklyGrantMicroUsd=="number"?p.weeklyGrantMicroUsd:null,onGateway:(process.env.ANTHROPIC_BASE_URL??"").includes("/gateway"),turnEnd:ce,host:je(O),cc:_,now:Date.now()}),nt=(p.config.displayDurationSeconds??25)*1e3,v=p.fill&&p.blip&&!U(p.blip.campaignId)&&!G(p.blip.campaignId)?p.blip:null;if((I||v)&&!Xe(nt)&&Ze())if(I){let A=Date.now();I.kind==="limit"?_.lastLimitAt=A:I.kind==="depleted"?_.lastDepletedAt=A:I.kind==="backup"&&(_.lastBackupAt=A),o=await D({...I.card,label:"OpenCrater"},o);}else v&&(F(v.campaignId),o=await D(H(v),o,v.creative,v.impressionId,v.campaignId),o.devToken&&ge(o.devToken,v.impressionId,c));o={...o,computeCards:_};}y(o);return}let{blip:d,pool:f}=Q(o,Date.now());for(;d&&(U(d.campaignId)||G(d.campaignId));)h("hook: pooled blip skipped \u2014 campaign inside a local cooldown"),{blip:d,pool:f}=Q({pool:f},Date.now());if((d||e.key)&&Xe((s.displayDurationSeconds??25)*1e3)){y(o),h("hook: a card is already on screen \u2014 not rendering another");return}if((d||e.key)&&!Ze()){y(o),h("hook: render slot already claimed by a concurrent fire");return}if(d){F(d.campaignId),o=await D(H(d),{...o,pool:f},d.creative,d.impressionId,d.campaignId),y(o),await Promise.race([q(d.impressionId,c),new Promise(p=>setTimeout(p,qe).unref?.())]);return}if(f.length!==o.pool.length&&(o={...o,pool:f}),!e.key||!e.package){y(o),h("hook: pool empty and no --key/--package; nothing to render");return}let l=await fe({publisherKey:e.key,packageName:e.package,placement:r,host:e.host},c);if(!l){y(o);return}if(o={...o,cachedConfig:l.config,configFetchedAt:Date.now()},Qe(R,l.config.minSdkVersion)&&(h(`SDK ${R} below floor ${l.config.minSdkVersion} \u2014 forcing runtime update`),et()),e.package&&l.allowedPlacements&&(o={...o,allowedPlacements:{...o.allowedPlacements,[`${e.package}:${e.host}`]:l.allowedPlacements}}),l.fill&&l.blip){if(U(l.blip.campaignId)||G(l.blip.campaignId)){h("hook: served blip suppressed \u2014 campaign inside a local cooldown"),y(o);return}F(l.blip.campaignId),o=await D(H(l.blip),o,l.blip.creative,l.blip.impressionId,l.blip.campaignId),y(o),await Promise.race([q(l.blip.impressionId,c),new Promise(p=>setTimeout(p,qe).unref?.())]);return}l.fallback&&(o=await D(ye(l.fallback),o)),y(o);}if(typeof P<"u"&&typeof module<"u"&&P.main===module){let e=setTimeout(()=>process.exit(0),nn);Cn().catch(t=>h(`opencrater-hook v${R} error:`,t)).finally(()=>{clearTimeout(e),process.exit(0);});}
6
- exports.decodeTtyNr=pn;exports.painterSpawnOptions=gn;exports.parseProcStat=dn;exports.parsePsLine=un;exports.resolveTtyPath=mn;exports.ttyNameToDevPath=ln;
2
+ 'use strict';var child_process=require('child_process'),u=require('fs'),C=require('os'),g=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 u__namespace=/*#__PURE__*/_interopNamespace(u);var C__namespace=/*#__PURE__*/_interopNamespace(C);var g__namespace=/*#__PURE__*/_interopNamespace(g);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:""},ue={claude_code:["SessionStart","Stop","SessionEnd","Notification"],codex:["Stop"],openclaw:[],gemini_cli:["AfterAgent","SessionStart","SessionEnd"],copilot_cli:["agentStop","sessionStart","sessionEnd","notification"],generic:["SessionStart","Stop"]},pe={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"],generic:["SessionStart","Stop"]};var T="1.1.24";var it="https://api.opencrater.to";function q(e,t=process.env){let n=t.OPENCRATER_API_ORIGIN;return ((n&&n.trim()!==""?n:it)).replace(/\/+$/,"")}function h(...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 B(e){return typeof e=="number"&&Number.isFinite(e)}function st(e){let t=M;if(typeof e!="object"||e===null)return {...t};let n=e;return {minIntervalSeconds:B(n.minIntervalSeconds)?n.minIntervalSeconds:t.minIntervalSeconds,serveTimeoutMs:B(n.serveTimeoutMs)?n.serveTimeoutMs:t.serveTimeoutMs,preloadPoolSize:B(n.preloadPoolSize)?n.preloadPoolSize:t.preloadPoolSize,killSwitch:n.killSwitch===true,displayDurationSeconds:B(n.displayDurationSeconds)?n.displayDurationSeconds:t.displayDurationSeconds,minSdkVersion:typeof n.minSdkVersion=="string"?n.minSdkVersion:t.minSdkVersion}}async function j(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():(h(`POST ${t} -> HTTP ${i.status}`),null)}catch(i){return h(`POST ${t} failed:`,i),null}}function de(e,t){let n=e.host??"generic";return {publisherKey:e.publisherKey,packageName:e.packageName,placement:e.placement,host:n,sdkVersion:T,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 fe(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:st(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),n}async function me(e,t){let n=await j(t.origin,"/v1/serve",de(e,t),t.timeoutMs);return fe(n)}async function ge(e,t,n){let r={...de(t,n),publisherKey:t.publisherKey??"",packageName:t.packageName??""},o=await j(n.origin,"/v1/dev/serve",r,n.timeoutMs,{authorization:`Bearer ${e}`});return fe(o)}function he(e,t,n){return j(n.origin,"/v1/dev/impression",{impressionId:t},n.timeoutMs,{authorization:`Bearer ${e}`}).then(()=>{}).catch(()=>{})}function X(e,t){return j(t.origin,"/v1/events/impression",{impressionId:e},t.timeoutMs).then(()=>{}).catch(()=>{})}function ye(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 Se(e){return {sponsorLabel:"",title:e.title,body:e.body,url:e.url}}function H(e){let t=ye(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 $(e=process.env){return g__namespace.join(C__namespace.homedir(),".config","opencrater")}function U(e=process.env){return g__namespace.join($(e),"state.json")}function L(){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 ke=new Set(["EPERM","EACCES","EBUSY","EEXIST"]);function we(e){for(let t=0;;t++)try{return {text:u__namespace.readFileSync(e,"utf8")}}catch(n){let r=n.code??"";if(!(r==="ENOENT"||ke.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 ct(e){if(typeof e!="object"||e===null)return null;let t=e;return !k(t.minIntervalSeconds)||!k(t.serveTimeoutMs)||!k(t.preloadPoolSize)||typeof t.killSwitch!="boolean"?null:{minIntervalSeconds:t.minIntervalSeconds,serveTimeoutMs:t.serveTimeoutMs,preloadPoolSize:t.preloadPoolSize,killSwitch:t.killSwitch,displayDurationSeconds:k(t.displayDurationSeconds)?t.displayDurationSeconds:25,minSdkVersion:typeof t.minSdkVersion=="string"?t.minSdkVersion:""}}function lt(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(!k(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 ut(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 pt(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"||!k(r.at))&&(t.push({topic:r.topic.slice(0,32),at:r.at}),t.length>=24))break}return t}function dt(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 ft(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 mt(e){if(typeof e!="object"||e===null)return null;let t=e,n=r=>k(r)&&r>=0?r:0;return {turns:n(t.turns),lastLimitAt:n(t.lastLimitAt),lastDepletedAt:n(t.lastDepletedAt),lastBackupAt:n(t.lastBackupAt)}}function gt(e){let t=L();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:k(n.lastShownAt)&&n.lastShownAt>=0?n.lastShownAt:0,optOut:n.optOut===true,disclosureShown:n.disclosureShown===true,cachedConfig:ct(n.cachedConfig),allowedPlacements:ut(n.allowedPlacements),sessionTopics:pt(n.sessionTopics),integrations:dt(n.integrations),devToken:typeof n.devToken=="string"?n.devToken:null,computeRouting:ft(n.computeRouting),computeCards:mt(n.computeCards),configFetchedAt:k(n.configFetchedAt)&&n.configFetchedAt>=0?n.configFetchedAt:0,pool:lt(n.pool)}}function Z(e=process.env){let t=U(e),n=we(t);if(n.text!==void 0)try{return gt(JSON.parse(n.text))}catch{let r=L();try{y(r,e);}catch{}return r}if(n.missing){let r=L();try{y(r,e);}catch{}return r}return L()}function y(e,t=process.env,n={}){let r=U(t),o=g__namespace.dirname(r);u__namespace.mkdirSync(o,{recursive:true});let i=we(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=g__namespace.join(o,`.state.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`);u__namespace.writeFileSync(c,JSON.stringify(e,null,2)+`
4
+ `,"utf8");for(let a=0;;a++)try{u__namespace.renameSync(c,r);return}catch(p){let f=p.code??"";if(a>=4||!ke.has(f)){try{u__namespace.rmSync(c,{force:!0});}catch{}if(a>=4)return;throw p}try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(a+1));}catch{}}}var ht=300*1e3;function yt(){return g__namespace.join($(),"blocked-ads.json")}function Q(){return g__namespace.join($(),"recent-renders.json")}function St(){return g__namespace.join($(),"reported-ads.json")}function ve(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 bt(e){try{let t=JSON.parse(u__namespace.readFileSync(yt(),"utf8"));return ve(t&&typeof t=="object"?t:{},e)}catch{return {}}}function kt(){try{let e=JSON.parse(u__namespace.readFileSync(St(),"utf8"));return e&&typeof e=="object"?e:{}}catch{return {}}}function wt(e){return e?kt()[e]!==void 0:false}function F(e,t=Date.now()){return e?bt(t)[e]!==void 0||wt(e):false}function Ee(e){try{let t=JSON.parse(u__namespace.readFileSync(Q(),"utf8"));return ve(t&&typeof t=="object"?t:{},e)}catch{return {}}}function J(e,t=Date.now()){if(e)try{let n=Ee(t);n[e]=t+ht,u__namespace.mkdirSync(g__namespace.dirname(Q()),{recursive:!0}),u__namespace.writeFileSync(Q(),JSON.stringify(n));}catch{}}function G(e,t=Date.now()){return e?Ee(t)[e]!==void 0:false}function vt(e,t){return e.filter(n=>n.renderBy>t)}function ee(e,t){let n=vt(e.pool,t),r=n.shift();return {blip:r?r.blip:null,pool:n}}var Et=["claude_code","codex","gemini_cli","copilot_cli"];function Ae(e){return e.includes("opencrater-hook")}function Ct(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Tt(e,t){return Ae(e)&&new RegExp(`--package ['"]?${Ct(t)}['"]?`).test(e)}function Pe(e,t){return t?Tt(e,t):Ae(e)&&!/--package\b/.test(e)}function Ce(e){return /^[A-Za-z0-9@_./:-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}var Te='"$HOME/.config/opencrater/runtime/node_modules/opencrater/dist/hook.js"',Re="$env:USERPROFILE\\.config\\opencrater\\runtime\\node_modules\\opencrater\\dist\\hook.js";function te(e,t,n,r){let o=`--placement ${t}`;return n&&(o+=` --key ${Ce(n)}`),r&&(o+=` --package ${Ce(r)}`),o+=` --host ${e}`,`{ if [ -f ${Te} ]; then node ${Te} ${o}; else npx -y -p opencrater opencrater-hook ${o}; fi; } 2>/dev/null || true`}function Rt(e,t,n,r){let o=`--placement ${t}`;return n&&(o+=` --key '${n}'`),r&&(o+=` --package '${r}'`),o+=` --host ${e}`,`try { if (Test-Path "${Re}") { node "${Re}" ${o} } else { npx -y -p opencrater opencrater-hook ${o} } } catch {}`}function Oe(e,t,n,r){return te(e,t,n,r)}function xe(e,t){let n=C__namespace.homedir();switch(e){case "claude_code":{let r=t.CLAUDE_CONFIG_DIR;return r&&r.trim()!==""?r:g__namespace.join(n,".claude")}case "codex":{let r=t.CODEX_HOME;return r&&r.trim()!==""?r:g__namespace.join(n,".codex")}case "gemini_cli":return g__namespace.join(n,".gemini");case "copilot_cli":{let r=t.COPILOT_HOME;return r&&r.trim()!==""?r:g__namespace.join(n,".copilot")}default:return g__namespace.join(n,".opencrater-unknown")}}function K(e,t=process.env){let n=xe(e,t);switch(e){case "claude_code":return g__namespace.join(n,"settings.json");case "codex":return g__namespace.join(n,"hooks.json");case "gemini_cli":return g__namespace.join(n,"settings.json");case "copilot_cli":return g__namespace.join(n,"hooks","hooks.json");default:return g__namespace.join(n,"hooks.json")}}var Ot={claude_code:["claude"],codex:["codex"],gemini_cli:["gemini"],copilot_cli:["copilot"]};function It(e,t){if(e.length===0)return false;let n=(t.PATH??t.Path??"").split(g__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(u__namespace.existsSync(g__namespace.join(o,i+s)))return !0}catch{}return false}function _t(e,t=process.env){try{if(u__namespace.existsSync(xe(e,t)))return !0}catch{}return It(Ot[e]??[],t)}function ne(e=process.env){return Et.filter(t=>_t(t,e))}function Ne(e){let t;try{t=u__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=g__namespace.dirname(e);u__namespace.mkdirSync(n,{recursive:true});let r=g__namespace.join(n,`.${g__namespace.basename(e)}.${process.pid}.tmp`);u__namespace.writeFileSync(r,JSON.stringify(t,null,2)+`
5
+ `,"utf8"),u__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 Pt(e,t,n,r){let o=K(e),i=Ne(o),s=i.hooks&&typeof i.hooks=="object"?i.hooks:{};if(r.every(a=>{let p=Oe(e,a,t,n);return (Array.isArray(s[a])?s[a]:[]).some(f=>Array.isArray(f.hooks)&&f.hooks.some(l=>l.command===p))}))return "nochange";for(let a of r){let f=(Array.isArray(s[a])?s[a]:[]).filter(l=>!At(l,n));f.push({matcher:"",hooks:[{type:"command",command:Oe(e,a,t,n)}]}),s[a]=f;}return i.hooks=s,Me(o,i),"wrote"}var Ie=12;function xt(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=K(e),i=Ne(o);typeof i.version!="number"&&(i.version=1);let s=i.hooks&&typeof i.hooks=="object"?i.hooks:{};if(r.every(a=>{let p=te(e,a,t,n);return (Array.isArray(s[a])?s[a]:[]).some(f=>f.bash===p&&f.timeoutSec===Ie)}))return "nochange";for(let a of r){let f=(Array.isArray(s[a])?s[a]:[]).filter(l=>!xt(l,n));f.push({type:"command",bash:te(e,a,t,n),powershell:Rt(e,a,t,n),timeoutSec:Ie}),s[a]=f;}return i.hooks=s,Me(o,i),"wrote"}function $e(e){return [...pe[e]]}function Mt(e,t,n){let r=$e(e);return r.length===0?"nochange":e==="copilot_cli"?Nt(e,t,n,r):Pt(e,t,n,r)}function oe(e,t,n=process.env){return ne(n).map(r=>{try{let o=Mt(r,e,t);return {host:r,status:o,events:$e(r)}}catch(o){return {host:r,status:"error",events:[],error:o.message}}})}function Dt(){return g__namespace.join(C__namespace.homedir(),".config","opencrater","runtime")}function Bt(e){return ["install","--prefix",e,"opencrater@latest","--silent","--no-audit","--no-fund"]}function re(e=Dt()){child_process.spawn("npm",Bt(e),process.platform==="win32"?{detached:false,stdio:"ignore",windowsHide:true,shell:true}:{detached:true,stdio:"ignore"}).unref();}var He={atLimit:false,resetAt:null};function Le(e,t=C__namespace.homedir()){try{if(e==="claude_code")return jt(t);if(e==="codex")return Ht(t)}catch{}return He}function jt(e){let t=u__namespace.readFileSync(g__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 Ht(e){return u__namespace.accessSync(g__namespace.join(e,".codex","auth.json")),He}function Ue(e,t){switch(e){case "gemini_cli":return t==="AfterAgent";case "copilot_cli":return t==="agentStop";default:return t==="Stop"}}var Fe=36e5,Lt=30*6e4,Ut=30*6e4,Ft=4*Fe,Jt=3,Y="https://opencrater.to/dashboard";function z(e){return `$${(e/1e6).toFixed(2)}`}function Gt(e,t){return t<=0?0:Math.max(0,Math.min(100,Math.round(e/t*100)))}function Kt(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/Fe))}h`,o=new Date(e).toISOString().slice(0,10);return ` Your host limit resets in ${r} (${o}).`}function Je(e){let{balanceMicroUsd:t,weeklyGrantMicroUsd:n,onGateway:r,turnEnd:o,host:i,cc:s,now:c}=e;if(t===null)return null;if(t<=0)return c-(s.lastDepletedAt??0)<Ut?null:{kind:"depleted",card:{sponsorLabel:"OpenCrater",title:"Compute used up",body:"Keep coding in Codex / Copilot to earn more compute, then switch back to Claude Code."+Kt(i.resetAt,c),url:Y,cta:"Earn more"}};if(r){if(!o||(s.turns??0)%Jt!==0)return null;let a=n&&n>0?Gt(t,n):null;return {kind:"hud",card:{sponsorLabel:"OpenCrater",title:"Running on OpenCrater compute",body:a!==null?`${a}% of your weekly compute left \u2014 ${z(t)} remaining.`:`${z(t)} of compute remaining this week.`,url:Y,cta:"Wallet"}}}return i.atLimit?c-(s.lastLimitAt??0)<Lt?null:{kind:"limit",card:{sponsorLabel:"OpenCrater",title:"Hit your limit? You've got compute",body:`${z(t)} of OpenCrater compute is ready. Continue this session now: opencrater code -c`,url:Y,cta:"opencrater code -c"}}:c-(s.lastBackupAt??0)>=Ft?{kind:"backup",card:{sponsorLabel:"OpenCrater",title:"Backup compute ready",body:`${z(t)} of OpenCrater compute waiting. When you hit your limit: opencrater code -c`,url:Y,cta:"opencrater code -c"}}:null}var Wt=["CI","CONTINUOUS_INTEGRATION","GITHUB_ACTIONS","GITLAB_CI","CIRCLECI","TRAVIS","BUILDKITE","JENKINS_URL","TEAMCITY_VERSION","TF_BUILD","APPVEYOR","CODEBUILD_BUILD_ID","DRONE","NETLIFY","VERCEL"];function se(e){return e!==void 0&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}function qt(e){return se(e.OPENCRATER_DISABLE)||se(e.TSN_DISABLE)}function Xt(e){return Wt.some(t=>se(e[t]))}function W(e){return e?{...M,...e}:M}function qe(e,t={}){if(qt(e.env))return "env_disabled";if(e.state.optOut)return "opt_out";let n=W(e.state.cachedConfig);if(n.killSwitch)return "kill_switch";if(Xt(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 Zt=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 Qt(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 en(e,t=12){let n=[];for(let r of e.slice(0,2e3).split(/\s+/))if(!(!r||Qt(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)||Zt.has(i))&&!n.includes(i)&&(n.push(i),n.length>=t))return n}return n}function ae(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 en(t.join(" "))}function ce(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 Xe(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 on=false,rn=process.platform==="win32"?8e3:3200,sn=150,Ze=250,an=2800,ot="claude_code";function cn(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==="generic")&&(t.host=o,n++);break;}}return t}function ln(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 un="\\\\.\\CONOUT$";function pn(e){return !e||e==="?"||e==="??"||e==="-"?null:e.startsWith("/")?e:`/dev/${e}`}function dn(e){let t=e.match(/^\s*(\d+)\s+(\S+)/);return t?{ppid:Number(t[1]),tty:t[2]}:null}function fn(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 mn(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 gn(e){try{let t=mn(u__namespace.readFileSync(`/proc/${e}/stat`,"utf8"));if(t)return {ppid:t.ppid,ttyPath:fn(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=dn(t);return n?{ppid:n.ppid,ttyPath:pn(n.tty)}:null}catch{return null}}function hn(){if(process.platform==="win32")return {path:un,ownerPid:null};let e=process.pid;for(let t=0;t<12&&e>1;t++){let n=gn(e);if(!n)return null;if(n.ttyPath)return {path:n.ttyPath,ownerPid:e};e=n.ppid;}return null}function yn(e){return e==="win32"?{detached:false,stdio:"ignore",windowsHide:false}:{detached:true,stdio:"ignore",windowsHide:false}}async function D(e,t,n,r,o){try{let i=g__namespace.join(__dirname,"paint.js"),s=W(t.cachedConfig),c=Math.min(Math.max(s.displayDurationSeconds??25,3),120),a={...e,format:n?.format,mediaUrl:n?.mediaUrl,mediaPixelUrl:n?.mediaPixelUrl,audioUrl:n?.audioUrl,impressionId:r,campaignId:o,apiOrigin:q(),durationMs:c*1e3,disclosure:!t.disclosureShown,host:ot},p={...process.env,OPENCRATER_PAINT:JSON.stringify(a)};if(!p.OPENCRATER_TTY){let l=hn();l&&(p.OPENCRATER_TTY=l.path,l.ownerPid!==null&&(p.OPENCRATER_HOST_PID=String(l.ownerPid)));}let f=child_process.spawn(process.execPath,[i],{...yn(process.platform),env:p});process.platform==="win32"?await new Promise(l=>{let d=!1,O=()=>{d||(d=!0,l());};f.on("exit",O),f.on("error",O),setTimeout(O,7500);}):f.unref();}catch{}return {...t,lastShownAt:Date.now(),disclosureShown:true}}function Qe(e){if(process.platform!=="win32")return false;try{let t=g__namespace.join(C__namespace.homedir(),".config","opencrater","painter.lock"),n=JSON.parse(u__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 Sn=8e3;function et(){let e=g__namespace.join(C__namespace.homedir(),".config","opencrater","render.lock");try{let t=u__namespace.statSync(e);if(Date.now()-t.mtimeMs<Sn)return !1;u__namespace.unlinkSync(e);}catch{}try{return u__namespace.mkdirSync(g__namespace.join(C__namespace.homedir(),".config","opencrater"),{recursive:!0}),u__namespace.writeFileSync(e,String(process.pid),{flag:"wx"}),!0}catch{return false}}function bn(e,t,n,r){if(!t)return true;let o=e.allowedPlacements[`${t}:${n}`];return o?o.includes(r):t==="opencrater"?ue[n].includes(r):true}var kn=1440*60*1e3;function wn(){try{let e=g__namespace.join(C__namespace.homedir(),".config","opencrater","runtime"),t=g__namespace.join(e,"node_modules","opencrater","dist","hook.js"),n=g__namespace.join(e,".last-update");if(u__namespace.existsSync(t)){try{if(Date.now()-u__namespace.statSync(n).mtimeMs<kn)return}catch{}try{u__namespace.writeFileSync(n,String(Date.now()));}catch{return}}else {let r=g__namespace.join(e,".installing");try{u__namespace.mkdirSync(e,{recursive:!0});let o=u__namespace.statSync(r);if(Date.now()-o.mtimeMs<600*1e3)return}catch{}u__namespace.writeFileSync(r,String(Date.now()));}re(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=g__namespace.join(C__namespace.homedir(),".config","opencrater","runtime"),t=g__namespace.join(e,".last-update"),n=g__namespace.join(e,".force-update");try{if(Date.now()-u__namespace.statSync(n).mtimeMs<600*1e3)return}catch{}u__namespace.mkdirSync(e,{recursive:!0}),u__namespace.writeFileSync(n,String(Date.now()));try{u__namespace.rmSync(t,{force:!0});}catch{}re(e);}catch{}}function vn(){try{let e=g__namespace.join(C__namespace.homedir(),".config","opencrater");u__namespace.mkdirSync(e,{recursive:!0}),u__namespace.writeFileSync(g__namespace.join(e,"activity.signal"),String(Date.now()));}catch{}}var En=1440*60*1e3;function Cn(){try{let e=g__namespace.join(C__namespace.homedir(),".config","opencrater"),t=g__namespace.join(e,".last-host-check"),n=g__namespace.join(e,".known-hosts"),r=ne().sort(),o=[];try{let c=JSON.parse(u__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()-u__namespace.statSync(t).mtimeMs<En)return}catch{}u__namespace.mkdirSync(e,{recursive:!0});try{u__namespace.writeFileSync(t,String(Date.now()));}catch{return}let s=Z();try{u__namespace.writeFileSync(n,JSON.stringify(r));}catch{}if(s.optOut)return;if(s.devToken)try{oe();}catch{}for(let c of s.integrations)try{oe(c.key,c.package);}catch{}}catch{}}async function Tn(){let e=cn(process.argv.slice(2));ot=e.host,vn(),wn(),Cn();let t=await ln(sn),n={};if(t)try{n=JSON.parse(t);let d=n.hook_event_name;!e.placement&&typeof d=="string"&&(e.placement=d);}catch{}let r=e.placement??"SessionStart",o=Z();h(`state=${U()} devToken=${o.devToken?"present":"MISSING"}`,`host=${e.host} placement=${r}`);let i=qe({env:process.env,state:o,now:Date.now()},{skipTTY:true});if(i!==null){if(i==="frequency"){let d=ae(n);d.length>0&&y({...o,sessionTopics:ce(o.sessionTopics,d,Date.now())});}h("hook suppressed:",i);return}if(o={...o,sessionTopics:ce(o.sessionTopics,ae(n),Date.now())},!bn(o,e.package,e.host,r)){y(o),h("hook gated: placement",r,"not selected for",e.package);return}let s=W(o.cachedConfig),c=q(),a={origin:c,timeoutMs:Math.min(s.serveTimeoutMs,an),installId:o.installId,topics:Xe(o.sessionTopics,Date.now())};if(o.devToken){let d=await ge(o.devToken,{publisherKey:e.key??"",packageName:e.package??"",placement:r,host:e.host},a);if(d){if(o={...o,cachedConfig:d.config,configFetchedAt:Date.now()},tt(T,d.config.minSdkVersion)&&nt(),on);let O=e.host??"claude_code",le=Ue(O,r),I=o.computeCards??{turns:0,lastLimitAt:0,lastDepletedAt:0,lastBackupAt:0};le&&(I.turns+=1);let _=Je({balanceMicroUsd:typeof d.computeBalanceMicroUsd=="number"?d.computeBalanceMicroUsd:null,weeklyGrantMicroUsd:typeof d.weeklyGrantMicroUsd=="number"?d.weeklyGrantMicroUsd:null,onGateway:(process.env.ANTHROPIC_BASE_URL??"").includes("/gateway"),turnEnd:le,host:Le(O),cc:I,now:Date.now()}),rt=(d.config.displayDurationSeconds??25)*1e3,v=d.fill&&d.blip&&!F(d.blip.campaignId)&&!G(d.blip.campaignId)?d.blip:null;if((_||v)&&!Qe(rt)&&et())if(_){let A=Date.now();_.kind==="limit"?I.lastLimitAt=A:_.kind==="depleted"?I.lastDepletedAt=A:_.kind==="backup"&&(I.lastBackupAt=A),o=await D({..._.card,label:"OpenCrater"},o);}else v&&(J(v.campaignId),o=await D(H(v),o,v.creative,v.impressionId,v.campaignId),o.devToken&&he(o.devToken,v.impressionId,a));o={...o,computeCards:I};}y(o);return}let{blip:p,pool:f}=ee(o,Date.now());for(;p&&(F(p.campaignId)||G(p.campaignId));)h("hook: pooled blip skipped \u2014 campaign inside a local cooldown"),{blip:p,pool:f}=ee({pool:f},Date.now());if((p||e.key)&&Qe((s.displayDurationSeconds??25)*1e3)){y(o),h("hook: a card is already on screen \u2014 not rendering another");return}if((p||e.key)&&!et()){y(o),h("hook: render slot already claimed by a concurrent fire");return}if(p){J(p.campaignId),o=await D(H(p),{...o,pool:f},p.creative,p.impressionId,p.campaignId),y(o),await Promise.race([X(p.impressionId,a),new Promise(d=>setTimeout(d,Ze).unref?.())]);return}if(f.length!==o.pool.length&&(o={...o,pool:f}),!e.key||!e.package){y(o),h("hook: pool empty and no --key/--package; nothing to render");return}let l=await me({publisherKey:e.key,packageName:e.package,placement:r,host:e.host},a);if(!l){y(o);return}if(o={...o,cachedConfig:l.config,configFetchedAt:Date.now()},tt(T,l.config.minSdkVersion)&&(h(`SDK ${T} below floor ${l.config.minSdkVersion} \u2014 forcing runtime update`),nt()),e.package&&l.allowedPlacements&&(o={...o,allowedPlacements:{...o.allowedPlacements,[`${e.package}:${e.host}`]:l.allowedPlacements}}),l.fill&&l.blip){if(F(l.blip.campaignId)||G(l.blip.campaignId)){h("hook: served blip suppressed \u2014 campaign inside a local cooldown"),y(o);return}J(l.blip.campaignId),o=await D(H(l.blip),o,l.blip.creative,l.blip.impressionId,l.blip.campaignId),y(o),await Promise.race([X(l.blip.impressionId,a),new Promise(d=>setTimeout(d,Ze).unref?.())]);return}l.fallback&&(o=await D(Se(l.fallback),o)),y(o);}if(typeof P<"u"&&typeof module<"u"&&P.main===module){let e=setTimeout(()=>process.exit(0),rn);Tn().catch(t=>h(`opencrater-hook v${T} error:`,t)).finally(()=>{clearTimeout(e),process.exit(0);});}
6
+ exports.decodeTtyNr=fn;exports.painterSpawnOptions=yn;exports.parseProcStat=mn;exports.parsePsLine=dn;exports.resolveTtyPath=hn;exports.ttyNameToDevPath=pn;
package/dist/index.d.mts CHANGED
@@ -224,7 +224,7 @@ declare function renderBlip(blip: Blip, opts?: MediaRenderOptions): Promise<stri
224
224
 
225
225
  /** Keep in sync with package.json (bundled, so we avoid a runtime fs read).
226
226
  * AUTO-GENERATED by scripts/sync-version.mjs on `npm version`. */
227
- declare const SDK_VERSION = "1.1.22";
227
+ declare const SDK_VERSION = "1.1.24";
228
228
 
229
229
  /** Public API. Every method is fail-silent: it never throws. */
230
230
  declare const sponsor: {
package/dist/index.d.ts CHANGED
@@ -224,7 +224,7 @@ declare function renderBlip(blip: Blip, opts?: MediaRenderOptions): Promise<stri
224
224
 
225
225
  /** Keep in sync with package.json (bundled, so we avoid a runtime fs read).
226
226
  * AUTO-GENERATED by scripts/sync-version.mjs on `npm version`. */
227
- declare const SDK_VERSION = "1.1.22";
227
+ declare const SDK_VERSION = "1.1.24";
228
228
 
229
229
  /** Public API. Every method is fail-silent: it never throws. */
230
230
  declare const sponsor: {
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
- 'use strict';var crypto=require('crypto'),p=require('fs'),ee=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 p__namespace=/*#__PURE__*/_interopNamespace(p);var ee__namespace=/*#__PURE__*/_interopNamespace(ee);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 re=["SessionStart","SessionEnd","Stop","PostToolUse","Notification"];var D="1.1.22";var ie="https://api.opencrater.to";function K(e,t=process.env){let n=t.OPENCRATER_API_ORIGIN;return (e??(n&&n.trim()!==""?n:ie)).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 E(e){return typeof e=="number"&&Number.isFinite(e)}function V(e){let t=b;if(typeof e!="object"||e===null)return {...t};let n=e;return {minIntervalSeconds:E(n.minIntervalSeconds)?n.minIntervalSeconds:t.minIntervalSeconds,serveTimeoutMs:E(n.serveTimeoutMs)?n.serveTimeoutMs:t.serveTimeoutMs,preloadPoolSize:E(n.preloadPoolSize)?n.preloadPoolSize:t.preloadPoolSize,killSwitch:n.killSwitch===true,displayDurationSeconds:E(n.displayDurationSeconds)?n.displayDurationSeconds:t.displayDurationSeconds,minSdkVersion:typeof n.minSdkVersion=="string"?n.minSdkVersion:t.minSdkVersion}}async function N(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 W(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 se(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:V(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),n}async function U(e,t){let n=await N(t.origin,"/v1/serve",W(e,t),t.timeoutMs);return se(n)}async function q(e,t,n){let r=await N(n.origin,"/v1/serve/batch",{...W(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:V(o.config),...Array.isArray(o.allowedPlacements)?{allowedPlacements:o.allowedPlacements.filter(i=>typeof i=="string")}:{}}:null}function j(e,t){return N(t.origin,"/v1/events/impression",{impressionId:e},t.timeoutMs).then(()=>{}).catch(()=>{})}var ae=new RegExp("\x1B\\[[0-9;]*m|\x1B\\]8;;[^\x07\x1B]*(?:\x07|\x1B\\\\)","g"),k={dim:"\x1B[2m",bold:"\x1B[1m",reset:"\x1B[0m"},le=60,ce=24,ue="\u2139 This project is supported by Blips via OpenCrater. Opt out: `npx opencrater off` or OPENCRATER_DISABLE=1";function pe(e){return e.replace(ae,"").length}function y(e,t){return t<=0?"":e.length<=t?e:t===1?"\u2026":e.slice(0,t-1).trimEnd()+"\u2026"}function de(e,t,n){let r=e.split(/\s+/).filter(a=>a.length>0),o=[],i="";for(let a of r){let d=i===""?a:`${i} ${a}`;if(d.length<=t)i=d;else if(i!==""&&o.push(i),i=a.length>t?y(a,t):a,o.length>=n)break}i!==""&&o.length<n&&o.push(i),o.length>n&&(o.length=n);let l=o.join(" "),s=o.length-1,u=o[s];return u!==void 0&&l.length<r.join(" ").length&&(o[s]=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 fe(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 J(e){return {sponsorLabel:"",title:e.title,body:e.body,url:e.url}}function m(e,t={}){let n=t.width??process.stdout.columns??80,o=Math.max(ce,Math.min(n,le))-4,i=t.color??P(),l=t.hyperlinks??O(),s=(f,$)=>i?`${$}${f}${k.reset}`:f,u=e.label?y(e.label,o):e.sponsorLabel?y(`Sponsored Blips \xB7 ${e.sponsorLabel}`,o):"Sponsored Blips",a=[];a.push(s(u,k.dim)),e.title!==e.sponsorLabel&&a.push(s(y(e.title,o),k.bold));for(let f of de(e.body,o,2))a.push(f);let d="\u2192 ";if(l){let f=y(e.cta??e.url,o-d.length);a.push(d+s(fe(e.url,f),k.dim));}else e.cta&&a.push(y(e.cta,o)),a.push(d+s(y(e.url,o-d.length),k.dim));let I=`\u256D${"\u2500".repeat(o+2)}\u256E`,v=`\u2570${"\u2500".repeat(o+2)}\u256F`,L=a.map(f=>{let $=" ".repeat(Math.max(0,o-pe(f)));return `\u2502 ${f}${$} \u2502`}),h=[];return t.disclosure&&h.push(s(ue,k.dim)),h.push(I,...L,v),h.join(`
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.24";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 E(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:E(n.minIntervalSeconds)?n.minIntervalSeconds:t.minIntervalSeconds,serveTimeoutMs:E(n.serveTimeoutMs)?n.serveTimeoutMs:t.serveTimeoutMs,preloadPoolSize:E(n.preloadPoolSize)?n.preloadPoolSize:t.preloadPoolSize,killSwitch:n.killSwitch===true,displayDurationSeconds:E(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),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`,v=`\u2570${"\u2500".repeat(o+2)}\u256F`,N=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,...N,v),h.join(`
3
3
  `)+`
4
- `}function X(e){return e!==void 0&&e!==""}function Y(e=process.env,t=!!process.stdout.isTTY){if(!t)return "none";let n=e.TERM??"";if(X(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"||X(e.KITTY_WINDOW_ID)?"kitty":"none"}var w="\x1B",me="\x07",ge=2e3,Se=2*1024*1024,ye=new Set(["image/png","image/jpeg","image/gif","image/webp"]),B=4096;async function he(e,t=fetch,n={}){let r=n.timeoutMs??ge,o=n.maxBytes??Se;try{let i=await t(e,{signal:AbortSignal.timeout(r)});if(!i.ok)return c(`media: HTTP ${i.status} for ${e}`),null;let l=(i.headers.get("content-type")??"").split(";")[0].trim().toLowerCase();if(!ye.has(l))return c(`media: disallowed content-type "${l}" for ${e}`),null;let s=Number(i.headers.get("content-length")??"0");if(Number.isFinite(s)&&s>o)return c(`media: content-length ${s} exceeds ${o} for ${e}`),null;let u=i.body;if(u&&typeof u.getReader=="function"){let d=u.getReader(),I=[],v=0;for(;;){let{done:L,value:h}=await d.read();if(L)break;if(h!==void 0){if(v+=h.byteLength,v>o)return await d.cancel().catch(()=>{}),c(`media: stream exceeded ${o} bytes for ${e}`),null;I.push(h);}}return Buffer.concat(I)}let a=Buffer.from(await i.arrayBuffer());return a.byteLength>o?(c(`media: body ${a.byteLength} bytes exceeds ${o} for ${e}`),null):a}catch(i){return c(`media: fetch failed for ${e}:`,i),null}}function be(e){let t=e.toString("base64");return `${w}]1337;File=inline=1;size=${e.byteLength};width=auto:${t}${me}`}function ke(e){let t=e.toString("base64");if(t.length<=B)return `${w}_Gf=100,a=T;${t}${w}\\`;let n=[];for(let r=0;r<t.length;r+=B){let o=t.slice(r,r+B),l=`m=${r+B>=t.length?0:1}`,s=r===0?`f=100,a=T,${l}`:l;n.push(`${w}_G${s};${o}${w}\\`);}return n.join("")}function x(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 G(e,t={}){try{let n=e.creative;if(n.format!=="image"&&n.format!=="gif")return m(x(e),t);let r=t.protocol??Y();if(r==="none"||n.mediaUrl===void 0||n.mediaUrl==="")return m(x(e),t);let o={};t.timeoutMs!==void 0&&(o.timeoutMs=t.timeoutMs),t.maxBytes!==void 0&&(o.maxBytes=t.maxBytes);let i=await he(n.mediaUrl,t.fetchImpl??fetch,o);return i===null||i.byteLength===0?m(x(e),t):(r==="kitty"?ke(i):be(i))+`
5
- `+m(A(e),t)}catch(n){return c("media: render failed, falling back to text:",n),m(A(e),t)}}function Ce(e,t){return e.filter(n=>n.renderBy>t)}function Z(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 Q(e,t){let n=Ce(e.pool,t),r=n.shift();return {blip:r?r.blip:null,pool:n}}function Te(e=process.env){return C__namespace.join(ee__namespace.homedir(),".config","opencrater")}function te(e=process.env){return C__namespace.join(Te(e),"state.json")}function ne(){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 g(e){return typeof e=="number"&&Number.isFinite(e)}function Re(e){if(typeof e!="object"||e===null)return null;let t=e;return !g(t.minIntervalSeconds)||!g(t.serveTimeoutMs)||!g(t.preloadPoolSize)||typeof t.killSwitch!="boolean"?null:{minIntervalSeconds:t.minIntervalSeconds,serveTimeoutMs:t.serveTimeoutMs,preloadPoolSize:t.preloadPoolSize,killSwitch:t.killSwitch,displayDurationSeconds:g(t.displayDurationSeconds)?t.displayDurationSeconds:25,minSdkVersion:typeof t.minSdkVersion=="string"?t.minSdkVersion:""}}function Ie(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(!g(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 ve(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 Ee(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"||!g(r.at))&&(t.push({topic:r.topic.slice(0,32),at:r.at}),t.length>=24))break}return t}function Oe(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 Pe(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 Ae(e){if(typeof e!="object"||e===null)return null;let t=e,n=r=>g(r)&&r>=0?r:0;return {turns:n(t.turns),lastLimitAt:n(t.lastLimitAt),lastDepletedAt:n(t.lastDepletedAt),lastBackupAt:n(t.lastBackupAt)}}function Be(e){let t=ne();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:g(n.lastShownAt)&&n.lastShownAt>=0?n.lastShownAt:0,optOut:n.optOut===true,disclosureShown:n.disclosureShown===true,cachedConfig:Re(n.cachedConfig),allowedPlacements:ve(n.allowedPlacements),sessionTopics:Ee(n.sessionTopics),integrations:Oe(n.integrations),devToken:typeof n.devToken=="string"?n.devToken:null,computeRouting:Pe(n.computeRouting),computeCards:Ae(n.computeCards),configFetchedAt:g(n.configFetchedAt)&&n.configFetchedAt>=0?n.configFetchedAt:0,pool:Ie(n.pool)}}function T(e=process.env){let t=te(e);try{let n=p__namespace.readFileSync(t,"utf8"),r=JSON.parse(n);return Be(r)}catch{let n=ne();try{S(n,e);}catch{}return n}}function S(e,t=process.env,n={}){let r=te(t),o=C__namespace.dirname(r);p__namespace.mkdirSync(o,{recursive:true});try{let s=JSON.parse(p__namespace.readFileSync(r,"utf8"));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});}catch{}let i=C__namespace.join(o,`.state.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`);p__namespace.writeFileSync(i,JSON.stringify(e,null,2)+`
6
- `,"utf8");let l=new Set(["EPERM","EACCES","EBUSY","EEXIST"]);for(let s=0;;s++)try{p__namespace.renameSync(i,r);return}catch(u){let a=u.code??"";if(s>=4||!l.has(a)){try{p__namespace.rmSync(i,{force:!0});}catch{}if(s>=4)return;throw u}try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(s+1));}catch{}}}var xe=["CI","CONTINUOUS_INTEGRATION","GITHUB_ACTIONS","GITLAB_CI","CIRCLECI","TRAVIS","BUILDKITE","JENKINS_URL","TEAMCITY_VERSION","TF_BUILD","APPVEYOR","CODEBUILD_BUILD_ID","DRONE","NETLIFY","VERCEL"];function H(e){return e!==void 0&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}function _e(e){return H(e.OPENCRATER_DISABLE)||H(e.TSN_DISABLE)}function Me(e){return xe.some(t=>H(e[t]))}function z(e){return e?{...b,...e}:b}function R(e,t={}){if(_e(e.env))return "env_disabled";if(e.state.optOut)return "opt_out";let n=z(e.state.cachedConfig);if(n.killSwitch)return "kill_switch";if(Me(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 _(e){try{return await e()}catch(t){return c("suppressed error:",t),null}}function M(e,t){let n=z(t.cachedConfig);return {origin:K(e.apiOrigin),timeoutMs:n.serveTimeoutMs,installId:t.installId,config:n}}function Le(e,t){let n=!t.disclosureShown,r=m(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 oe(e,t){let n=await G(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 $e(e){let t=T(),n=R({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=M(e,t),o=await U(e,r);return o?(S({...t,cachedConfig:o.config,configFetchedAt:Date.now()}),o.fill&&o.blip?o.blip:null):null}async function Fe(e){let t=T(),n=R({env:process.env,isTTY:!!process.stdout.isTTY,state:t,now:Date.now()});if(n!==null)return c("suppressed:",n),false;let r=M(e,t),o=await U(e,r);return o?(t={...t,cachedConfig:o.config,configFetchedAt:Date.now()},o.fill&&o.blip?(t=await oe(o.blip,t),S(t),j(o.blip.impressionId,r),true):o.fallback?(t=Le(J(o.fallback),t),S(t),true):(S(t),false)):false}async function De(e){let t=T(),n=R({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=M(e,t),o=Math.max(1,r.config.preloadPoolSize),i=await q(e,o,r);if(!i)return 0;let l=Date.now(),s=Z(i.blips,l);return S({...t,pool:s,cachedConfig:i.config,configFetchedAt:l}),s.length}async function Ne(e){let t=T(),n=Date.now(),r=R({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}=Q(t,n);if(!o)return S({...t,pool:i}),false;let l=await oe(o,{...t,pool:i});S(l);let s=M(e,t);return j(o.impressionId,s),true}var ct={show(e){return _(()=>Fe(e)).then(t=>t??false)},fetch(e){return _(()=>$e(e))},preload(e){return _(()=>De(e)).then(t=>t??0)},renderFromPool(e){return _(()=>Ne(e)).then(t=>t??false)}};exports.DEFAULT_CONFIG=b;exports.HOOK_CATALOG=re;exports.SDK_VERSION=D;exports.detectImageProtocol=Y;exports.renderBlip=G;exports.renderCard=m;exports.sponsor=ct;exports.textCardForBlip=x;
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=[],v=0;for(;;){let{done:N,value:h}=await p.read();if(N)break;if(h!==void 0){if(v+=h.byteLength,v>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 ve(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 Ee(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:ve(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:Ee(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 Le(e){return z(e.OPENCRATER_DISABLE)||z(e.TSN_DISABLE)}function Ne(e){return Me.some(t=>z(e[t]))}function K(e){return e?{...b,...e}:b}function I(e,t={}){if(Le(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(Ne(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 L(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=L(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=L(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=L(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=L(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;
package/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import {randomUUID}from'crypto';import*as p from'fs';import*as ee 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 re=["SessionStart","SessionEnd","Stop","PostToolUse","Notification"];var D="1.1.22";var ie="https://api.opencrater.to";function K(e,t=process.env){let n=t.OPENCRATER_API_ORIGIN;return (e??(n&&n.trim()!==""?n:ie)).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 E(e){return typeof e=="number"&&Number.isFinite(e)}function V(e){let t=b;if(typeof e!="object"||e===null)return {...t};let n=e;return {minIntervalSeconds:E(n.minIntervalSeconds)?n.minIntervalSeconds:t.minIntervalSeconds,serveTimeoutMs:E(n.serveTimeoutMs)?n.serveTimeoutMs:t.serveTimeoutMs,preloadPoolSize:E(n.preloadPoolSize)?n.preloadPoolSize:t.preloadPoolSize,killSwitch:n.killSwitch===true,displayDurationSeconds:E(n.displayDurationSeconds)?n.displayDurationSeconds:t.displayDurationSeconds,minSdkVersion:typeof n.minSdkVersion=="string"?n.minSdkVersion:t.minSdkVersion}}async function N(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 W(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 se(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:V(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),n}async function U(e,t){let n=await N(t.origin,"/v1/serve",W(e,t),t.timeoutMs);return se(n)}async function q(e,t,n){let r=await N(n.origin,"/v1/serve/batch",{...W(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:V(o.config),...Array.isArray(o.allowedPlacements)?{allowedPlacements:o.allowedPlacements.filter(i=>typeof i=="string")}:{}}:null}function j(e,t){return N(t.origin,"/v1/events/impression",{impressionId:e},t.timeoutMs).then(()=>{}).catch(()=>{})}var ae=new RegExp("\x1B\\[[0-9;]*m|\x1B\\]8;;[^\x07\x1B]*(?:\x07|\x1B\\\\)","g"),k={dim:"\x1B[2m",bold:"\x1B[1m",reset:"\x1B[0m"},le=60,ce=24,ue="\u2139 This project is supported by Blips via OpenCrater. Opt out: `npx opencrater off` or OPENCRATER_DISABLE=1";function pe(e){return e.replace(ae,"").length}function y(e,t){return t<=0?"":e.length<=t?e:t===1?"\u2026":e.slice(0,t-1).trimEnd()+"\u2026"}function de(e,t,n){let r=e.split(/\s+/).filter(a=>a.length>0),o=[],i="";for(let a of r){let d=i===""?a:`${i} ${a}`;if(d.length<=t)i=d;else if(i!==""&&o.push(i),i=a.length>t?y(a,t):a,o.length>=n)break}i!==""&&o.length<n&&o.push(i),o.length>n&&(o.length=n);let l=o.join(" "),s=o.length-1,u=o[s];return u!==void 0&&l.length<r.join(" ").length&&(o[s]=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 fe(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 J(e){return {sponsorLabel:"",title:e.title,body:e.body,url:e.url}}function m(e,t={}){let n=t.width??process.stdout.columns??80,o=Math.max(ce,Math.min(n,le))-4,i=t.color??P(),l=t.hyperlinks??O(),s=(f,$)=>i?`${$}${f}${k.reset}`:f,u=e.label?y(e.label,o):e.sponsorLabel?y(`Sponsored Blips \xB7 ${e.sponsorLabel}`,o):"Sponsored Blips",a=[];a.push(s(u,k.dim)),e.title!==e.sponsorLabel&&a.push(s(y(e.title,o),k.bold));for(let f of de(e.body,o,2))a.push(f);let d="\u2192 ";if(l){let f=y(e.cta??e.url,o-d.length);a.push(d+s(fe(e.url,f),k.dim));}else e.cta&&a.push(y(e.cta,o)),a.push(d+s(y(e.url,o-d.length),k.dim));let I=`\u256D${"\u2500".repeat(o+2)}\u256E`,v=`\u2570${"\u2500".repeat(o+2)}\u256F`,L=a.map(f=>{let $=" ".repeat(Math.max(0,o-pe(f)));return `\u2502 ${f}${$} \u2502`}),h=[];return t.disclosure&&h.push(s(ue,k.dim)),h.push(I,...L,v),h.join(`
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.24";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 E(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:E(n.minIntervalSeconds)?n.minIntervalSeconds:t.minIntervalSeconds,serveTimeoutMs:E(n.serveTimeoutMs)?n.serveTimeoutMs:t.serveTimeoutMs,preloadPoolSize:E(n.preloadPoolSize)?n.preloadPoolSize:t.preloadPoolSize,killSwitch:n.killSwitch===true,displayDurationSeconds:E(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),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`,v=`\u2570${"\u2500".repeat(o+2)}\u256F`,N=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,...N,v),h.join(`
3
3
  `)+`
4
- `}function X(e){return e!==void 0&&e!==""}function Y(e=process.env,t=!!process.stdout.isTTY){if(!t)return "none";let n=e.TERM??"";if(X(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"||X(e.KITTY_WINDOW_ID)?"kitty":"none"}var w="\x1B",me="\x07",ge=2e3,Se=2*1024*1024,ye=new Set(["image/png","image/jpeg","image/gif","image/webp"]),B=4096;async function he(e,t=fetch,n={}){let r=n.timeoutMs??ge,o=n.maxBytes??Se;try{let i=await t(e,{signal:AbortSignal.timeout(r)});if(!i.ok)return c(`media: HTTP ${i.status} for ${e}`),null;let l=(i.headers.get("content-type")??"").split(";")[0].trim().toLowerCase();if(!ye.has(l))return c(`media: disallowed content-type "${l}" for ${e}`),null;let s=Number(i.headers.get("content-length")??"0");if(Number.isFinite(s)&&s>o)return c(`media: content-length ${s} exceeds ${o} for ${e}`),null;let u=i.body;if(u&&typeof u.getReader=="function"){let d=u.getReader(),I=[],v=0;for(;;){let{done:L,value:h}=await d.read();if(L)break;if(h!==void 0){if(v+=h.byteLength,v>o)return await d.cancel().catch(()=>{}),c(`media: stream exceeded ${o} bytes for ${e}`),null;I.push(h);}}return Buffer.concat(I)}let a=Buffer.from(await i.arrayBuffer());return a.byteLength>o?(c(`media: body ${a.byteLength} bytes exceeds ${o} for ${e}`),null):a}catch(i){return c(`media: fetch failed for ${e}:`,i),null}}function be(e){let t=e.toString("base64");return `${w}]1337;File=inline=1;size=${e.byteLength};width=auto:${t}${me}`}function ke(e){let t=e.toString("base64");if(t.length<=B)return `${w}_Gf=100,a=T;${t}${w}\\`;let n=[];for(let r=0;r<t.length;r+=B){let o=t.slice(r,r+B),l=`m=${r+B>=t.length?0:1}`,s=r===0?`f=100,a=T,${l}`:l;n.push(`${w}_G${s};${o}${w}\\`);}return n.join("")}function x(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 G(e,t={}){try{let n=e.creative;if(n.format!=="image"&&n.format!=="gif")return m(x(e),t);let r=t.protocol??Y();if(r==="none"||n.mediaUrl===void 0||n.mediaUrl==="")return m(x(e),t);let o={};t.timeoutMs!==void 0&&(o.timeoutMs=t.timeoutMs),t.maxBytes!==void 0&&(o.maxBytes=t.maxBytes);let i=await he(n.mediaUrl,t.fetchImpl??fetch,o);return i===null||i.byteLength===0?m(x(e),t):(r==="kitty"?ke(i):be(i))+`
5
- `+m(A(e),t)}catch(n){return c("media: render failed, falling back to text:",n),m(A(e),t)}}function Ce(e,t){return e.filter(n=>n.renderBy>t)}function Z(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 Q(e,t){let n=Ce(e.pool,t),r=n.shift();return {blip:r?r.blip:null,pool:n}}function Te(e=process.env){return C.join(ee.homedir(),".config","opencrater")}function te(e=process.env){return C.join(Te(e),"state.json")}function ne(){return {installId:randomUUID(),lastShownAt:0,optOut:false,disclosureShown:false,cachedConfig:null,configFetchedAt:0,pool:[],allowedPlacements:{},sessionTopics:[],integrations:[],devToken:null,computeRouting:null,computeCards:null}}function g(e){return typeof e=="number"&&Number.isFinite(e)}function Re(e){if(typeof e!="object"||e===null)return null;let t=e;return !g(t.minIntervalSeconds)||!g(t.serveTimeoutMs)||!g(t.preloadPoolSize)||typeof t.killSwitch!="boolean"?null:{minIntervalSeconds:t.minIntervalSeconds,serveTimeoutMs:t.serveTimeoutMs,preloadPoolSize:t.preloadPoolSize,killSwitch:t.killSwitch,displayDurationSeconds:g(t.displayDurationSeconds)?t.displayDurationSeconds:25,minSdkVersion:typeof t.minSdkVersion=="string"?t.minSdkVersion:""}}function Ie(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(!g(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 ve(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 Ee(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"||!g(r.at))&&(t.push({topic:r.topic.slice(0,32),at:r.at}),t.length>=24))break}return t}function Oe(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 Pe(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 Ae(e){if(typeof e!="object"||e===null)return null;let t=e,n=r=>g(r)&&r>=0?r:0;return {turns:n(t.turns),lastLimitAt:n(t.lastLimitAt),lastDepletedAt:n(t.lastDepletedAt),lastBackupAt:n(t.lastBackupAt)}}function Be(e){let t=ne();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:g(n.lastShownAt)&&n.lastShownAt>=0?n.lastShownAt:0,optOut:n.optOut===true,disclosureShown:n.disclosureShown===true,cachedConfig:Re(n.cachedConfig),allowedPlacements:ve(n.allowedPlacements),sessionTopics:Ee(n.sessionTopics),integrations:Oe(n.integrations),devToken:typeof n.devToken=="string"?n.devToken:null,computeRouting:Pe(n.computeRouting),computeCards:Ae(n.computeCards),configFetchedAt:g(n.configFetchedAt)&&n.configFetchedAt>=0?n.configFetchedAt:0,pool:Ie(n.pool)}}function T(e=process.env){let t=te(e);try{let n=p.readFileSync(t,"utf8"),r=JSON.parse(n);return Be(r)}catch{let n=ne();try{S(n,e);}catch{}return n}}function S(e,t=process.env,n={}){let r=te(t),o=C.dirname(r);p.mkdirSync(o,{recursive:true});try{let s=JSON.parse(p.readFileSync(r,"utf8"));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});}catch{}let i=C.join(o,`.state.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`);p.writeFileSync(i,JSON.stringify(e,null,2)+`
6
- `,"utf8");let l=new Set(["EPERM","EACCES","EBUSY","EEXIST"]);for(let s=0;;s++)try{p.renameSync(i,r);return}catch(u){let a=u.code??"";if(s>=4||!l.has(a)){try{p.rmSync(i,{force:!0});}catch{}if(s>=4)return;throw u}try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,15*(s+1));}catch{}}}var xe=["CI","CONTINUOUS_INTEGRATION","GITHUB_ACTIONS","GITLAB_CI","CIRCLECI","TRAVIS","BUILDKITE","JENKINS_URL","TEAMCITY_VERSION","TF_BUILD","APPVEYOR","CODEBUILD_BUILD_ID","DRONE","NETLIFY","VERCEL"];function H(e){return e!==void 0&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}function _e(e){return H(e.OPENCRATER_DISABLE)||H(e.TSN_DISABLE)}function Me(e){return xe.some(t=>H(e[t]))}function z(e){return e?{...b,...e}:b}function R(e,t={}){if(_e(e.env))return "env_disabled";if(e.state.optOut)return "opt_out";let n=z(e.state.cachedConfig);if(n.killSwitch)return "kill_switch";if(Me(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 _(e){try{return await e()}catch(t){return c("suppressed error:",t),null}}function M(e,t){let n=z(t.cachedConfig);return {origin:K(e.apiOrigin),timeoutMs:n.serveTimeoutMs,installId:t.installId,config:n}}function Le(e,t){let n=!t.disclosureShown,r=m(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 oe(e,t){let n=await G(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 $e(e){let t=T(),n=R({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=M(e,t),o=await U(e,r);return o?(S({...t,cachedConfig:o.config,configFetchedAt:Date.now()}),o.fill&&o.blip?o.blip:null):null}async function Fe(e){let t=T(),n=R({env:process.env,isTTY:!!process.stdout.isTTY,state:t,now:Date.now()});if(n!==null)return c("suppressed:",n),false;let r=M(e,t),o=await U(e,r);return o?(t={...t,cachedConfig:o.config,configFetchedAt:Date.now()},o.fill&&o.blip?(t=await oe(o.blip,t),S(t),j(o.blip.impressionId,r),true):o.fallback?(t=Le(J(o.fallback),t),S(t),true):(S(t),false)):false}async function De(e){let t=T(),n=R({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=M(e,t),o=Math.max(1,r.config.preloadPoolSize),i=await q(e,o,r);if(!i)return 0;let l=Date.now(),s=Z(i.blips,l);return S({...t,pool:s,cachedConfig:i.config,configFetchedAt:l}),s.length}async function Ne(e){let t=T(),n=Date.now(),r=R({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}=Q(t,n);if(!o)return S({...t,pool:i}),false;let l=await oe(o,{...t,pool:i});S(l);let s=M(e,t);return j(o.impressionId,s),true}var ct={show(e){return _(()=>Fe(e)).then(t=>t??false)},fetch(e){return _(()=>$e(e))},preload(e){return _(()=>De(e)).then(t=>t??0)},renderFromPool(e){return _(()=>Ne(e)).then(t=>t??false)}};export{b as DEFAULT_CONFIG,re as HOOK_CATALOG,D as SDK_VERSION,Y as detectImageProtocol,G as renderBlip,m as renderCard,ct as sponsor,x as textCardForBlip};
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=[],v=0;for(;;){let{done:N,value:h}=await p.read();if(N)break;if(h!==void 0){if(v+=h.byteLength,v>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 ve(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 Ee(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:ve(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:Ee(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 Le(e){return z(e.OPENCRATER_DISABLE)||z(e.TSN_DISABLE)}function Ne(e){return Me.some(t=>z(e[t]))}function K(e){return e?{...b,...e}:b}function I(e,t={}){if(Le(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(Ne(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 L(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=L(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=L(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=L(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=L(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};
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'),xe=require('os'),j=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 xe__namespace=/*#__PURE__*/_interopNamespace(xe);var j__namespace=/*#__PURE__*/_interopNamespace(j);var pe__namespace=/*#__PURE__*/_interopNamespace(pe);var te=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):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 Me(t,e){let n=e.filter(i=>Number.isFinite(i)&&t-i<6e5&&i<=t);return n.length>=2?{play:false,next:n}:{play:true,next:[...n,t]}}function ne(t=process.env){return j__namespace.join(xe__namespace.homedir(),".config","opencrater")}var cn=600*1e3;function re(){return j__namespace.join(ne(),"blocked-ads.json")}function oe(){return j__namespace.join(ne(),"reported-ads.json")}function ln(t,e){let n={};for(let[i,a]of Object.entries(t))typeof a=="number"&&Number.isFinite(a)&&a>e&&(n[i]=a);return n}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 n=un(e);n[t]=e+cn,ot__namespace.mkdirSync(j__namespace.dirname(re()),{recursive:!0}),ot__namespace.writeFileSync(re(),JSON.stringify(n));}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 n=pn();n[t]=e,ot__namespace.mkdirSync(j__namespace.dirname(oe()),{recursive:!0}),ot__namespace.writeFileSync(oe(),JSON.stringify(n));}catch{}}var dn=[137,80,78,71,13,10,26,10];function Pe(t){try{if(t.length<45)return null;for(let M=0;M<8;M++)if(t[M]!==dn[M])return null;let e=new DataView(t.buffer,t.byteOffset,t.byteLength),n=8,i=0,a=0,u=0,r=-1,d=0,p=[];for(;n+8<=t.length;){let M=e.getUint32(n),D=String.fromCharCode(t[n+4],t[n+5],t[n+6],t[n+7]),B=t.subarray(n+8,n+8+M);if(D==="IHDR")i=e.getUint32(n+8),a=e.getUint32(n+12),u=t[n+16],r=t[n+17],d=t[n+20];else if(D==="IDAT")p.push(B);else if(D==="IEND")break;n+=12+M;}if(u!==8||r!==2&&r!==6||d!==0||i===0||a===0||i>1024||a>1024)return null;let $=r===6?4:3,h=i*$,l=zlib.inflateSync(Buffer.concat(p.map(M=>Buffer.from(M))));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 M=0;M<a;M++){let D=M*(h+1),B=l[D];for(let C=0;C<h;C++){let k=l[D+1+C],b=C>=$?O[C-$]:0,v=I[C],G=C>=$?I[C-$]:0,y;switch(B){case 0:y=k;break;case 1:y=k+b;break;case 2:y=k+v;break;case 3:y=k+(b+v>>1);break;case 4:{let T=b+v-G,X=Math.abs(T-b),Ot=Math.abs(T-v),H=Math.abs(T-G);y=k+(X<=Ot&&X<=H?b:Ot<=H?v:G);break}default:return null}O[C]=y&255;}for(let C=0;C<i;C++){let k=C*$,b=(M*i+C)*4;N[b]=O[k],N[b+1]=O[k+1],N[b+2]=O[k+2],N[b+3]=$===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,_e=25e3,Ge=64,S="\x1B",Cn="\x07",Te=`${S}7`,De=`${S}8`;function Ut(t,e){return `${S}]8;;${t}${S}\\${e}${S}]8;;${S}\\`}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 Mn(t,e){let n=t.split(/\s+/).filter(Boolean),i=[],a="";for(let u of n)if(a===""?a=mt(u,e):a.length+1+u.length<=e?a+=` ${u}`:(i.push(a),a=mt(u,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 xn(t){let e=()=>{try{ot.closeSync(t);}catch{}};return {write:n=>{try{ot.writeSync(t,n);}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($winId -eq 0 -and $b.sz.Y -lt 1000){ $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 Pn(){try{let t=Buffer.from(Rn,"utf16le").toString("base64"),e=He(),n="ignore";if(process.env.OPENCRATER_DEBUG==="1")try{n=ot.openSync(j__namespace.join(xe.homedir(),".config","opencrater","pump-err.log"),"a");}catch{}_("spawning pump:",e);let i=child_process.spawn(e,["-NoProfile","-NonInteractive","-EncodedCommand",t],{stdio:["pipe","pipe",n],windowsHide:!0});i.on("error",d=>_("pump spawn error:",e,"-",d.message)),i.on("exit",d=>_("pump process exited code",d,"pid",i.pid));let a=i.stdin;if(!a)return _("pump: no stdin pipe"),null;a.on("error",()=>{});let u=!1;return i.on("exit",()=>{u=!0;}),{size:new Promise(d=>{let p="",$=!1,h=N=>{$||($=!0,d(N));},l=i.stdout;if(!l)return h(null);l.setEncoding("utf8"),l.on("data",N=>{p+=N;let I=p.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:d=>{try{a.write(d);}catch{}},close:()=>{try{a.end();}catch{}},closeAndWait:()=>new Promise(d=>{if(u)return d();let p=!1,$=()=>{p||(p=!0,d());};i.on("exit",$),setTimeout($,5e3);try{a.end();}catch{$();}})}}catch(t){return _("pump: spawn threw",t.message),null}}function En(t){try{let e=t.replace(/'/g,"''"),n=`$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(n,"utf16le").toString("base64"),a=child_process.spawnSync(He(),["-NoProfile","-NonInteractive","-EncodedCommand",i],{timeout:5e3,encoding:"utf8"}),u=(a.stdout??"").match(/OCPID\s+(\d+)/);return u?Number(u[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 n=j__namespace.join(xe.homedir(),".config","opencrater");ot.mkdirSync(n,{recursive:!0});let i=j__namespace.join(n,`paint-${process.pid}-${Date.now()}.json`);ot.writeFileSync(i,JSON.stringify({...t,_env:process.env}),"utf8");let a=d=>`"${d}"`,u=[a(process.execPath),a(__filename),"--persist","--payload-file",a(i),"--console-pid",String(e)];Wt&&u.push("--debug");let r=En(u.join(" "));return _("escape: wmi persistent painter pid",r),r>0}catch(n){return _("escape failed",n.message),false}}function lr(t){return !!(t.WT_SESSION||t.TERM_PROGRAM||t.ConEmuANSI==="ON"||t.ANSICON)}function _n(){try{let t=child_process.spawnSync("mode",["con"],{timeout:1500,encoding:"utf8"}).stdout;if(!t)return null;let n=[...t.matchAll(/:\s*(\d+)/g)].map(i=>Number(i[1]))[1];return n&&n>0?n:null}catch{return null}}function Tn(t){let e=t.TERM_PROGRAM??"",n=t.TERM??"";return t.TMUX?"none":e==="iTerm.app"||t.LC_TERMINAL==="iTerm2"||e==="WezTerm"?"iterm2":n==="xterm-kitty"||t.KITTY_WINDOW_ID?"kitty":"none"}function Le(t,e){let n=t.toString("base64");return `${S}]1337;File=inline=1;size=${t.length};width=${e.w};height=${e.h};preserveAspectRatio=1:${n}${Cn}`}function Dn(t,e){let n=t.toString("base64"),i=[];for(let u=0;u<n.length;u+=4096)i.push(n.slice(u,u+4096));let a="";for(let u=0;u<i.length;u++){let r=u===0,d=u===i.length-1,p=r?`a=T,f=100,c=${e.w},r=${e.h},m=${d?0:1}`:`m=${d?0:1}`;a+=`${S}_G${p};${i[u]}${S}\\`;}return a}function Ln(t){let e=(t.COLORTERM??"").toLowerCase();if(e.includes("truecolor")||e.includes("24bit"))return true;let n=t.TERM_PROGRAM??"";return ["iTerm.app","WezTerm","vscode","ghostty","Apple_Terminal"].includes(n)}function ae(t,e,n){if(Math.abs(t-e)<12&&Math.abs(e-n)<12&&Math.abs(t-n)<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(n)}var Un=[" ","\u2598","\u259D","\u2580","\u2596","\u258C","\u259E","\u259B","\u2597","\u259A","\u2590","\u259C","\u2584","\u2599","\u259F","\u2588"];function ze(t,e,n,i){let a=[],u=(d,p)=>{let $=(p*e+d)*3;return [t[$],t[$+1],t[$+2]]},r=(d,p)=>{let $=d[0]-p[0],h=d[1]-p[1],l=d[2]-p[2];return $*$+h*h+l*l};for(let d=0;d+1<n;d+=2){let p="",$="";for(let h=0;h+1<e;h+=2){let l=[u(h,d),u(h+1,d),u(h,d+1),u(h+1,d+1)],N=0,I=1,O=-1;for(let y=0;y<4;y++)for(let T=y+1;T<4;T++){let X=r(l[y],l[T]);X>O&&(O=X,N=y,I=T);}let M=0,D=[0,0,0],B=[0,0,0],C=0,k=0;for(let y=0;y<4;y++)r(l[y],l[N])<=r(l[y],l[I])?(M|=1<<y,D[0]+=l[y][0],D[1]+=l[y][1],D[2]+=l[y][2],C++):(B[0]+=l[y][0],B[1]+=l[y][1],B[2]+=l[y][2],k++);if(O<1e3){let y=Ot=>Ot&-8,T=[y(Math.round((l[0][0]+l[1][0]+l[2][0]+l[3][0])/4)),y(Math.round((l[0][1]+l[1][1]+l[2][1]+l[3][1])/4)),y(Math.round((l[0][2]+l[1][2]+l[2][2]+l[3][2])/4))],X=i?`${S}[48;2;${T[0]};${T[1]};${T[2]}m`:`${S}[48;5;${ae(T[0],T[1],T[2])}m`;X!==$&&(p+=X,$=X),p+=" ";continue}let b=C?[Math.round(D[0]/C),Math.round(D[1]/C),Math.round(D[2]/C)]:[0,0,0],v=k?[Math.round(B[0]/k),Math.round(B[1]/k),Math.round(B[2]/k)]:b,G=i?`${S}[38;2;${b[0]};${b[1]};${b[2]};48;2;${v[0]};${v[1]};${v[2]}m`:`${S}[38;5;${ae(b[0],b[1],b[2])};48;5;${ae(v[0],v[1],v[2])}m`;G!==$&&(p+=G,$=G),p+=Un[M];}p+=`${S}[0m`,a.push(p);}return a}function jn(t,e,n,i,a,u){let r=e*2,d=n*2,p=`${u?`${u},`:""}scale=${r}:${d}:flags=lanczos+accurate_rnd`,$=["-y","-i",t];i?$.push("-t","6","-vf",`fps=7,${p}`):$.push("-frames:v","1","-vf",p),$.push("-f","rawvideo","-pix_fmt","rgb24","-");let h=child_process.spawnSync("ffmpeg",$,{timeout:12e3,maxBuffer:64*1024*1024});if(h.status!==0||!h.stdout||h.stdout.length===0)return null;let l=r*d*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),r,d,a));return I}function Wn(t,e,n,i,a,u){if(!et("chafa"))return null;let r=j__namespace.join(e,"fr_%03d.png"),d=["-y","-i",t],p=[];if(a?(d.push("-t","6"),p.push("fps=5")):d.push("-frames:v","1"),u&&p.push(u),p.length>0&&d.push("-vf",p.join(",")),d.push(r),child_process.spawnSync("ffmpeg",d,{timeout:12e3}).status!==0)return null;let h=[];for(let l=1;l<=Ge;l++){let N=j__namespace.join(e,`fr_${String(l).padStart(3,"0")}.png`),I;try{I=child_process.spawnSync("chafa",a?["-f","symbols","-s",`${n}x${i}`,"--stretch","--symbols","vhalf","--colors","full",N]:["-f","symbols","-s",`${n}x${i}`,"--stretch","--colors","full",N],{timeout:5e3,maxBuffer:8*1024*1024,encoding:"utf8"});}catch{break}if(I.status!==0||!I.stdout)break;let M=I.stdout.replace(/\x1b\[\?25[lh]/g,"").split(`
4
- `).filter(k=>k.length>0);if(M.length===0)break;let D=" ".repeat(n),B=Math.floor((i-M.length)/2),C=[];for(let k=0;k<i;k++){let b=M[k-B];if(b===void 0)C.push(D);else {let v=" ".repeat(Math.max(0,n-jt(b)));C.push(b+v);}}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 n=e.stdout.trim().match(/^(\d+),(\d+)/);if(!n)return null;let i=Number(n[1]),a=Number(n[2]);return i>0&&a>0?{w:i,h:a}:null}catch{return null}}function Fn(t){try{let n=(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(!n||n.length===0)return null;let i=n[n.length-1],a=i.match(/crop=(\d+):(\d+):(\d+):(\d+)/),u=Number(a[1]),r=Number(a[2]);if(u<8||r<8)return null;let d=Je(t);if(d){let p=u*r/(d.w*d.h);if(p<.55||p>.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 n=await fetch(t,{signal:AbortSignal.timeout(An)});if(!n.ok)return null;let i=(n.headers.get("content-type")??"").split(";")[0].trim().toLowerCase();if(Number(n.headers.get("content-length")??"0")>e)return null;let u=Buffer.from(await n.arrayBuffer());return u.length===0||u.length>e?null:{data:u,type:i}}catch{return null}}var It=j__namespace.join(xe.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 n=!0;try{process.kill(e.pid,"SIGTERM");}catch{n=!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 u=0;u<e.rows;u++)i+=`\x1B[${e.row+u};${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(j__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(n=>String(n)).join(" ")}`;console.error(e);try{ot.appendFileSync(j__namespace.join(xe.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 n=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"),u=process.env.OPENCRATER_PAINT;if(a)try{u=ot.readFileSync(a,"utf8");}catch(o){_("payload-file unreadable:",o.message);}if(!u){_("no paint payload (env or --payload-file) \u2014 nothing to draw");return}let r;try{let o=JSON.parse(u);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;}r=o;}catch(o){_("paint payload is not valid JSON:",o.message);return}let d=process.env.OPENCRATER_TTY??"/dev/tty",p,$=-1;if(Y){let o=Pn();if(!o){_("Windows: could not start the console pump (powershell.exe)");return}p=o;}else {try{$=ot.openSync(d,"w");}catch(o){_("could not open output device",d,"-",o.message);return}p=xn($);}_("painting via",Y?"Windows console pump":d,"format",r.format??"text"),process.env.OPENCRATER_FLOW!=="1"&&!Y&&je(p);let h=0;if(Y)h=_n()??0;else try{let o=new pe__namespace.WriteStream($);o.columns&&(h=o.columns);}catch{}h||(h=80);let l=process.env.NO_COLOR===void 0,N=l&&Ln(process.env),I=(r.format??"text").toLowerCase(),O=I==="image"||I==="logo",M=I==="gif"||I==="video",D=M?72:56,B=Y?24:40;if(Y)process.stdout.rows&&(B=process.stdout.rows);else try{let o=new pe__namespace.WriteStream(ot.openSync(d,"w"));o.rows&&(B=o.rows);}catch{}let C=M?Math.max(8,Math.min(16,Math.floor((B-14)/2)*2)):vn,k=O?5:C,b=Math.min(D,h-4);if(b<24){p.close();return}let v=b-4,G=Math.max(1,h-b-1),y=2,T=Date.now(),X=l?`${S}[2m`:"",H=l?`${S}[38;5;214m`:"",L=l?`${S}[0m`:"",P=I,kt=Tn(process.env),Mt=process.env.OPENCRATER_FLOW==="1",Ye=process.env.OPENCRATER_MUTE==="1",st=r.apiOrigin??"https://api.opencrater.to",At=P==="video"?`${it("\u25B6")} `:P==="audio"?`${it("\u266A")} `:"",fe=false,de=o=>{if(r.impressionId)try{fetch(`${st}/v1/events/engagement`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({impressionId:r.impressionId,events:o}),signal:AbortSignal.timeout(1500)}).catch(()=>{});}catch{}},rt=null,z=null,xt=0,pt=0,q=null,J="none",Ft=null,Bt=null,at=null,Gt=0,me=0,Z=null,E=0,x=0,Xe=(o,s)=>{let f=o/s,c=O?Math.min(10,Math.floor(v*.35)):v;E=Math.max(4,Math.min(c,Math.round(2*f*k))),x=Math.max(2,Math.min(k,Math.round(c/(2*f))||k)),O&&(x=Math.min(x,k));let m=Math.min(1,o/(E*2),s/(x*2));m<1&&(E=Math.max(8,Math.floor(E*m)),x=Math.max(2,Math.floor(x*m)));},ht=0,qe=()=>{let o=(r.label??"").trim(),s=(r.sponsorLabel??"").trim(),f=s.toLowerCase()===r.title.trim().toLowerCase(),c=o||(s&&!f?`Sponsored Blips \xB7 ${s}`:"Sponsored Blips"),m=[],g=gt??`${st}/x/${r.impressionId}`,w=r.impressionId||r.replay&&gt?Ut(g,it("\u2715")):"",U=ht>0&&!Mt?Math.max(0,Math.ceil((ht-Date.now())/1e3)):0,W=U>0?`Auto dismiss in: ${U}s `:"",R=l?U<=5?`${S}[1;38;5;196m`:U<=12?`${S}[1;38;5;178m`:`${S}[1;38;5;35m`:"",A=mt(c,Math.max(8,v-2-W.length)),F=" ".repeat(Math.max(1,v-A.length-W.length-1));m.push(`${X}${A}${L}${F}${R}${W}${L}${H}${w}${L}`);let Q=l?kt!=="none"||(process.env.COLORTERM??"").includes("truecolor")?`${S}[1;38;2;255;184;48m`:`${S}[1;38;5;214m`:"",tt=O&&x>0?v-E-2:v;O||m.push(""),m.push(`${Q}${mt(r.title.toUpperCase(),tt)}${L}`);for(let V of Mn(r.body,tt))m.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",_t="";for(let Tt=0;Tt<ft;Tt++){let an=J==="playing"?Math.abs(Math.sin(pt*.9+Tt*1.7)*.55+Math.sin(pt*.37+Tt*.53)*.45):.05;_t+=dt[Math.max(0,Math.min(7,Math.floor(an*8)))];}let sn=Ft?Ut(Ft,V):V;m.push(`${it("\u266A")} ${H}${_t}${L} ${H}${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?`${S}[48;2;${ft[0]};${ft[1]};${ft[2]};38;2;${dt[0]};${dt[1]};${dt[2]};1m ${V} ${S}[0m`:`[ ${V} ]`,$t=[240,178,50],Zt=[12,12,10],Qt=r.impressionId?`${st}/k/${r.impressionId}`:r.url,yt=[];if(qt){let V=mt(r.cta&&r.cta.trim()!==""?r.cta:"visit sponsor",v-6-At.length);yt.push(Ut(r.url,Kt(`${At}${V} \u2192`,$t,Zt)));}else {let V=(r.cta&&r.cta.trim()!==""?r.cta.trim():"VISIT").toUpperCase();At.length+V.length+1+Qt.length<=v?yt.push(Kt(`${V} ${At}${Qt}`,$t,Zt)):yt.push(Kt(`${At}${Qt}`,$t,Zt));let ft=process.platform==="darwin"?"\u2318-click":"Ctrl-click",dt=mt(`${it("\u2191")} ${ft} the link to open`,v),_t=l?`${S}[38;2;${$t[0]};${$t[1]};${$t[2]}m`:"";yt.push(`${_t}${dt}${L}`);}let ke=Bt??(r.impressionId?`${st}/r/${r.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 yt.push(`${X}${mt(on,Math.max(0,v-jt(Ae)))}${Ae}${L}`),{head:m,tail:yt}},he=0,ge=()=>{let{head:o,tail:s}=qe(),f=`${H}\u256D${"\u2500".repeat(b-2)}\u256E${L}`,c=`${H}\u2570${"\u2500".repeat(b-2)}\u256F${L}`,m=w=>{let U=" ".repeat(Math.max(0,v-jt(w)));return `${H}\u2502${L} ${w}${U} ${H}\u2502${L}`},g;if(O&&x>0&&(z||rt)){let w=v-E-2,U=o[0]??"",W=o.slice(1),R=z?z[xt%z.length]:null;g=[f,m(U)];let A=Math.max(W.length,x);for(let F=0;F<A;F++){let Q=W[F]??"",tt=" ".repeat(Math.max(0,w-jt(Q))),Xt=F<x&&R?R[F]??" ".repeat(E):" ".repeat(E);g.push(`${H}\u2502${L} ${Q}${tt} ${Xt} ${H}\u2502${L}`);}}else {g=[f,...o.map(m)];let w=Math.max(0,Math.floor((v-E)/2)),U=Math.max(0,v-E-w);if(z&&x>0){let W=z[xt%z.length];for(let R=0;R<x;R++){let A=W[R]??" ".repeat(E);g.push(`${H}\u2502${L} ${" ".repeat(w)}${A}${" ".repeat(U)} ${H}\u2502${L}`);}}else if(rt&&x>0)for(let W=0;W<x;W++)g.push(`${H}\u2502${L} ${" ".repeat(v)} ${H}\u2502${L}`);}return g.push(...s.map(m)),g.push(c),he=s.length+1,g},Ht=0,be=`${S}[?2026h`,$e=`${S}[?2026l`,ye=0,we=2e3,Ze=8,zt=()=>{let o=ge();Ht=Math.max(Ht,o.length),Gn({pid:process.pid,row:y,col:G,width:b,rows:o.length,startedAt:T,...r.impressionId?{impressionId:r.impressionId}:{},...gt?{dismissUrl:gt}:{}});let s=be+Te,f=Date.now()<ye,c=Math.max(1,y-(f?Ze:2));for(let m=c;m<y;m++)s+=`${S}[${m};${G}H${S}[0m${" ".repeat(b)}`;for(let m=0;m<o.length;m++)s+=`${S}[${y+m};${G}H${o[m]}`;if(rt&&pt%(f?1:3)===0&&x>0){let m=O?y+2:y+o.length-he-x,g=O?G+2+(v-E):G+2+Math.max(0,Math.floor((v-E)/2));s+=`${S}[${m};${g}H${rt}`;}return s+=De+$e,pt++,z&&z.length>1&&xt++,s},ct=()=>{p.write(zt());},Se=()=>{let o=be+Te+`${S}[0m`,s=" ".repeat(b);for(let f=0;f<Ht;f++)o+=`${S}[${y+f};${G}H${s}`;o+=De+$e,p.write(o);},lt=null,Rt=null,Pt=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),Pt&&clearInterval(Pt),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,Pt=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,f=()=>{s||(s=true,process.exit(0));};p.closeAndWait().then(f),setTimeout(f,1500).unref?.();return}p.close(),process.exit(0);},Qe=()=>{lt&&clearInterval(lt);let s=E*x>1100?200:Ee;lt=setInterval(ct,z&&z.length>1?s:Lt);},Nt=()=>(Z||(Z=ot.mkdtempSync(j__namespace.join(xe.tmpdir(),"ocpaint-"))),Z),Jt=async()=>{if(r.mediaPixelUrl&&(I==="image"||I==="logo"))try{let R=await fetch(r.mediaPixelUrl,{signal:AbortSignal.timeout(2500)});if(R.ok){let A=Pe(new Uint8Array(await R.arrayBuffer()));if(A&&A.width>=4&&A.height>=2){let F=Buffer.alloc(A.width*A.height*3);for(let Q=0,tt=0;Q<A.rgba.length;Q+=4,tt+=3)F[tt]=A.rgba[Q],F[tt+1]=A.rgba[Q+1],F[tt+2]=A.rgba[Q+2];E=Math.floor(A.width/2),x=Math.floor(A.height/2),z=[ze(F,A.width,A.height,N)];return}}}catch{}if(!r.mediaUrl)return;let o=P==="video",s=await Ue(r.mediaUrl,o?On:Ne);if(!s||!(o?s.type.startsWith("video/"):s.type.startsWith("image/")))return;let c=j__namespace.join(Nt(),"in");try{ot.writeFileSync(c,s.data);}catch{return}let m=Je(c),g=et("ffmpeg")?Fn(c):null,w=g?.match(/crop=(\d+):(\d+)/),U=w?Number(w[1]):m?.w??16,W=w?Number(w[2]):m?.h??9;if(O&&et("ffmpeg")&&U>0&&W>0){let R=Math.min(U,W),A=Math.floor((U-R)/2),F=Math.floor((W-R)/2);g=`crop=${R}:${R}:${A}:${F}`,U=R,W=R,w=null;}if(Xe(U,W),!o&&kt==="iterm2"){rt=Le(s.data,{w:E,h:x}),pt=0;return}if(!o&&kt==="kitty"&&s.type==="image/png"){rt=Dn(s.data,{w:E,h:x}),pt=0;return}if(o&&kt==="iterm2"&&et("ffmpeg"))try{let R=j__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 F=ot.readFileSync(R);if(F.length<=Ne){rt=Le(F,{w:E,h:x}),pt=0;return}}}catch{}if(et("ffmpeg"))try{let R=o||s.type==="image/gif",A=Wn(c,Nt(),E,x,R,g)??jn(c,E,x,R,N,g);A&&A.length>0&&(z=A,xt=0,Qe());}catch{}},Yt=(o=0)=>{if(!at)return;let{kind:s,file:f,vol:c}=at,m=Math.max(0,o/1e3),g,w;s==="afplay"?(g="afplay",w=["-v",c.toFixed(2),f]):s==="ffplay"?(g="ffplay",w=["-nodisp","-autoexit","-volume",String(Math.round(c*100))],m>.2&&w.push("-ss",m.toFixed(2)),w.push(f)):s==="mpv"?(g="mpv",w=["--no-video","--really-quiet",`--volume=${Math.round(c*100)}`],m>.2&&w.push(`--start=${m.toFixed(2)}`),w.push(f)):s==="paplay"?(g="paplay",w=[`--volume=${Math.round(c*65536)}`,f]):(g="mpg123",w=["-q","-f",String(Math.round(32768*c))],m>.2&&w.push("-k",String(Math.round(o/26.12))),w.push(f));try{q=Y?child_process.spawn(g,w,{stdio:"ignore",detached:!0,windowsHide:!0}):child_process.spawn(g,w,{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=r.mediaUrl)=>{if(!o||Ye)return;let s=j__namespace.join(xe.homedir(),".config","opencrater","audio-plays.json");try{let c=[];try{c=JSON.parse(ot.readFileSync(s,"utf8")),Array.isArray(c)||(c=[]);}catch{}let m=Me(Date.now(),c);if(ot.writeFileSync(s,JSON.stringify(m.next)),!m.play)return}catch{}let f=await Ue(o,kn);if(!(!f||!f.type.startsWith("audio/")))try{let c=f.type.includes("wav")?"wav":f.type.includes("ogg")?"ogg":"mp3",m=j__namespace.join(Nt(),`ad.${c}`);ot.writeFileSync(m,f.data);let g=Ce(new Date().getHours());if(et("ffplay"))at={kind:"ffplay",file:m,vol:g,canSeek:!0};else if(!Y&&et("mpv"))at={kind:"mpv",file:m,vol:g,canSeek:!0};else if(process.platform==="darwin"&&et("afplay"))at={kind:"afplay",file:m,vol:g,canSeek:!1};else if(!Y&&et("mpg123")&&c==="mp3")at={kind:"mpg123",file:m,vol:g,canSeek:!0};else if(!Y&&c!=="mp3"&&et("paplay"))at={kind:"paplay",file:m,vol:g,canSeek:!1};else return;Yt(),setTimeout(()=>{try{q?.kill("SIGKILL");}catch{}(J==="playing"||J==="paused")&&(J="ended");},_e).unref?.();}catch{}},ve=()=>{if(!r.impressionId||r.replay)return;let o=j__namespace.join(xe.homedir(),".config","opencrater","dismiss.signal"),s=Date.now();Rt=setInterval(()=>{try{let f=ot.readFileSync(o,"utf8"),c=JSON.parse(f),m=typeof c.at=="number"&&c.at>=s-5e3,g=!c.impressionId||c.impressionId===r.impressionId;if(m&&g){try{ot.unlinkSync(o);}catch{}Dt(r.campaignId),fetch(`${st}/x/${r.impressionId}`,{signal:AbortSignal.timeout(1500)}).catch(()=>{}),K(!0);return}}catch{}(async()=>{try{let f=await fetch(`${st}/v1/events/dismissed/${r.impressionId}`,{signal:AbortSignal.timeout(1200)});if(!f.ok)return;(await f.json()).dismissed&&(Dt(r.campaignId),K(!0));}catch{}})();},In);},Ie=()=>{if(Mt)return;let o=j__namespace.join(xe.homedir(),".config","opencrater","activity.signal"),s=Date.now(),f=1500;Pt=setInterval(()=>{try{let c=ot.statSync(o).mtimeMs;c>s+f&&c>Date.now()-we&&(ye=c+we,ct());}catch{}},150);};if(Y){(async()=>{let o=p.size?await p.size:null;if(o&&o.cols>=24&&(h=o.cols,b=Math.min(D,h-4),v=b-4,G=Math.max(1,h-b-1),_("windows geometry from pump:","cols",h,"width",b,"col",G,"ownerPid",o.pid)),P==="image"||P==="logo"||P==="gif"||P==="video"?await Jt():P==="audio"&&await bt(),r.audioUrl&&P!=="audio"&&bt(r.audioUrl),n){let g=Math.min(Math.max(r.durationMs??se,3e3),12e4);if(ht=Date.now()+g,a)try{ot.unlinkSync(a);}catch{}je(p);let w=z,U=!!(w&&w.length>1);ct(),lt=setInterval(ct,U?Ee:Lt),Ie(),Oe(),ve(),process.on("SIGINT",()=>K(true)),process.on("SIGHUP",()=>K(true)),setTimeout(()=>K(true),g);return}let s=o?.pid??0;r.host!=="copilot_cli"?s>0&&Nn(r,s)?(p.close(),process.exit(0)):_("no job-escape (ownerPid",s,") \u2014 bounded toast fallback"):_("host=copilot_cli \u2014 skipping WMI escape, using in-job toast");let c=Number(process.env.OPENCRATER_WIN_HOLD_MS),m=c>0?c:Math.min(r.durationMs??se,5e3);if(ht=Date.now()+m,p.write(zt()),await new Promise(g=>{let w=setInterval(()=>{if(Date.now()>=ht){clearInterval(w),g();return}p.write(zt());},Lt);}),Se(),Z)try{ot.rmSync(Z,{recursive:!0,force:!0});}catch{}await p.closeAndWait(),process.exit(0);})();return}if(Mt){(async()=>{P==="image"||P==="logo"||P==="gif"||P==="video"?await Jt():P==="audio"&&await bt(),r.audioUrl&&P!=="audio"&&bt(r.audioUrl);let o=z;o&&o.length>1&&(z=[o[0]]);let s=ge(),f=" ".repeat(Math.max(0,h-b-2)),c=`\r
6
- `;for(let g of s)c+=`${f}${g}\r
7
- `;rt&&x>0&&(c+=`${f}${rt}\r
8
- `),p.write(c);let m=q?_e+1e3:250;setTimeout(()=>{if(q)try{q.kill("SIGKILL");}catch{}if(Z)try{ot.rmSync(Z,{recursive:!0,force:!0});}catch{}p.close(),process.exit(0);},m);})();return}ct(),lt=setInterval(ct,Lt);function Oe(){if(!(!r.impressionId&&!r.replay||Mt))try{let o=crypto.randomBytes(8).toString("hex"),s=Fe__namespace.createServer((f,c)=>{if(!f.url||!f.url.includes(o)){c.writeHead(404).end();return}if(f.url.startsWith("/p/")){Re(r.campaignId),r.impressionId?(c.writeHead(302,{location:`${st}/r/${r.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(f.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(r.campaignId),!r.replay&&r.impressionId&&fetch(`${st}/x/${r.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"&&(gt=`http://127.0.0.1:${f.port}/x/${o}`,Ft=`http://127.0.0.1:${f.port}/a/${o}`,Bt=`http://127.0.0.1:${f.port}/p/${o}`,Et=s,ct());}),s.on("error",()=>{gt=null,Bt=null;});}catch{}}try{ot.writeFileSync(j__namespace.join(xe.homedir(),".config","opencrater","last-ad.json"),JSON.stringify({payload:r,at:Date.now()}));}catch{}Oe(),ve(),Ie(),P==="image"||P==="logo"||P==="gif"||P==="video"?Jt():P==="audio"&&bt(),r.audioUrl&&P!=="audio"&&bt(r.audioUrl);let Vt=r.durationMs??(P==="video"?18e3:P==="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();
2
+ 'use strict';var child_process=require('child_process'),crypto=require('crypto'),Fe=require('http'),ot=require('fs'),Re=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 Re__namespace=/*#__PURE__*/_interopNamespace(Re);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,n)=>(typeof require<"u"?require:e)[n]}):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 n=e.filter(i=>Number.isFinite(i)&&t-i<6e5&&i<=t);return n.length>=2?{play:false,next:n}:{play:true,next:[...n,t]}}function ne(t=process.env){return U__namespace.join(Re__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 n={};for(let[i,a]of Object.entries(t))typeof a=="number"&&Number.isFinite(a)&&a>e&&(n[i]=a);return n}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 n=un(e);n[t]=e+cn,ot__namespace.mkdirSync(U__namespace.dirname(re()),{recursive:!0}),ot__namespace.writeFileSync(re(),JSON.stringify(n));}catch{}}function pn(){try{let t=JSON.parse(ot__namespace.readFileSync(oe(),"utf8"));return t&&typeof t=="object"?t:{}}catch{return {}}}function Me(t,e=Date.now()){if(t)try{let n=pn();n[t]=e,ot__namespace.mkdirSync(U__namespace.dirname(oe()),{recursive:!0}),ot__namespace.writeFileSync(oe(),JSON.stringify(n));}catch{}}var dn=[137,80,78,71,13,10,26,10];function Pe(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),n=8,i=0,a=0,p=0,r=-1,m=0,d=[];for(;n+8<=t.length;){let x=e.getUint32(n),D=String.fromCharCode(t[n+4],t[n+5],t[n+6],t[n+7]),F=t.subarray(n+8,n+8+x);if(D==="IHDR")i=e.getUint32(n+8),a=e.getUint32(n+12),p=t[n+16],r=t[n+17],m=t[n+20];else if(D==="IDAT")d.push(F);else if(D==="IEND")break;n+=12+x;}if(p!==8||r!==2&&r!==6||m!==0||i===0||a===0||i>1024||a>1024)return null;let $=r===6?4:3,h=i*$,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>=$?O[C-$]:0,S=I[C],B=C>=$?I[C-$]:0,y;switch(F){case 0:y=k;break;case 1:y=k+b;break;case 2:y=k+S;break;case 3:y=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);y=k+(X<=Ot&&X<=G?b:Ot<=G?S:B);break}default:return null}O[C]=y&255;}for(let C=0;C<i;C++){let k=C*$,b=(x*i+C)*4;N[b]=O[k],N[b+1]=O[k+1],N[b+2]=O[k+2],N[b+3]=$===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 Wt(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 n=t.split(/\s+/).filter(Boolean),i=[],a="";for(let p of n)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 Rn(t){let e=()=>{try{ot.closeSync(t);}catch{}};return {write:n=>{try{ot.writeSync(t,n);}catch{}},close:e,closeAndWait:async()=>e()}}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 He(){return `${process.env.SystemRoot||process.env.windir||"C:\\Windows"}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`}function Pn(){try{let t=Buffer.from(Mn,"utf16le").toString("base64"),e=He(),n="ignore";if(process.env.OPENCRATER_DEBUG==="1")try{n=ot.openSync(U__namespace.join(Re.homedir(),".config","opencrater","pump-err.log"),"a");}catch{}_("spawning pump:",e);let i=child_process.spawn(e,["-NoProfile","-NonInteractive","-EncodedCommand",t],{stdio:["pipe","pipe",n],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="",$=!1,h=N=>{$||($=!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,$=()=>{d||(d=!0,m());};i.on("exit",$),setTimeout($,5e3);try{a.end();}catch{$();}})}}catch(t){return _("pump: spawn threw",t.message),null}}function En(t){try{let e=t.replace(/'/g,"''"),n=`$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(n,"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 n=U__namespace.join(Re.homedir(),".config","opencrater");ot.mkdirSync(n,{recursive:!0});let i=U__namespace.join(n,`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)];jt&&p.push("--debug");let r=En(p.join(" "));return _("escape: wmi persistent painter pid",r),r>0}catch(n){return _("escape failed",n.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 n=[...t.matchAll(/:\s*(\d+)/g)].map(i=>Number(i[1]))[1];return n&&n>0?n:null}catch{return null}}function _n(t){let e=t.TERM_PROGRAM??"",n=t.TERM??"";return t.TMUX?"none":e==="iTerm.app"||t.LC_TERMINAL==="iTerm2"||e==="WezTerm"?"iterm2":n==="xterm-kitty"||t.KITTY_WINDOW_ID?"kitty":"none"}function Le(t,e){let n=t.toString("base64");return `${w}]1337;File=inline=1;size=${t.length};width=${e.w};height=${e.h};preserveAspectRatio=1:${n}${Cn}`}function Dn(t,e){let n=t.toString("base64"),i=[];for(let p=0;p<n.length;p+=4096)i.push(n.slice(p,p+4096));let a="";for(let p=0;p<i.length;p++){let r=p===0,m=p===i.length-1,d=r?`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 n=t.TERM_PROGRAM??"";return ["iTerm.app","WezTerm","vscode","ghostty","Apple_Terminal"].includes(n)}function ae(t,e,n){if(Math.abs(t-e)<12&&Math.abs(e-n)<12&&Math.abs(t-n)<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(n)}var Un=[" ","\u2598","\u259D","\u2580","\u2596","\u258C","\u259E","\u259B","\u2597","\u259A","\u2590","\u259C","\u2584","\u2599","\u259F","\u2588"];function ze(t,e,n,i){let a=[],p=(m,d)=>{let $=(d*e+m)*3;return [t[$],t[$+1],t[$+2]]},r=(m,d)=>{let $=m[0]-d[0],h=m[1]-d[1],l=m[2]-d[2];return $*$+h*h+l*l};for(let m=0;m+1<n;m+=2){let d="",$="";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 y=0;y<4;y++)for(let T=y+1;T<4;T++){let X=r(l[y],l[T]);X>O&&(O=X,N=y,I=T);}let x=0,D=[0,0,0],F=[0,0,0],C=0,k=0;for(let y=0;y<4;y++)r(l[y],l[N])<=r(l[y],l[I])?(x|=1<<y,D[0]+=l[y][0],D[1]+=l[y][1],D[2]+=l[y][2],C++):(F[0]+=l[y][0],F[1]+=l[y][1],F[2]+=l[y][2],k++);if(O<1e3){let y=Ot=>Ot&-8,T=[y(Math.round((l[0][0]+l[1][0]+l[2][0]+l[3][0])/4)),y(Math.round((l[0][1]+l[1][1]+l[2][1]+l[3][1])/4)),y(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!==$&&(d+=X,$=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!==$&&(d+=B,$=B),d+=Un[x];}d+=`${w}[0m`,a.push(d);}return a}function Wn(t,e,n,i,a,p){let r=e*2,m=n*2,d=`${p?`${p},`:""}scale=${r}:${m}:flags=lanczos+accurate_rnd`,$=["-y","-i",t];i?$.push("-t","6","-vf",`fps=7,${d}`):$.push("-frames:v","1","-vf",d),$.push("-f","rawvideo","-pix_fmt","rgb24","-");let h=child_process.spawnSync("ffmpeg",$,{timeout:12e3,maxBuffer:64*1024*1024});if(h.status!==0||!h.stdout||h.stdout.length===0)return null;let l=r*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),r,m,a));return I}function jn(t,e,n,i,a,p){if(!et("chafa"))return null;let r=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(r),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",`${n}x${i}`,"--stretch","--symbols","vhalf","--colors","full",N]:["-f","symbols","-s",`${n}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(n),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,n-Wt(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 n=e.stdout.trim().match(/^(\d+),(\d+)/);if(!n)return null;let i=Number(n[1]),a=Number(n[2]);return i>0&&a>0?{w:i,h:a}:null}catch{return null}}function Fn(t){try{let n=(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(!n||n.length===0)return null;let i=n[n.length-1],a=i.match(/crop=(\d+):(\d+):(\d+):(\d+)/),p=Number(a[1]),r=Number(a[2]);if(p<8||r<8)return null;let m=Je(t);if(m){let d=p*r/(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 n=await fetch(t,{signal:AbortSignal.timeout(An)});if(!n.ok)return null;let i=(n.headers.get("content-type")??"").split(";")[0].trim().toLowerCase();if(Number(n.headers.get("content-length")??"0")>e)return null;let p=Buffer.from(await n.arrayBuffer());return p.length===0||p.length>e?null:{data:p,type:i}}catch{return null}}var It=U__namespace.join(Re.homedir(),".config","opencrater","painter.lock"),Bn=6e3;function We(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 n=!0;try{process.kill(e.pid,"SIGTERM");}catch{n=!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 je="";function Gn(t){let e=JSON.stringify(t);if(e!==je){je=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 jt=process.env.OPENCRATER_DEBUG==="1";function _(...t){try{if(!jt)return;let e=`[opencrater-paint] ${t.map(n=>String(n)).join(" ")}`;console.error(e);try{ot.appendFileSync(U__namespace.join(Re.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")&&(jt=true,process.env.OPENCRATER_DEBUG="1");let n=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 r;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"&&(jt=!0),delete o._env;}r=o;}catch(o){_("paint payload is not valid JSON:",o.message);return}let m=process.env.OPENCRATER_TTY??"/dev/tty",d,$=-1;if(Y){let o=Pn();if(!o){_("Windows: could not start the console pump (powershell.exe)");return}d=o;}else {try{$=ot.openSync(m,"w");}catch(o){_("could not open output device",m,"-",o.message);return}d=Rn($);}_("painting via",Y?"Windows console pump":m,"format",r.format??"text"),process.env.OPENCRATER_FLOW!=="1"&&!Y&&We(d);let h=0;if(Y)h=Tn()??0;else try{let o=new pe__namespace.WriteStream($);o.columns&&(h=o.columns);}catch{}h||(h=80);let l=process.env.NO_COLOR===void 0,N=l&&Ln(process.env),I=(r.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),y=2,T=Date.now(),X=l?`${w}[2m`:"",G=l?`${w}[38;5;214m`:"",L=l?`${w}[0m`:"",P=I,kt=_n(process.env),xt=process.env.OPENCRATER_FLOW==="1",Ye=process.env.OPENCRATER_MUTE==="1",st=r.apiOrigin??"https://api.opencrater.to",At=P==="video"?`${it("\u25B6")} `:P==="audio"?`${it("\u266A")} `:"",fe=false,de=o=>{if(r.impressionId)try{fetch(`${st}/v1/events/engagement`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({impressionId:r.impressionId,events:o}),signal:AbortSignal.timeout(1500)}).catch(()=>{});}catch{}},rt=null,H=null,Rt=0,pt=0,q=null,J="none",Ft=null,Bt=null,at=null,Gt=0,me=0,Z=null,E=0,R=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))),R=Math.max(2,Math.min(k,Math.round(c/(2*u))||k)),O&&(R=Math.min(R,k));let f=Math.min(1,o/(E*2),s/(R*2));f<1&&(E=Math.max(8,Math.floor(E*f)),R=Math.max(2,Math.floor(R*f)));},ht=0,qe=()=>{let o=(r.label??"").trim(),s=(r.sponsorLabel??"").trim(),u=s.toLowerCase()===r.title.trim().toLowerCase(),c=o||(s&&!u?`Sponsored Blips \xB7 ${s}`:"Sponsored Blips"),f=[],g=gt??`${st}/x/${r.impressionId}`,v=r.impressionId||r.replay&&gt?Ut(g,it("\u2715")):"",z=ht>0&&!xt?Math.max(0,Math.ceil((ht-Date.now())/1e3)):0,W=z>0?`Auto dismiss in: ${z}s `:"",M=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-W.length)),j=" ".repeat(Math.max(1,S-A.length-W.length-1));f.push(`${X}${A}${L}${j}${M}${W}${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&&R>0?S-E-2:S;O||f.push(""),f.push(`${Q}${mt(r.title.toUpperCase(),tt)}${L}`);for(let V of xn(r.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} ]`,$t=[240,178,50],Zt=[12,12,10],Qt=r.impressionId?`${st}/k/${r.impressionId}`:r.url,yt=[];if(qt){let V=mt(r.cta&&r.cta.trim()!==""?r.cta:"visit sponsor",S-6-At.length);yt.push(Ut(r.url,Kt(`${At}${V} \u2192`,$t,Zt)));}else {let V=(r.cta&&r.cta.trim()!==""?r.cta.trim():"VISIT").toUpperCase();At.length+V.length+1+Qt.length<=S?yt.push(Kt(`${V} ${At}${Qt}`,$t,Zt)):yt.push(Kt(`${At}${Qt}`,$t,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;${$t[0]};${$t[1]};${$t[2]}m`:"";yt.push(`${Tt}${dt}${L}`);}let ke=Bt??(r.impressionId?`${st}/r/${r.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 yt.push(`${X}${mt(on,Math.max(0,S-Wt(Ae)))}${Ae}${L}`),{head:f,tail:yt}},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-Wt(v)));return `${G}\u2502${L} ${v}${z} ${G}\u2502${L}`},g;if(O&&R>0&&(H||rt)){let v=S-E-2,z=o[0]??"",W=o.slice(1),M=H?H[Rt%H.length]:null;g=[u,f(z)];let A=Math.max(W.length,R);for(let j=0;j<A;j++){let Q=W[j]??"",tt=" ".repeat(Math.max(0,v-Wt(Q))),Xt=j<R&&M?M[j]??" ".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&&R>0){let W=H[Rt%H.length];for(let M=0;M<R;M++){let A=W[M]??" ".repeat(E);g.push(`${G}\u2502${L} ${" ".repeat(v)}${A}${" ".repeat(z)} ${G}\u2502${L}`);}}else if(rt&&R>0)for(let W=0;W<R;W++)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`,$e=`${w}[?2026l`,ye=0,we=2e3,Ze=8,zt=()=>{let o=ge();Ht=Math.max(Ht,o.length),Gn({pid:process.pid,row:y,col:B,width:b,rows:o.length,startedAt:T,...r.impressionId?{impressionId:r.impressionId}:{},...gt?{dismissUrl:gt}:{}});let s=be+_e,u=Date.now()<ye,c=Math.max(1,y-(u?Ze:2));for(let f=c;f<y;f++)s+=`${w}[${f};${B}H${w}[0m${" ".repeat(b)}`;for(let f=0;f<o.length;f++)s+=`${w}[${y+f};${B}H${o[f]}`;if(rt&&pt%(u?1:3)===0&&R>0){let f=O?y+2:y+o.length-he-R,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+$e,pt++,H&&H.length>1&&Rt++,s},ct=()=>{d.write(zt());},Se=()=>{let o=be+_e+`${w}[0m`,s=" ".repeat(b);for(let u=0;u<Ht;u++)o+=`${w}[${y+u};${B}H${s}`;o+=De+$e,d.write(o);},lt=null,Mt=null,Pt=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),Mt&&clearInterval(Mt),Pt&&clearInterval(Pt),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,Mt=null,Pt=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*R>1100?200:Ee;lt=setInterval(ct,H&&H.length>1?s:Lt);},Nt=()=>(Z||(Z=ot.mkdtempSync(U__namespace.join(Re.tmpdir(),"ocpaint-"))),Z),Jt=async()=>{if(r.mediaPixelUrl&&(I==="image"||I==="logo"))try{let M=await fetch(r.mediaPixelUrl,{signal:AbortSignal.timeout(2500)});if(M.ok){let A=Pe(new Uint8Array(await M.arrayBuffer()));if(A&&A.width>=4&&A.height>=2){let j=Buffer.alloc(A.width*A.height*3);for(let Q=0,tt=0;Q<A.rgba.length;Q+=4,tt+=3)j[tt]=A.rgba[Q],j[tt+1]=A.rgba[Q+1],j[tt+2]=A.rgba[Q+2];E=Math.floor(A.width/2),R=Math.floor(A.height/2),H=[ze(j,A.width,A.height,N)];return}}}catch{}if(!r.mediaUrl)return;let o=P==="video",s=await Ue(r.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,W=v?Number(v[2]):f?.h??9;if(O&&et("ffmpeg")&&z>0&&W>0){let M=Math.min(z,W),A=Math.floor((z-M)/2),j=Math.floor((W-M)/2);g=`crop=${M}:${M}:${A}:${j}`,z=M,W=M,v=null;}if(Xe(z,W),!o&&kt==="iterm2"){rt=Le(s.data,{w:E,h:R}),pt=0;return}if(!o&&kt==="kitty"&&s.type==="image/png"){rt=Dn(s.data,{w:E,h:R}),pt=0;return}if(o&&kt==="iterm2"&&et("ffmpeg"))try{let M=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",M],{timeout:12e3}).status===0){let j=ot.readFileSync(M);if(j.length<=Ne){rt=Le(j,{w:E,h:R}),pt=0;return}}}catch{}if(et("ffmpeg"))try{let M=o||s.type==="image/gif",A=jn(c,Nt(),E,R,M,g)??Wn(c,E,R,M,N,g);A&&A.length>0&&(H=A,Rt=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=r.mediaUrl)=>{if(!o||Ye)return;let s=U__namespace.join(Re.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(!r.impressionId||r.replay)return;let o=U__namespace.join(Re.homedir(),".config","opencrater","dismiss.signal"),s=Date.now();Mt=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===r.impressionId;if(f&&g){try{ot.unlinkSync(o);}catch{}Dt(r.campaignId),fetch(`${st}/x/${r.impressionId}`,{signal:AbortSignal.timeout(1500)}).catch(()=>{}),K(!0);return}}catch{}(async()=>{try{let u=await fetch(`${st}/v1/events/dismissed/${r.impressionId}`,{signal:AbortSignal.timeout(1200)});if(!u.ok)return;(await u.json()).dismissed&&(Dt(r.campaignId),K(!0));}catch{}})();},In);},Ie=()=>{if(xt)return;let o=U__namespace.join(Re.homedir(),".config","opencrater","activity.signal"),s=Date.now(),u=1500;Pt=setInterval(()=>{try{let c=ot.statSync(o).mtimeMs;c>s+u&&c>Date.now()-we&&(ye=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)),P==="image"||P==="logo"||P==="gif"||P==="video"?await Jt():P==="audio"&&await bt(),r.audioUrl&&P!=="audio"&&bt(r.audioUrl),n){let f=Math.min(Math.max(r.durationMs??se,3e3),12e4);if(ht=Date.now()+f,a)try{ot.unlinkSync(a);}catch{}We(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(r,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(r.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()=>{P==="image"||P==="logo"||P==="gif"||P==="video"?await Jt():P==="audio"&&await bt(),r.audioUrl&&P!=="audio"&&bt(r.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&&R>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(!(!r.impressionId&&!r.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/")){Me(r.campaignId),r.impressionId?(c.writeHead(302,{location:`${st}/r/${r.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(r.campaignId),!r.replay&&r.impressionId&&fetch(`${st}/x/${r.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(Re.homedir(),".config","opencrater","last-ad.json"),JSON.stringify({payload:r,at:Date.now()}));}catch{}Oe(),ve(),Ie(),P==="image"||P==="logo"||P==="gif"||P==="video"?Jt():P==="audio"&&bt(),r.audioUrl&&P!=="audio"&&bt(r.audioUrl);let Vt=r.durationMs??(P==="video"?18e3:P==="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
9
  exports.windowsVtOk=lr;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencrater",
3
- "version": "1.1.22",
3
+ "version": "1.1.24",
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",